kawa.texi 903 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679
  1. \input texinfo.tex @c -*-texinfo-*-
  2. @c %**start of header
  3. @setfilename kawa.info
  4. @documentencoding UTF-8
  5. @settitle The Kawa Scheme language
  6. @setchapternewpage off
  7. @syncodeindex fn cp
  8. @syncodeindex vr cp
  9. @syncodeindex pg cp
  10. @codequoteundirected on
  11. @codequotebacktick on
  12. @c version: %W% %G%
  13. @c %**end of header
  14. @macro false{}
  15. @code{#f}
  16. @end macro
  17. @macro true{}
  18. @code{#t}
  19. @end macro
  20. @macro func{NAME}
  21. @code{\NAME\}
  22. @end macro
  23. @macro stxdef{NAME}
  24. @findex @i{\NAME\}
  25. @anchor{meta-\NAME\}@var{\NAME\} @t{::=}
  26. @end macro
  27. @ifnotinfo
  28. @ifnottex
  29. @macro stxref{NAME}
  30. @ref{meta-\NAME\, @var{\NAME\}, @var{\NAME\}}
  31. @end macro
  32. @end ifnottex
  33. @end ifnotinfo
  34. @ifinfo
  35. @macro stxref{NAME}
  36. @var{\NAME\}
  37. @end macro
  38. @end ifinfo
  39. @iftex
  40. @macro stxref{NAME}
  41. @var{\NAME\}
  42. @end macro
  43. @end iftex
  44. @macro stxlit{TEXT}
  45. @code{@b{\TEXT\}}
  46. @end macro
  47. @macro stxlitlbrace{TEXT}
  48. @code{@b{@{}}
  49. @end macro
  50. @macro arbno{THING}
  51. \THING\@sup{*}
  52. @end macro
  53. @c maybe use \x2217
  54. @c \THING\ @var{...}
  55. @macro atleastone{THING}
  56. \THING\@sup{+}
  57. @end macro
  58. @macro meta{THING}
  59. @var{\THING\}
  60. @end macro
  61. @macro PerformanceNote
  62. @emph{Performance note:}
  63. @end macro
  64. @macro CompatibilityNote
  65. @emph{Compatibility:}
  66. @end macro
  67. @ifinfo
  68. @macro vari{THING}
  69. @var{\THING\1}
  70. @end macro
  71. @macro varii{THING}
  72. @var{\THING\2}
  73. @end macro
  74. @macro variii{THING}
  75. @var{\THING\3}
  76. @end macro
  77. @macro variv{THING}
  78. @var{\THING\4}
  79. @end macro
  80. @end ifinfo
  81. @ifnotinfo
  82. @macro vari{THING}
  83. @var{\THING\}@sub{1}
  84. @end macro
  85. @macro varii{THING}
  86. @var{\THING\}@sub{2}
  87. @end macro
  88. @macro variii{THING}
  89. @var{\THING\}@sub{3}
  90. @end macro
  91. @macro variv{THING}
  92. @var{\THING\}@sub{4}
  93. @end macro
  94. @end ifnotinfo
  95. @include version.texi
  96. @iftex
  97. @finalout
  98. @end iftex
  99. @titlepage
  100. @title The Kawa Scheme language
  101. @subtitle @value{UPDATED}
  102. @sp 1
  103. @author Per Bothner
  104. @page
  105. @end titlepage
  106. @contents
  107. @ifinfo
  108. @format
  109. START-INFO-DIR-ENTRY
  110. * kawa: (kawa). The Kawa Scheme language
  111. END-INFO-DIR-ENTRY
  112. @end format
  113. @end ifinfo
  114. @ifnottex
  115. @node Top, Installation, (dir), (dir)
  116. @top The Kawa Scheme language
  117. @end ifnottex
  118. @c Kawa is best known as an implementation of the
  119. @c @uref{http://www.schemers.org/,Scheme language} for the Java platform.
  120. @c It compiles Scheme to high-performance Java bytecodes.
  121. @c It is also a general framework for implementing dynamic languages,
  122. @c and includes a full implementation of XQuery and the beginnings of
  123. @c implementations of Common Lisp and Emacs Lisp (JEmacs).
  124. Kawa is a general-purpose programming language that runs on the Java platform.
  125. It aims to combine:
  126. @itemize
  127. @item
  128. the benefits of dynamic scripting languages
  129. (non-verbose code with less boiler-plate, fast and easy start-up,
  130. a @uref{http://en.wikipedia.org/wiki/Read-eval-print_loop,REPL},
  131. no required compilation step); with
  132. @item
  133. the benefits of traditional compiled languages (fast execution, static error detection,
  134. modularity, zero-overhead Java platform integration).
  135. @end itemize
  136. It is an extension of the long-established @uref{http://www.schemers.org/,Scheme}
  137. language, which is in the Lisp family of programming languages.
  138. Kawa has many @ref{Features,useful features}.
  139. Kawa is also a useful @ref{Framework,framework} for implementing
  140. other programming languages on the Java platform.
  141. It has many useful utility classes.
  142. This manual describes version @value{VERSION}, updated @value{UPDATED}.
  143. See the summary of @ref{News,recent changes}.
  144. @c Old versions of makeinfo don't support: @ifnotdocbook
  145. The Kawa home page (which is currently just an on-line
  146. version of this document) is @uref{http://www.gnu.org/software/kawa/}.
  147. @c (blank line needed above) @end ifnotdocbook
  148. The @ref{Tutorial,Kawa tutorial} is useful to get stated.
  149. While it is woefully incomplete, it does link to some other more in-depth
  150. (but not Kawa-specific) Scheme tutorials.
  151. For copyright information on the software and documentation,
  152. see @ref{License}.
  153. Various people and orgnizations @ref{Acknowledgements,have contributed to Kawa}.
  154. This package has nothing to do with the defunct Kawa commercial Java IDE.
  155. @menu
  156. * News:: News - Recent Changes
  157. * Features::
  158. * Community::
  159. * Installation:: Building and installing Kawa
  160. * Tutorial:: Kawa Scheme Tutorial
  161. * Running:: Invoking, Running, and Using Kawa
  162. * Syntax::
  163. * Program structure::
  164. * Control features::
  165. * Symbols and namespaces::
  166. * Procedures::
  167. * Numbers:: Quantities and Numbers
  168. * Characters and text::
  169. * Data structures::
  170. * Eval and Environments::
  171. * Debugging::
  172. * Input-Output:: Input, output, and file handling
  173. * Types::
  174. * Objects Classes and Modules::
  175. * XML tools:: XML, HTML, and the web
  176. * Miscellaneous::
  177. * FAQs:: Frequently Asked Questions
  178. * Framework:: The Kawa language framework
  179. * License::
  180. * Overall Index:: Index of functions, macros, concepts, and more.
  181. @end menu
  182. @node News
  183. @chapter News - Recent Changes
  184. @include news.texi
  185. @node Features
  186. @chapter Features
  187. Runs on the Java platform, with no native code needed.
  188. Extends the @uref{http://en.wikipedia.org/wiki/Scheme_%28programming_language%29,Scheme language}, following the @uref{http://r7rs.org/,R7RS} specification from 2013.
  189. Scheme has many implementations, and is much used in research and teaching.
  190. Programs @uref{http://per.bothner.com/blog/2010/Kawa-in-shootout/, run fast}
  191. - roughly as fast as Java programs,
  192. and much faster than other ``scripting languages''.
  193. This is due to a sophisticated compiler,
  194. compile-time transformations, type inference, and optional type declarations.
  195. Full, convenient, and efficient access to the huge set of Java libraries
  196. means you can access objects, methods, fields, and classes without run-time overhead.
  197. Start-up times are fast. You don't have to wait for a lot of
  198. initialization. Even if you start with source code, the parser
  199. and compiler are fast.
  200. @ref{Scripts} are simple Kawa source files
  201. that can run as an application or command. These are simple to write,
  202. start, and run efficiently, since they're automatically
  203. compiled before execution.
  204. Alternatively, you can embed Kawa as a @ref{Evaluating Scheme expressions from Java,
  205. scripting language for Java applications}.
  206. Deployment is easy and flexible. You just need the Kawa jar file.
  207. @ref{Macros} and @ref{Named quasi-literals,custom named literals} make it easy
  208. to extend the syntax and implement Domain-Specific Languages.
  209. Kawa provides the usual @ref{REPL Console,read-eval-print loop}, as well as batch modes.
  210. Kawa has builtin @ref{Pretty-printing,pretty-printer} support, and fancy formatting.
  211. Kawa supports class-definition facilities, and separately-compiled modules.
  212. You can @ref{Allocating objects,allocate and initialize objects}
  213. with a compact ``builder'' syntax. It works out-of-the-box
  214. (with no run-time overhead) on many classes and APIs,
  215. but can be customized if need be.
  216. A library for functional @ref{Composable pictures,composable pictures}
  217. lets you create ``picture'' objects,
  218. display them, transform them, combine them, convert to
  219. SVG or images, and more.
  220. This can be ``printed'' directly in the Kawa console
  221. (either the DomTerm console or the Swing one).
  222. @ref{Building JavaFX applications,JavaFX programming} is simpler.
  223. You can @ref{Building for Android,run Kawa programs on Android},
  224. and there is special handling to make @ref{Android view construction,constructing View objects} easier.
  225. Flexible shell-like functionality, including @ref{process literals}.
  226. @ref{Server-side scripts,Web page scripts} are easy to write and install
  227. with @ref{Self-configuring page scripts,self-configuring web servers},
  228. optionally using @ref{Servlets,servlets} and @ref{XML literals}.
  229. @ref{Arrays} and sequences have a lot of flexibility:
  230. Arrays can be multi-dimensional;
  231. you can use an array as an index (which generalizes slices and permutations);
  232. you can define a lazy array using a function that maps indexes to values;
  233. you can re-map the indexes to yield a transformed array.
  234. Many useful features for mathematics and numerics:
  235. @itemize
  236. @item
  237. The full ``numeric tower'' includes infinite-precision
  238. rational numbers and complex numbers.
  239. @item
  240. Compile-time optimization of arithmetic
  241. with the use of type declarations and inference.
  242. @item
  243. A @ref{Quantities,@dfn{quantity}} is a real number with a unit,
  244. such as @code{3cm}.
  245. @item
  246. @ref{Quaternions} are a 4-dimensional generalization of complex numbers.
  247. Unsigned primitive integer types (@code{ubyte}, @code{ushort},
  248. @code{uint}, @code{ulong}) are implemented efficiently without
  249. object allocation.
  250. @end itemize
  251. A @ref{Lazy evaluation,lazy value} wraps an expression which is evaluated
  252. only when it is needed.
  253. Kawa provides a @ref{Framework,framework} for implementing other programming languages,
  254. and comes with incomplete support for CommonLisp, Emacs Lisp, and
  255. EcmaScript, and
  256. @uref{http://www.gnu.org/software/qexo/,XQuery}.
  257. @menu
  258. * Implemented SRFIs::
  259. * Compatibility:: Compatibility with standards
  260. @end menu
  261. @node Implemented SRFIs
  262. @section Implemented SRFIs
  263. Kawa implements the following semi-standard SRFIs
  264. (@uref{http://srfi.schemers.org/,Scheme Request for Implementation}):
  265. @itemize
  266. @item
  267. @uref{http://srfi.schemers.org/srfi-0/srfi-0.html, SRFI 0}: Feature-based conditional expansion construct,
  268. using @code{cond-expand} - @pxref{Syntax and conditional compilation}.
  269. @item
  270. @uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI 1}: List Library, if @code{(require 'list-lib)} - @pxref{SRFI-1}.
  271. @item
  272. @uref{http://srfi.schemers.org/srfi-2/srfi-2.html, SRFI 2}: AND-LET*: an AND with local bindings, a guarded LET* special form.
  273. @item
  274. @uref{http://srfi.schemers.org/srfi-4/srfi-4.html, SRFI 4}: Homogeneous numeric vector datatypes - @pxref{Uniform vectors}.
  275. @item
  276. @uref{http://srfi.schemers.org/srfi-6/srfi-6.html, SRFI 6}: Basic String Ports - @pxref{Ports}.
  277. @item
  278. @uref{http://srfi.schemers.org/srfi-8/srfi-8.html, SRFI 8}: @code{receive}: Binding to multiple values - @pxref{Multiple values}.
  279. @item
  280. @uref{http://srfi.schemers.org/srfi-9/srfi-9.html, SRFI 9}: Defining Record Types, using @code{define-record-type}
  281. - @pxref{Record types}.
  282. @item
  283. @uref{http://srfi.schemers.org/srfi-10/srfi-10.html, SRFI 10}: @code{#,} external form for special named types.
  284. This is deprecated for various reasons, including that it conflicts
  285. with syntax-case @code{unsyntax}.
  286. Better to use srfi-108 @ref{Named quasi-literals}.
  287. @item
  288. @uref{http://srfi.schemers.org/srfi-11/srfi-11.html, SRFI 11}: Syntax for receiving multiple values,
  289. using @code{let-values} and @code{let*-value} - @pxref{Multiple values}.
  290. @item
  291. @uref{http://srfi.schemers.org/srfi-13/srfi-13.html, SRFI 13}: String Library.
  292. Needs some polishing.
  293. @item
  294. @uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14}: Character-set Library - @pxref{Character sets}.
  295. @item
  296. @uref{http://srfi.schemers.org/srfi-16/srfi-16.html, SRFI 16}: Syntax for procedures of variable arity,
  297. using @uref{http://srfi.schemers.org/srfi-16/srfi-16.html, @code{case-lambda}}.
  298. @item
  299. @uref{http://srfi.schemers.org/srfi-17/srfi-17.html, SRFI 17}: Generalized @code{set!} - @pxref{Locations}.
  300. @item
  301. @uref{http://srfi.schemers.org/srfi-23/srfi-23.html, SRFI 23}: Error reporting mechanism, using @code{error} - @pxref{Exceptions}.
  302. @item
  303. @uref{http://srfi.schemers.org/srfi-25/srfi-25.html, SRFI 25}: Multi-dimensional Array Primitives - @pxref{Arrays}.
  304. @item
  305. @uref{http://srfi.schemers.org/srfi-26/srfi-26.html, SRFI 26}: Notation for Specializing Parameters without Currying - @pxref{Procedures}.
  306. @item
  307. @uref{http://srfi.schemers.org/srfi-28/srfi-28.html, SRFI 28}: Basic Format Strings - @pxref{Format}.
  308. @item
  309. @uref{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI 30}: Nested Multi-line Comments.
  310. @item
  311. @uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI 35}: Conditions.
  312. @item
  313. @uref{http://srfi.schemers.org/srfi-37/srfi-37.html, SRFI 37}: @uref{http://srfi.schemers.org/srfi-37/srfi-37.html,@code{args-fold} - a program argument processor}, if @code{(require 'args-fold)}.
  314. @item
  315. @uref{http://srfi.schemers.org/srfi-38/srfi-38.html, SRFI 38}: External Representation for Data With Shared Structure.
  316. The @code{read-with-shared-structure} is missing, but subsumed by @code{read}.
  317. @item
  318. @uref{http://srfi.schemers.org/srfi-39/srfi-39.html, SRFI 39}:
  319. @xref{Parameter objects}.
  320. @item
  321. @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41}: Streams - @pxref{Streams}.
  322. @item
  323. @uref{http://srfi.schemers.org/srfi-45/srfi-45.html, SRFI 45}: Primitives for Expressing Iterative Lazy Algorithms - @pxref{Lazy evaluation}.
  324. @item
  325. @uref{http://srfi.schemers.org/srfi-60/srfi-60.html, SRFI 60}: Integers as Bits. - @pxref{Logical Number Operations}.
  326. @item
  327. @uref{http://srfi.schemers.org/srfi-62/srfi-62.html, SRFI 62}: S-expression comments.
  328. @item
  329. @uref{http://srfi.schemers.org/srfi-64/srfi-64.html, SRFI 64}: A Scheme API for test suites.
  330. @item
  331. @uref{http://srfi.schemers.org/srfi-69/srfi-69.html, SRFI 69}: Basic hash tables - @pxref{Hash tables}.
  332. @item
  333. @uref{http://srfi.schemers.org/srfi-87/srfi-87.html, SRFI 87}: @code{=>} in @code{case} clauses.
  334. @item
  335. @uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI 88}: Keyword objects - @pxref{Keywords}.
  336. @item
  337. @uref{http://srfi.schemers.org/srfi-95/srfi-95.html, SRFI 95}: Sorting and Merging.
  338. @item
  339. @uref{http://srfi.schemers.org/srfi-97/srfi-97.html, SRFI 97}: Names for SRFI Libraries.
  340. @item
  341. @uref{http://srfi.schemers.org/srfi-98/srfi-98.html, SRFI 98}: An interface to access environment variables
  342. @item
  343. @uref{http://srfi.schemers.org/srfi-101/srfi-101.html, SRFI 101}: Purely Functional Random-Access Pairs and Lists - @pxref{SRFI-101}.
  344. @item
  345. @uref{http://srfi.schemers.org/srfi-107/,SRFI 107}: XML reader syntax - @pxref{XML literals}.
  346. @item
  347. @uref{http://srfi.schemers.org/srfi-108/,SRFI 108}: Named quasi-literal constructors - @pxref{Named quasi-literals}.
  348. @item
  349. @uref{http://srfi.schemers.org/srfi-109/srfi-109.html, SRFI-109}: Extended string quasi-literals - @pxref{string quasi-literals}.
  350. @item
  351. @uref{http://srfi.schemers.org/srfi-118/srfi-118.html, SRFI-118}: Simple adjustable-size strings (@code{string-append!} and @code{string-replace!}).
  352. @end itemize
  353. @node Compatibility
  354. @section Compatibility with standards
  355. Kawa implements all the required and optional features of R7RS,
  356. with the following exceptions.
  357. The entire ``numeric tower" is implemented.
  358. However, some transcendental functions only work on reals.
  359. Integral functions do not necessarily work on
  360. inexact (floating-point) integers.
  361. (The whole idea of ``inexact integer" in R5RS seems rather pointless ...)
  362. Also, @code{call-with-current-continuation} is only ``upwards" (?).
  363. I.e. once a continuation has been exited, it cannot be invoked.
  364. These restricted continuations can be used to implement catch/throw
  365. (such as the examples in R4RS), but not co-routines or backtracking.
  366. Kawa now does general tail-call elimination, but only if
  367. you use the flag @code{--full-tailcalls}. (Currently, the
  368. @code{eval} function itself is not fully tail-recursive, in violation
  369. of R5RS.) The @code{--full-tailcalls} flag is not on by default,
  370. partly because it is noticably slower (though I have not measured how
  371. much), and partly I think it is more useful for Kawa to be compatible
  372. with standard Java calling conventions and tools.
  373. Code compiled with @code{--full-tailcalls} can call code
  374. compiled without it and vice versa.
  375. Even without @code{--full-tailcalls}, if the
  376. compiler can prove that the procedure being called is the current
  377. function, then the tail call will be replaced by a jump.
  378. This includes must ``obvious'' cases of calls to the
  379. current function named using @code{define} or @code{letrec},
  380. and many cases of mutual tail-recursion (including
  381. state-machines using @code{letrec}).
  382. By default, symbols are case sensitive.
  383. Kawa implements most of the features of the expression language of DSSSL,
  384. the Scheme-derived ISO-standard Document Style Semantics and Specification
  385. Language for SGML. Of the core expression language, the only features
  386. missing are character properties, @code{external-procedure},
  387. the time-relationed procedures, and character name escapes in
  388. string literals.
  389. From the full expression language, Kawa additionally is missing
  390. @code{format-number}, @code{format-number-list}, and language objects.
  391. Quantities, keyword values, and the expanded @code{lambda} form
  392. (with optional and keyword parameters) are supported.
  393. @node Community
  394. @chapter The Kawa Community
  395. @menu
  396. * Reporting bugs:: Where to report bugs
  397. * Mailing lists:: Where to discuss changes, etc
  398. * Acknowledgements:: Acknowledgements and thanks
  399. * Support:: Technical support for Kawa
  400. * Projects:: Projects using Kawa
  401. * Ideas and tasks:: Ideas and tasks for contributing to Kawa
  402. @end menu
  403. @node Reporting bugs
  404. @section Reporting bugs
  405. To report a bug or a feature request
  406. use the @uref{https://gitlab.com/kashell/Kawa/issues,Issue Tracker}.
  407. This does require a @uref{https://gitlab.com/,GitLab} account;
  408. if this is a problem you can use the Savannah bug tracker.
  409. @subsubheading Older Savannah bug tracker
  410. The older bug tracker for Kawa on Savannah is still available,
  411. but we request you use
  412. the @uref{https://gitlab.com/kashell/Kawa/issues,GitLab Issue Tracker}
  413. for new issues.
  414. To report a bug or feature request for Kawa (including Qexo or JEmacs) through Savannah,
  415. use the
  416. @uref{http://savannah.gnu.org/bugs/?func=additem&group=kawa,bug-submission page}.
  417. You can browse and comment on existing bug reports
  418. using the @uref{http://savannah.gnu.org/bugs/?group=kawa, Kawa Bugzilla page}.
  419. When a bug report is created or modified, mail is automatically sent to the
  420. @email{bug-kawa@@gnu.org} list. You can subscribe, unsubscribe, or browse
  421. the archives through the
  422. @uref{http://mail.gnu.org/mailman/listinfo/bug-kawa,
  423. @code{bug-kawa} web interface}.
  424. @node Mailing lists
  425. @section General Kawa email and discussion
  426. The general Kawa email list is @email{kawa@@sourceware.org}.
  427. This mailing list is used for announcements, questions, patches,
  428. and general discussion relating to Kawa. If you wish to subscribe,
  429. send a blank message request to @email{kawa-subscribe@@sourceware.org}.
  430. To unsubscribe, send a blank message to
  431. @email{kawa-unsubscribe@@sourceware.org}.
  432. (If your mail is forwarded and you're not sure which email address you're
  433. subscribed as, send mail to the address following @code{mailto:} in the
  434. @code{List-Unsubscribe} line in the headers of the messages you get from
  435. the list.)
  436. You can browse the @uref{http://sourceware.org/ml/kawa/,
  437. archive of past messages}.
  438. There are separate mailing lists for
  439. @uref{http://mail.gnu.org/mailman/listinfo/qexo-general, Qexo}
  440. and @uref{http://lists.sourceforge.net/mailman/listinfo/jemacs-info,JEmacs}.
  441. @node Acknowledgements
  442. @section Acknowledgements and thanks
  443. The author and project leader of Kawa is
  444. @uref{http://per.bothner.com/,Per Bothner}
  445. @email{per@@bothner.com}.
  446. Kawa is a re-write of Kawa 0.2, which was a Scheme interpreter written by
  447. R. Alexander Milowski @email{alex@@milowski.com}.
  448. Thanks to Cygnus Solutions (now part of Red Hat) for sponsoring
  449. the initial development of Kawa, and then transferring
  450. their ownership interest to Per.
  451. @subsubheading Financial support
  452. Ean Schuessler and @uref{http://www.brainfood.com/,Brainfood}
  453. provided financial support and encouragement.
  454. Thanks to Chris Dean, Dean Ferreyra, and others
  455. at @uref{http://www.mercedsystems.com/,Merced Systems} for financial
  456. support and other contributions.
  457. @uref{http://google.com/,Google} through their
  458. @uref{http://code.google.com/soc/,Summer of Code} project
  459. sponsored Charles Turner during Summer 2011 and 2012,
  460. Andrea Bernardini Summer 2014 and 2015,
  461. and Tom Bousso Summer 2017.
  462. Thomas Kirk and AT&T provided financial support, and useful bug reports.
  463. @subsubheading Various contributions
  464. @uref{http://jcubic.pl/,Jakub Jankiewicz} contributed the Kawa logo.
  465. Helmut Eller provided SLIME support, syntaxutils.scm, and many bug reports.
  466. Daniel Bonniot for multiple small improvements
  467. to gnu.bytecode and gnu.expr.
  468. Jamison Hope for multiple contributions,
  469. including quaternion support, the SRFI-14 implementation,
  470. Ant improvements, and Google Summer of Code mentoring.
  471. Jim White for Ant support and other improvements.
  472. Bruce R. Lewis implemented @ref{KRL,,KRL} and made other contributions.
  473. Geoff Berry: Handle Exceptions attribute. Other improvements.
  474. Tom Bousso re-implemented @code{gnu.bytecode} to make use
  475. of @uref{asm.ow2.org,ASM}; plus other changes,
  476. Shad Gregory improved JEmacs.
  477. Al Petrofsky improved gnu.math printing and added some IntNum methods.
  478. Marco Vezzoli: SRFI-1 tailoring for Kawa.
  479. Albert Ting - old GuiConsole code.
  480. Christian Surlykke ported JEmacs to use SWT.
  481. Geoff Berry for various gnu.bytecode improvements.
  482. Ivelin Ivanov and Tom Reilly for servlet support.
  483. Anthony Green for Fedora packaging.
  484. Charles Turner for pretty-printer improvements,
  485. improvements in the Common Lips support, and other changes.
  486. Andrea Bernardini optimized the implementation of @code{case}, and
  487. implemented full continuation support (in experimental @code{callcc} branch.
  488. Julien Rousseau and Marius Kjeldahl contributed to Android support.
  489. Peter Lane for many documentation improvements.
  490. William D Clinger for test-cases.
  491. @subsubheading Small fixes and improvements
  492. Patrick Barta;
  493. Joseph Bowbeer;
  494. Dominique Boucher;
  495. Alexander Bunkenburg;
  496. Harold Carr;
  497. Emmanuel Castro;
  498. Álvaro Castro-Castilla;
  499. Sudarshan S Chawathe;
  500. Heather Downs;
  501. Francisco Vides Fernández;
  502. Nic Ferrier;
  503. Oliver Flasch;
  504. Weiqi Gao;
  505. Luke Gorrie;
  506. Mario Domenech Goulart;
  507. Zvi Har'E;
  508. Jeff Haynes;
  509. Ethan Herdrick;
  510. Joerg-Cyril Hoehle;
  511. Elliott Hughes;
  512. Mike Kenne;
  513. Brian Jones;
  514. Gerardo Jorvilleur;
  515. Simon Josefsson (JEmacs menu);
  516. Shiro Kawai;
  517. Thomas Kirk;
  518. Jay Krell;
  519. Timo Myyrä;
  520. Edouard Parmelan;
  521. Walter C. Pelissero;
  522. Rafael Jesus Alcantara Perez;
  523. Lynn Quam;
  524. Marcus Otto;
  525. Terje Pedersen (some XQuery functions);
  526. Matthias Radestock;
  527. Jim Rees;
  528. Ola Rinta-Koski;
  529. Andreas Schlapbach;
  530. Robert D. Skeels;
  531. Benny Tsai;
  532. Vladimir Tsichevski;
  533. Matthieu Vachon;
  534. Vasantha Ganesh;
  535. Phil Walker;
  536. Knut Wannheden;
  537. Chris Wegrzyn,
  538. Kay Zheng,
  539. @subsubheading Bug reports and test cases
  540. Seth Alves;
  541. Khairul Azhar;
  542. Bob Bane;
  543. Hans Boehm;
  544. Adrián Medraño Calvo;
  545. Brian D. Carlstrom;
  546. Luis Casillas;
  547. Sudarshan S Chawathe;
  548. Ken Dickey (format tests);
  549. Helge Dietert;
  550. Allan Erskine;
  551. Marc Feeley (polytype.scm);
  552. Margus Freudenthal;
  553. Weiqi Gao;
  554. Andrea Girotto;
  555. Norman Hard;
  556. Gerardo Horvilleur;
  557. Yaroslav Kavenchuk;
  558. Felix S Klock II;
  559. Francois Leygues;
  560. Mirko Luedde;
  561. Leonardo Valeri Manera;
  562. Kjetil S. Matheussen;
  563. Alex Mitchell;
  564. Alex Moiseenko;
  565. Marc Nieper-Wißkirchen;
  566. Okumura Yuki;
  567. Edouard Parmelan;
  568. Walter C. Pelissero;
  569. Stephen L. Peters;
  570. François Pinard;
  571. Bill Robinson;
  572. Dan Stanger (Eaton Vance);
  573. Hallvard Traetteberg;
  574. Taylor Venable;
  575. Alessandro Vernet;
  576. Tony White
  577. John Whittaker;
  578. Robert Yokota.
  579. @subsubheading Code ported from other packages
  580. Kawa includes Free Software originally written for other purposes,
  581. but incorporated into Kawa, perhaps with some porting. A partial list:
  582. Dorai Sitaram wrote pregexp.
  583. The @code{rationalize} algorithm is by Alan Bawden and Marc Feeley.
  584. Lars T Hansen wrote SRFI-11 (let-values, let*-values macros).
  585. Olin Shivers wrote the SRFI-1 list-processing library,
  586. and the SRFI-13 reference impementation.
  587. John David Stone wrote SRFI-8 (receive macro)
  588. Jussi Piitulainen wrote the SRFI-25 specification and tests.
  589. Richard Kelsey and Michael Sperber wrote SRFI-34.
  590. Anthony Carrico wrote the SRFI-37 reference implementation.
  591. Panu Kalliokoski wrote the SRFI-69 reference implementation.
  592. Donovan Kolbly wrote the srfi-64 ``meta'' testsuite.
  593. Alex Shinn improved SRFI-64 portability.
  594. Philip L. Bewig wrote the SRFI-41 (streams) specification and
  595. reference implementation.
  596. Simon Tatham wrote listsort.
  597. Aubrey Jaffer wrote much of SLIB, some of which has been
  598. imported into gnu.kawa.slib. He also wrote some tests we're using.
  599. @node Support
  600. @section Technical Support for Kawa
  601. If you have a project that depends on Kawa or one of its component
  602. packages, you might do well to get paid priority support from
  603. Kawa's author.
  604. The base price is $2400 for one year. This entitles you to basic
  605. support by email or phone. Per @email{per@@bothner.com} will answer techical
  606. questions about Kawa or its implementation, investigate bug reports, and
  607. suggest work-arounds. I may (at my discretion) provide fixes and
  608. enhancements (patches) for simple problems. Response for support
  609. requests received during the day (California time) will normally be
  610. within a few hours.
  611. All support requests must come through a single designated contact
  612. person. If Kawa is important to your business, you probably
  613. want at least two contact people, doubling the price.
  614. If the support contract is cancelled (by either party), remaining
  615. time will be prorated and refunded.
  616. Per is also available for development projects.
  617. @node Projects
  618. @section Projects using Kawa
  619. @uref{http://appinventor.mit.edu/,MIT App Inventor}
  620. for Android (formerly Google App Inventor)
  621. uses Kawa to translate its visual blocks language.
  622. The @uref{http://www.narrativeandplay.org/hypedyn/,HypeDyn} hypertext
  623. fiction authoring tool is written in Kawa. HypeDyn (pronounced "hyped
  624. in") is a procedural hypertext fiction authoring tool for people who
  625. want to create text-based interactive stories that adapt to reader
  626. choice. HypeDyn is free to download and open source, and runs on
  627. Linux, MacOS and Windows. This is a research project carried out at
  628. the Department of Communications and New Media, National University of
  629. Singapore.
  630. @uref{http://www.nuecho.com,Nü Echo} develops high-performance speech
  631. enabled applications. Nü Echo uses Kawa for the development of innovative
  632. speech application development tools, like a complete
  633. @uref{http://www.nuecho.com/en/services/grammar.shtml,grammar IDE}.
  634. @uref{http://www.mercedsystems.com/, Merced Systems@comma{} Inc.} uses Kawa
  635. extensively in their contact center performance management product
  636. Merced Peformance Suite. Kawa Scheme is used for all development
  637. and has allowed Merced to realize the large productivity gains
  638. that come with using Scheme while still maintaining tight
  639. integration with a large number of Java libraries.
  640. JEmacs is included in the Kawa distribution. It is a project to
  641. re-implement Emacs, allowing a mix of Java, Scheme, and Emacs Lisp.
  642. It has its own @uref{http://jemacs.sourceforge.net/,home-page}.
  643. BRL (``the Beautiful Report Language") is a database-oriented language
  644. to embed in HTML and other markup.
  645. @uref{http://brl.sourceforge.net/, BRL} allows you to embed Scheme in
  646. an HTML file on a web server.
  647. The @uref{http://schemeway.sourceforge.net,SchemeWay Project} is a set of
  648. @uref{http://www.eclipse.org,Eclipse} plug-ins for professional Scheme
  649. programming. The first plugin released, SchemeScript, is a fully-featured
  650. Scheme
  651. editor customizable in Scheme. It embeds the Kawa Scheme system and has
  652. many features that ease Kawa Scheme programming (like code completion on
  653. variable names,
  654. class and method names, namespaces, etc).
  655. The Health Media Research Laboratory, part of the Comprehensive Cancer
  656. Center at the University of Michigan, is using Kawa as an integral part of
  657. its core tailoring technologies. Java programs using Kawa libraries are used
  658. to administer customized web-based surveys, generate tailored feedback,
  659. validate data, and "characterize," or transform, data. Kawa code is embedded
  660. directly in XML-formatted surveys and data dictionaries. Performance and
  661. ease of implementation has far exceeded expectations. For more information
  662. contact Paul R. Potts, Technical Director, Health Media Research Lab,
  663. @code{<potts@@umich.edu>}.
  664. Mike Dillon (@code{mdillon@@gjt.org})
  665. did the preliminary work of creating a
  666. Kawa plugin for jEdit. It is called SchemeShell and provides a REPL inside
  667. of the jEdit console for executing expressions in Kawa (much as the BeanShell
  668. plugin does with the BeanShell scripting language).
  669. It is currently available only via CVS from:
  670. @example
  671. CVSROOT=:pserver:anonymous@@cvs.jedit.sourceforge.net:/cvsroot/jedit
  672. MODULE=plugins/SchemeShell
  673. @end example
  674. STMicroelectronics (@code{marco.vezzoli@@st.com})
  675. uses Kawa in a prototypal
  676. intranet 3tier information retrieval system as a communication protocol
  677. between server and clients, and to do server agents programming.
  678. @ignore
  679. The Nice Programming Language is a new open source language with a
  680. Java-like syntax. It features multiple dispatch, parametric types,
  681. higher-order functions, tuples, optional parameters, safe static typing
  682. of @code{null}, ..., and the new concept of "abstract interfaces".
  683. The Nice compiler (@code{nicec}) uses Kawa's @code{gnu.expr}
  684. and @code{gnu.bytecode}
  685. packages to generate Java bytecode.
  686. You can find more about Nice at @uref{http://nice.sourceforge.net}.
  687. For more information feel free to contact
  688. Daniel Bonniot @email{bonniot@@users.sf.net}).
  689. @end ignore
  690. @node Ideas and tasks
  691. @section Ideas and tasks for contributing to Kawa
  692. Kawa (like other Free Software projects) has no lack of tasks and projects
  693. to work on. Here are some ideas.
  694. The ones marked @i{(GSoC)} are probably most suitable for a Google
  695. Summer of Code project, in being a reasonable size, self-contained, and not
  696. depending on other tasks.
  697. @subsection Recusively initialized data structures
  698. @i{(GSoC)}
  699. Kawa has convenient syntax to @ref{Allocating objects, allocate and initialize objects},
  700. but it gets messier it you want to initialize multiple objects that
  701. reference each other.
  702. Likewise for a single object ``tree'' which contains links to the root.
  703. In this example, we will looks at two vectors, but the feature is more useful
  704. for tree structures. Assume:
  705. @example
  706. (define-constant list1 [1 2 list2])
  707. (define-constant list2 ['a 'b list1])
  708. @end example
  709. The compiler translates this to:
  710. @example
  711. (define-constant list1
  712. (let ((t (object[] length: 3))) ;; allocate native Java array
  713. (set! (t 0) 1)
  714. (set! (t 1) 2)
  715. (set! (t 2) list2)
  716. (FVector:makeConstant t)))
  717. (define-constant list2
  718. (let ((t (object[] length: 3))) ;; allocate native Java array
  719. (set! (t 0) 'a)
  720. (set! (t 1) 'b)
  721. (set! (t 2) list1)
  722. (FVector:makeConstant t)))
  723. @end example
  724. The problem is that @code{list2} has not been created when
  725. we evaluate the initializing expression for @code{list}.
  726. We can solve the problem by re-writing:
  727. @example
  728. (define-private tmp1 (object[] length: 3))
  729. (define-constant list1 (FVector:makeConstant tmp1)
  730. (define-private tmp2 (object[] length: 3))
  731. (define-constant list2 (FVector:makeConstant tmp2)
  732. (set! (tmp1 0) 1)
  733. (set! (tmp1 1) 2)
  734. (set! (tmp1 2) list2)
  735. (set! (tmp2 0) 1)
  736. (set! (tmp2 1) 2)
  737. (set! (tmp2 2) list1)
  738. @end example
  739. The complication is that the code for re-writing vector and object constructors
  740. is spread out (depending on the result type), and not where we
  741. deal with initializing the variables.
  742. One solution is to introduce an inlineable helper function @code{$build$} defined as:
  743. @example
  744. (define ($build$ raw-value create init)
  745. (let ((result (create raw-value))
  746. (init raw-value result)
  747. result))
  748. @end example
  749. Then we can re-write the above code to:
  750. @example
  751. (define-constant list1
  752. ($build$
  753. (object[] length: 3)
  754. (lambda (raw) (FVector:makeConstant raw))
  755. (lambda (raw result)
  756. ($init-raw-array$ raw 1 2 list2))))
  757. (define-constant list2
  758. ($build$
  759. (object[] length: 3)
  760. (lambda (raw) (FVector:makeConstant raw))
  761. (lambda (raw result)
  762. ($init-raw-array$ raw 'a 'b list1))))
  763. @end example
  764. Note that the call to @code{$build$}, as well as the generated @code{lambda}
  765. expressions, are all easily inlineable.
  766. Now assume if at the top-level @var{body} if there is a sequence of @code{define-constant}
  767. definitions initialized with calls to @code{$build$}.
  768. Now it is relatively easy to move all the @code{init} calls after all
  769. @code{alloc} and @code{create} expressions.
  770. The @code{$init-raw-array$} calls are expanded after the code has been re-ordered.
  771. The project includes both implementing the above framework,
  772. as well as updating type-specific (and default) object creation to use the framework.
  773. It would also be good to have compiler warnings if accessing an uninitialized object.
  774. @subsection Enhance texinfo-js documentation browser for Kawa documentation
  775. @i{(GSoC)}
  776. @subsection Run interactive process in separate Java Virtual Machine:
  777. @i{(GSoC)}
  778. When developing and testing it is useful for the REPL to support
  779. hot-swapping (replacing functions on-the-fly) and debugging.
  780. The main goal being able to smoothly reload changed modules
  781. (files or functions), and have other modules not break.
  782. Debugging (such as setting breakpoints) would not be a priority
  783. for this project, but could be a follow-on project.
  784. Skills: Should be experienced with Java, and interested in learning
  785. about @uref{https://docs.oracle.com/javase/8/docs/technotes/guides/jvmti/index.html,JVM TI} and similar low-level parts of the platform.
  786. Difficulty: Challenging, but you can study
  787. how @uref{https://en.wikipedia.org/wiki/Jshell,Java-9's new jshell}
  788. uses the JVM TI.
  789. @subsection Better dynamic reload
  790. @i{(GSoC - this is related to the previous item)}
  791. Kawa does a lot of optimizations and inlining. This conflicts
  792. with being able to ``reload'' a module into an already-running
  793. interactive environment.
  794. We could add an option to load a module in ``reloadable'' mode.
  795. Kawa already patches an old function object (a @code{ModuleMethod})
  796. so existing references to the function get automatically updated.
  797. However, there are problems if the ``signature'' of the function
  798. changes - for example if the return type (declared or inferred)
  799. becomes more general. In those cases the best thing is to
  800. re-compile any code that depends on the modified function.
  801. Reloading a module that defines a class is even trickier,
  802. at least if there are existing instances that should
  803. work as the updated class. We can handle the special case
  804. where only method bodies change: In reloadable mode, each
  805. method body is compiled to a separate function, the
  806. actual body indirects to the function. We must also
  807. recognize when compiling a new version of the same
  808. class, which requires a textual comparison between the
  809. old and new versions, or a structural comparison
  810. between the old class and the new code.
  811. When it comes to top-level variables, an issue is when
  812. to re-evaluate the initializing expression. It is reasonable
  813. to do so if and only if the expression is modified, which
  814. again requires a textual comparison.
  815. @subsection Easier Access to Native Libraries using JNA/JNR
  816. @i{(GSoC)}
  817. The traditional way to access native (C/C++) functions is using JNI,
  818. but it's very awkward.
  819. JNA and @uref{https://github.com/jnr,JNR} are @uref{http://www.oracle.com/technetwork/java/jvmls2013nutter-2013526.pdf,much easier to use}.
  820. This project would design and implement an easy-to-use Kawa wrapper for
  821. for JNR. You should study existing JNR wrappers, such as that for JRuby.
  822. Difficulty: Medium. Need to study existing wrappers and "foreign
  823. function interfaces" (in multiple languages) and design one suitable for Kawa.
  824. Some Scheme (Kawa) experience would be helpful.
  825. @subsection Types for units
  826. @i{(GSoC)}
  827. Kawa supports units (such as @code{cm^2} for square centimeters)
  828. and @ref{Quantities,quantities} (such as @code{4cm^2}).
  829. We would like to integrate these into the type system, both
  830. for performance and compile-time type checking.
  831. For syntax we can use a pseudo-parameterized type @code{quantity}. For example:
  832. @example
  833. (define a1 ::quantity[cm^2] 4cm^2)
  834. (* 2.0 a1) ;; @result{} 8cm^2
  835. (+ 2.0 a1) ;; @i{compile-time error}
  836. @end example
  837. The run-time type of the variable @code{a1} should be
  838. a primitive @code{double}, without object allocation.
  839. Of course when @code{a1} is converted to an object, we
  840. create a @code{Quantity}, not a @code{Double}.
  841. We can build on Kawa's existing framework for
  842. non-standard primitive types such as @code{character} and @code{ulong}.
  843. Skills: Need good Java experience, and somewhat familiar with the
  844. Java Virtual Machine.
  845. You will need to become comfortable reading @code{javap} output.
  846. Difficulty: Modest.
  847. @subsection Compiler should use class-file reading instead of reflection
  848. The Kawa compiler currently uses reflection to determine properties
  849. (such as exported function definitions) from referenced classes.
  850. It would be better to read class files.
  851. This should not be too difficult, since the @code{gnu.bytecode} library
  852. abstracts over class information read by reflection or class reading.
  853. @subsection Mutually dependent Java and Scheme modules
  854. @i{(GSoC - maybe)}
  855. We'd like a command for compiling a list of Java and Scheme
  856. source files that may have mutual dependencies. A good way
  857. to do this is to hook into @code{javac}, which is quite extensible
  858. and pluggable.
  859. One could do something like:
  860. @enumerate
  861. @item
  862. Read the ``header" of each Kawa source file, to determine the
  863. name of the generated main class.
  864. @item
  865. Enter these class names into the javac tables as ``uncompleted''
  866. classes.
  867. @item
  868. Start compiling the Java files. When this requires the members
  869. of the Kawa classes, switch to the Kawa files. From javac,
  870. treat these as pre-compiled .class files. I.e. we treat the Kawa
  871. compiler as a black box that produces Symbols in the same way as
  872. reading class files. At this point we should only need the
  873. initial ``scan'' phase on Kawa.
  874. @item
  875. If necessary, finish compiling remaining Kawa files.
  876. @end enumerate
  877. This approach may not immediately provide as robust mixed-language
  878. support as is ideal, but it is more amenable to incremental improvement
  879. than a standalone stub-generator.
  880. This project is good if you know or want to learn how @code{javac} works.
  881. @subsection Use Java-7 MethodHandles and invokedynamic
  882. Java 7 supports MethodHandles which are meant to provide better
  883. performance (ultimately) for dynamic languages.
  884. See @uref{http://jcp.org/en/jsr/detail?id=292,JSR 292}
  885. and the @uref{http://openjdk.java.net/projects/mlvm/,Da Vinci Machine Project}.
  886. Kawa makes limited use of MethodHandles, and no use of invokedynamic.
  887. There is more to be done. For example, we
  888. can start by optimizing arithmetic when the types are unknown
  889. at compile-time. They could make implementing
  890. generic functions (multimethods) more efficient.
  891. At some point we want to compile lambdas in the same way
  892. as Java 8 does. This can potentially
  893. be more efficient than Kawa's current mechanism.
  894. Remi Forax's @uref{https://github.com/forax/vmboiler,vmboiler} is
  895. a small library on top of ASM that generates optimistically typed bytecodes.
  896. It could be useful for ideas.
  897. @anchor{task-parameterized-types}
  898. @subsection Parameterized types
  899. @i{(GSoC)}
  900. Kawa has some limited support for parameterized types, but
  901. it's not used much. Improve type inferencing.
  902. Support definition of parameterized classes.
  903. Better use of parameterized types for sequence class.
  904. Support wildcards.
  905. (It might be better to have wild-carding be associated with
  906. declarations, as in Scala or @uref{http://openjdk.java.net/jeps/300,proposed for Java}, rather than uses.)
  907. See also @uref{http://openjdk.java.net/jeps/8043488}.
  908. @subsection Optimized function types and values using MethodHandles
  909. @i{(GSoC)}
  910. Kawa doesn't have true function types: Parameter and result types
  911. are only handled for ``known'' functions. The general case with
  912. optional and keyword parameter is complicated, but simple
  913. fixed-arity procedure types would be very useful.
  914. The following syntax is suggested:
  915. @example
  916. procedure[(@var{T1} .. @var{Tn}) @var{Tr}]
  917. @end example
  918. @var{T1} through @var{T1} are types of the parameters, and
  919. @var{Tr} is the type of the result.
  920. For example: @code{procedure[(vector int) string]}.
  921. We call this a typed-procedure type (in contrast to plain @code{procedure}).
  922. If a value has a typed-procedure type then its run-time representation
  923. is a just a @code{MethodHandle}. If such a procedure is called,
  924. the generated bytecode is to just call its @code{invokeExact} method.
  925. The argument expressions are converted (and type-checked) the same
  926. way as if we were calling a statically-known procedure.
  927. Note that passing an @code{int} argument
  928. of to @code{procedure[(vector int) string]} value does @emph{not}
  929. require allocating an object to ``box'' the @code{int};
  930. we can pass a plain @code{int} as-is.
  931. Thus using typed-procedure types can lead to major speed-up.
  932. For example the @code{lib-test.scm} should become much faster.
  933. Converting a known procedure to a typed-procedure type is usually
  934. just a matter of creating a @code{MethodHandle} that references the
  935. method implementing the procedure. Some glue code may be needed
  936. if the types aren't identical, or if the procedure is a closure.
  937. Converting a type-procedure value @code{p} to generic value (such
  938. as untyped @code{procedure} or @code{object}) can be though of as
  939. wrapping it in a @code{lambda}:
  940. @example
  941. ((lambda (arg1::vector arg2::int)::string (p arg1 arg2))
  942. @end example
  943. Coercing a generic value or an untyped procedure to a typed-procedure would
  944. need to generate a method whose signature matches the typed-procedure type,
  945. and in the body of the method use a generic apply.
  946. Coercing from one typed-procedure type to a different typed-procedure type
  947. is a combination of the above techniques (as if converting first to object and
  948. then to the target type), though some optimizations are worth doing.
  949. Adding varargs support can be done later.
  950. @c Later, we might consider merging @code{MHProcedure} and @code{PrimProcedure}.
  951. We need a fall-back mechanism for platforms (such as Android)
  952. that don't support @code{MethodHandle}s. The easiest is to
  953. just treat a typed-procedure type as plain @code{procedure} at run-time,
  954. though we still want the compile-time type-checking,
  955. @subsection Full continuations
  956. @emph{Currently being worked on.}
  957. Add support for full continuations, which is the major
  958. feature missing for Kawa to qualify as a ``true Scheme''.
  959. One way to implement continuations is to add a add that converts
  960. the abstract syntax tree to continuation-passing-style, and then
  961. expand the existing full-tail-call support to manage a stack.
  962. There are other ways to solve the problem.
  963. This may benefit from @ref{task-faster-tailcalls,Faster tailcalls}.
  964. @subsection Faster tailcalls
  965. @anchor{task-faster-tailcalls}
  966. Make @code{--full-tailcalls} run faster.
  967. This may depend on (or incorporate)
  968. @ref{task-TreeList-optimization,TreeList-optimization}.
  969. @anchor{task-TreeList-optimization}
  970. @subsection TreeList-optimization
  971. The @uref{http://www.gnu.org/software/kawa/api/gnu/lists/TreeList.html,TreeList} class is a data structure for ``flattened'' trees. It is used for
  972. XML-style nodes, for multiple values, and for the full-tail-call API.
  973. The basic concept is fine, but it could do with some re-thinking
  974. to make make random-access indexing fast. Also, support for updating
  975. is insufficient. (This needs someone into designing and hacking on
  976. low-level data-structures, along with lots of profiling and testing.)
  977. @subsection Asynchronous evaluation
  978. C# recently added @code{asynch} and @code{await} keywords
  979. for @uref{http://msdn.microsoft.com/en-us/vstudio/gg316360,asynchronous programming}. Kawa's recently improved support for lazy programming
  980. seems like a good framework for equivalent functionality:
  981. Instead of an @code{asynch} method that returns a @code{Task<T>},
  982. the Kawa programmer would write a function that returns a @code{lazy[T]}.
  983. This involves some design work, and modifying the compiler to
  984. rewrite the function body as needed.
  985. This is related to full continuations, as the re-writing is similar.
  986. @anchor{task-REPL-improvements}
  987. @subsection REPL console and other REPL improvement
  988. @emph{Currently being worked on.}
  989. Improvements to the read-eval-print console.
  990. In addition to a traditional Swing console,
  991. it would be useful to support using a web browser as a remote terminal,
  992. possibly using web-sockets.
  993. (This allows ``printing'' HTML-expressions, which can be a useful way
  994. to learn and experiment with web technologies.)
  995. See @uref{http://per.bothner.com/blog/2007/ReplPane/, here} for an article
  996. on the existing Swing REPL, along with some to-do items.
  997. Being able to hide and show different parts of the output might be nice.
  998. Being able to link from error messages to source might be nice.
  999. Better handling of redefinitions is discussed
  1000. @uref{http://per.bothner.com/blog/2009/REPL-for-JavaFX/, here in the context of JavaXF Script}; this is a general REPL issue, mostly independent of the GUI for it.
  1001. An interesting possibility is to use the @uref{http://ipython.org/,IPython}
  1002. framework. There are existing ports for Scala: either
  1003. @uref{https://github.com/mattpap/IScala,IScala}
  1004. or @uref{https://github.com/Bridgewater/scala-notebook, Scala Notebook}.
  1005. @subsection XQuery-3.0 functionality
  1006. @i{(GSoC, for some subset)}
  1007. It would be nice to update the XQuery (Qexo) support
  1008. to some subset of @uref{http://www.w3.org/TR/xquery-30/,XQuery 3.0}.
  1009. @subsection XQuery-updates
  1010. It would be nice to support @uref{http://www.w3.org/TR/xquery-update-10/, XQuery updates}. This depends on @ref{task-TreeList-optimization,TreeList-optimization}.
  1011. @anchor{task-common-lisp}
  1012. @subsection Common Lisp support
  1013. Kawa supports a small subset of the Common Lisp language, but it supports
  1014. a much larger subset of core Common Lisp concepts and data structures, some
  1015. designed with Common Lisp functionality in mind. Examples include
  1016. packages, arrays, expanded function declarations, type specifications,
  1017. and format. A lot could be done to improve the Common Lisp support
  1018. with modest effort. Some Common Lisp features could also be useful
  1019. for Scheme: Documentation strings (or markup) as Java annotations,
  1020. better MOP-like introspection, and generic methods a la defmethod
  1021. (i.e. with multiple definition statements, possibly in separate files,
  1022. as opposed to the current make-procedure) all come to mind.
  1023. Being able to run some existing Common Lisp code bases with
  1024. at most modest changes should be the goal.
  1025. One such package to start with might be an
  1026. @uref{http://aperiodic.net/phil/archives/Geekery/notes-on-lisp-testing-frameworks.html,existing test framework}, perhaps
  1027. @uref{http://common-lisp.net/project/bese/FiveAM.html, FivaAM}.
  1028. Full Common Lisp compatibility is nice, but let's walk before we can run.
  1029. @subsection JEmacs improvements
  1030. @i{(GSoC, for some subset)}
  1031. A lot of work is needed to make
  1032. @uref{http://jemacs.sourceforge.net/,JEmacs} useful.
  1033. One could try to import a useful package and see what works and what fails.
  1034. Or one may look at basic editing primitives.
  1035. Enhancements may be needed to core Emacs Lisp language primitives
  1036. (enhancing @ref{task-common-lisp, Common Lisp support} may help),
  1037. or to the display engine.
  1038. Emacs now supports @uref{http://www.gnu.org/software/emacs/manual/html_node/elisp/Lexical-Binding.html,lexical bindings} - we should do the same.
  1039. @subsection Improved IDE integration
  1040. There is some Kawa support for Eclipse (Schemeway), and possibly
  1041. other IDEs (NetBeans, IntelliJ). But many improvements are
  1042. desirable.
  1043. @ref{task-REPL-improvements, REPL improvements} may be a component of this.
  1044. @subsubsection Plugin for NetBeans IDE
  1045. Kawa-Scheme support for the NetBeans IDE would be useful.
  1046. One could perhaps build on the Clojure plugin.
  1047. @subsubsection Plugin for Eclipse IDE
  1048. Kawa-Scheme support for the Eclipse IDE would be useful.
  1049. Probably makes sense to
  1050. enhance @uref{http://sourceforge.net/projects/schemeway/,SchemeWay}.
  1051. It may also make sense to build on
  1052. the @uref{http://www.eclipse.org/dltk/,Dynamic Languages Toolkit},
  1053. possibly making use of @uref{http://schemeide.sourceforge.net/,Schemeide},
  1054. though DLTk seems more oriented towards interpreted non-JVM-based languages.
  1055. @subsubsection Improve Emacs integration
  1056. @uref{http://en.wikipedia.org/wiki/SLIME, SLIME} is an Emacs mode
  1057. that provides IDE-like functionality. It supports Kawa.
  1058. @uref{http://jdee.sourceforge.net/,JDEE} is a Java development environment,
  1059. so might have better hooks to the JVM and Java debugging architecture.
  1060. @uref{http://cedet.sourceforge.net/,CEDET} is a more general
  1061. framework of development tools.
  1062. @subsection Hop-style web programming
  1063. @uref{http://hop.inria.fr/,Hop} is an interesting design
  1064. for integrating server-side and client-side programming using
  1065. a Scheme dialect. These ideas seem like they would port
  1066. quite well to Kawa.
  1067. @subsection String localization
  1068. @i{(GSoC)}
  1069. Support localization by extending the
  1070. @uref{http://srfi.schemers.org/srfi-109/srfi-109.html,SRFI_109}
  1071. syntax, in the manner of (and compatible with)
  1072. @uref{http://www.gnu.org/software/gettext/,GNU gettext}.
  1073. I.e. optionally specify a localization key (to use as an index
  1074. in the translation database); if there is no key specified,
  1075. default to using the literal parts of the string.
  1076. @subsection Data binding
  1077. Implement a ``bind'' mechanism similar to that
  1078. of @uref{http://docs.oracle.com/javafx/1.3/tutorials/core/dataBinding/,JavaFX Script}.
  1079. The idea is that when you initialize a variable or field,
  1080. instead of initializing it to a fixed value, you bind it to
  1081. an expression depending on other variables.
  1082. We install ``listeners'' on those variables, so when those variables
  1083. change, we update the bound variable.
  1084. This feature is useful in many applications, but the initial
  1085. focus could be GUI programming and perhaps web programming.
  1086. @c Note in general the result is a ``text'', which is a generalization
  1087. @c of a string: A text is a sequence of characters *or* other values.
  1088. @c If an embedded expression evaluates to a non-string, it is @emph{not}
  1089. @c automatically converted to a string. Conversion to a string
  1090. @c is done on demand, for example on printing.
  1091. @c (This is similar to values in the XML data model.)
  1092. @subsection Decimal arithmetic and repeated decimals
  1093. @i{(GSoC. Possibly a bit light for a full Summer project,
  1094. but can be extended or combined with other projects.)}
  1095. Exact decimal arithmetic is a variation of exact rational arithmetic,
  1096. but may be more user-friendly. In particular, printing using
  1097. decimals is generally nicer than fractions.
  1098. It is also sometimes useful to specify an explicit scale,
  1099. so we can distinguish 0.2 from 0.20.
  1100. We can use the Java @code{BigDecimal} class, but run into problems
  1101. with division - for example @code{(/ 1.0 3.0)}.
  1102. We should implement a subclass of @code{RatNum} that generalizes
  1103. @code{BigDecimal} to also handle repeating decimals.
  1104. We need a lexical syntax for repeating decimals.
  1105. Possible ideas: @code{0._81_} or @code{0.#81}.
  1106. If a Scheme number literal is specified as exact and has either
  1107. a decimal point or an exponent (for example @code{#e1.25}), then it should
  1108. read as an exact decimal, not a fraction.
  1109. @subsection Optional strict typing along with an explicit @code{dynamic} type
  1110. @i{(GSoC)}
  1111. Kawa currently implements ``optimistic'' typing: The compiler only
  1112. complains if an expression has no values in common with the target type
  1113. - for example, if assigning a @code{string} expression to an @code{integer}
  1114. variable.
  1115. It would be interesting to experiment with a
  1116. @code{--strict-typing} option (which would never be the default):
  1117. Strict typing would only allow ``widening'' conversions - i.e.
  1118. that the expression type be a subtype of the target type.
  1119. For example it would complain if assigning a @code{number} to an @code{integer}
  1120. unless you used an explicit cast.
  1121. To make this easier to work with we'd make use
  1122. of the @ref{dynamic-type,@code{dynamic} type}, similar to
  1123. @uref{https://msdn.microsoft.com/en-us/library/dd264736.aspx,what
  1124. @code{C#} does}: Any expression can be converted
  1125. to or from @code{dynamic} without the compiler complaining.
  1126. Similarly, if @code{x} is @code{dynamic} then @code{x:name}
  1127. is allowed by the compiler regardless of @code{name}, with all checking
  1128. being deferred to run-time. If a variable is declared without a type,
  1129. it should default to @code{dynamic}. The @code{dynamic} type
  1130. is represented in the VM as @code{object} but with an annotation
  1131. (like we do with @code{character}).
  1132. The type-checker might need some changes to better distinguish
  1133. implicit conversions from explicit casts.
  1134. @node Installation
  1135. @chapter Getting and installing Kawa
  1136. @menu
  1137. * Getting Kawa::
  1138. * Running Java:: Getting and running Java
  1139. * Binary distribution:: Installing and using the binary distribution
  1140. * Source distribution:: Installing and using the source distribution
  1141. @end menu
  1142. @node Getting Kawa, Running Java, , Installation
  1143. @section Getting Kawa
  1144. You can compile Kawa from the source distribution.
  1145. Alternatively, you can install the pre-compiled binary distribution.
  1146. You can get Kawa sources and binaries from the Kawa ftp site
  1147. @uref{ftp://ftp.gnu.org/pub/gnu/kawa/},
  1148. or from a @uref{http://www.gnu.org/order/ftp.html,mirror site}.
  1149. The current release of the Kawa source code is
  1150. @uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.tar.gz}.
  1151. (To unpack @code{.tar.gz} files Windows users can use
  1152. @uref{http://www.7-zip.org/,7-Zip}, which is Free Software.)
  1153. The corresponding pre-compiled release
  1154. is @uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.zip}.
  1155. The most recent snapshot is
  1156. @uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-latest.zip}.
  1157. Instructions for using either are @ref{Binary distribution,here}.
  1158. @subsection Getting the development sources using Git
  1159. The Kawa sources are managed using a
  1160. @uref{https://gitlab.com/kashell/Kawa,git} repository.
  1161. If you want the very latest version grab
  1162. @uref{https://git-scm.com/downloads,a git client},
  1163. and then check out the source using this command:
  1164. @example
  1165. git clone https://gitlab.com/kashell/Kawa.git
  1166. @end example
  1167. After a checkout you will need to run:
  1168. @example
  1169. ./autogen.sh
  1170. @end example
  1171. before proceding with instructions for @ref{Source distribution,building the source distribution}.
  1172. Once you have it checked out, you can keep it up-to-date with @code{git pull}.
  1173. You can also
  1174. @uref{https://gitlab.com/kashell/Kawa/tree/master,browse the git archive} online.
  1175. @node Running Java, Binary distribution, Getting Kawa, Installation
  1176. @section Getting and running Java
  1177. Before installing Kawa, you will need a working Java system.
  1178. The released Kawa jar file assumes Java 8 or newer.
  1179. You need to build Kawa from source if you have Java 5, Java 6,
  1180. or are targeting Android.
  1181. (Older versions of Kawa have been reported to
  1182. work with JDK from 1.1, Kaffe, Symantec Cafe, J++, and GCJ,
  1183. but these are no longer supported.)
  1184. The discussion below assumes you are using the Java Developer's Kit
  1185. (JDK) from Oracle. You can download free copies of
  1186. @uref{http://www.oracle.com/technetwork/java/javase/downloads/index.html, JDK 8} for various platforms.
  1187. @c If you want to run Kawa on a Macintosh, see
  1188. @c @uref{http://rdsathene.org/scheme/mackawa.html}.
  1189. The program @code{java} is the Java interpreter.
  1190. The program @code{javac} is the Java compiler,
  1191. and is needed if you want to compile the source release yourself.
  1192. Both programs must be in your @code{PATH}.
  1193. If you have the JDK in directory @code{$JAVA_HOME},
  1194. and you are using a Bourne-shell compatible shell
  1195. (/bin/sh, ksh, bash, and some others) you can set @code{PATH} thus:
  1196. @example
  1197. PATH=$JAVA_HOME/bin:$PATH
  1198. export PATH
  1199. @end example
  1200. @node Binary distribution
  1201. @section Installing and using the binary distribution
  1202. The binary release comes as a @code{.zip} archive that
  1203. includes Kawa itself (as a @code{.jar} file @code{kawa-@var{version}.jar}),
  1204. some third-party helper libraries, @code{kawa} command scripts
  1205. (for GNU/Linux/Unix/MacOS or Windows),
  1206. and documentation (basically this manual).
  1207. After downloading (see @ref{Getting Kawa}), extract the files
  1208. from the @code{.zip} archive using a suitable @code{unzip} program,
  1209. which will create a directory @code{kawa-@var{version}},
  1210. with @code{lib}, @code{bin}, and @code{doc} sub-directories.
  1211. In the following, we assume the environment variable @code{KAWA_HOME}
  1212. refers to this directory:
  1213. @example
  1214. unzip ~/Downloads/kawa-@var{version}.zip
  1215. export KAWA_HOME=`pwd`/kawa-@var{version}
  1216. @end example
  1217. The binary release requires Java 8 or later.
  1218. If you have an older Java implementation, or build for a mobile
  1219. environment like Android,
  1220. then you will need to get the source distribution.
  1221. If you want to use Kawa as part of some other application,
  1222. you just need the @code{$KAWA_HOME/lib/kawa.jar}.
  1223. @subsubheading Running the @code{kawa} command
  1224. To run a Kawa script file or the Kawa read-eval-print-loop
  1225. run the Kawa application. There are various way to do so.
  1226. The recommended way is to execute the @code{$KAWA_HOME/bin/kawa} Bash
  1227. shell script.
  1228. This should work on most Unix-like platforms that have Bash installed,
  1229. including GNU/Linux, BSD, MacOS, and Cygwin/MingW.
  1230. (Please report if you have problems.)
  1231. The script assumes that either a suitable @code{java} program is
  1232. in your @code{PATH}; or the @code{JAVA} environment variable
  1233. names a suitable @code{java} executable; or that @code{JAVA_HOME}
  1234. is set so @code{$JAVA_HOME/bin/java} is suitable.
  1235. If you want to put @code{kawa} in your search path you can of course do:
  1236. @example
  1237. PATH=$KAWA_HOME/bin:$PATH
  1238. @end example
  1239. Alternatively you can create a symbolic link in an already-searched directory.
  1240. For example:
  1241. @example
  1242. cd /usr/local/bin
  1243. ln -s $KAWA_HOME/bin/kawa kawa
  1244. @end example
  1245. The @code{bin/kawa.bat} script works on Windows.
  1246. Both scripts add some helper libraries, including support for input editing.
  1247. It is also possible to run Kawa using @code{java} directly:
  1248. @example
  1249. java -jar $KAWA_HOME/lib/kawa.jar
  1250. @end example
  1251. or:
  1252. @example
  1253. CLASSPATH=$KAWA_HOME/lib/kawa.jar
  1254. export CLASSPATH
  1255. java kawa.repl
  1256. @end example
  1257. On Windows:
  1258. @example
  1259. set classpath=%KAWA_HOME%\lib\kawa.jar
  1260. @end example
  1261. To run Kawa in a fresh window use the -w flag:
  1262. @example
  1263. kawa -w
  1264. @end example
  1265. or
  1266. @example
  1267. java kawa.repl -w
  1268. @end example
  1269. @subsubheading Reading the documentation
  1270. The file @code{doc/kawa-manual.epub} contains the Kawa documention
  1271. packaged as an electronic book, which is readable by most
  1272. e-book readers. Plugins are also available for common browsers,
  1273. for example @uref{http://www.epubread.com,EPUBReader} for @code{firefox}.
  1274. Even easier is to invoke
  1275. @ref{browse-manual-option,@code{bin/kawa --browse-manual}}
  1276. (or on Windows: @code{bin\kawa.bat --browse-manual}).
  1277. An @code{epub} is essentially a zip archive, which you can unzip:
  1278. @example
  1279. cd $KAWA_HOME/doc
  1280. unzip kawa-manual.epub
  1281. @end example
  1282. Then you can use a plain browser
  1283. with the URL @code{file:$KAWA_HOME/doc/OEBPS/index.xhtml}.
  1284. @node Source distribution, , Binary distribution, Installation
  1285. @section Installing and using the source distribution
  1286. The Kawa release normally comes as a gzip-compressed tar file named
  1287. @samp{kawa-@value{VERSION}.tar.gz}.
  1288. @c The same sources are available as a zip file
  1289. @c @samp{kawa-@value{VERSION}-src.zip}.
  1290. Two methods are supporting for compiling the Kawa sources;
  1291. choose whichever is most convenient for you.
  1292. One method uses the traditional GNU @code{configure} script,
  1293. followed by running @code{make}. This works well on Unix-like
  1294. systems, such as GNU/Linux.
  1295. You can also use this method on Microsoft Windows,
  1296. with the help of tools from @uref{http://www.MinGW.org/, MinGW}
  1297. or @uref{http://www.cygwin.org/, Cygwin}.
  1298. The other method uses the @code{ant} command, a Java-based
  1299. build system released by Apache's Jakarta project. This uses
  1300. an @code{build.xml} file in place of @code{Makefile}s, and
  1301. works on non-Unix systems such as Microsoft Windows. However,
  1302. the @code{ant} method does not support all
  1303. the features of the @code{configure}+@code{make} method.
  1304. @subsection Build Kawa using @code{configure} and @code{make}
  1305. (See @ref{building-on-Windows-with-make,below} for some notes for building
  1306. on Microsoft Windows.)
  1307. If you have a @code{tar.gz} file, first unpack that in your build directory:
  1308. @example
  1309. tar xzf kawa-@value{VERSION}.tar.gz
  1310. cd kawa-@value{VERSION}
  1311. @end example
  1312. If you're building from the Git repository, you need to
  1313. generate @code{configure} and some other files. This is
  1314. easiest done with the @code{autogen.sh} script:
  1315. @example
  1316. ./autogen.sh
  1317. @end example
  1318. Then you must configure the sources. This you do in
  1319. the same way you configure most other GNU software. Normally
  1320. you can just run the configure script with no arguments:
  1321. @example
  1322. ./configure
  1323. @end example
  1324. The @code{configure} script takes a number of @ref{configure options,options}.
  1325. If you have installed Kawa before, make sure your @code{CLASSPATH}
  1326. does not include old versions of Kawa, or other classes that may
  1327. conflict with the new ones.
  1328. Then you need to compile all the .java source files.
  1329. Just run make:
  1330. @example
  1331. make
  1332. @end example
  1333. This assumes that @samp{java} and @samp{javac} are the java interpreter
  1334. and compiler, respectively.
  1335. It has been reported that parallel make doesn't work,
  1336. so don't use the @code{-j2} or above options.
  1337. You can now test the system by running Kawa in place:
  1338. @example
  1339. java kawa.repl
  1340. @end example
  1341. or you can run the test suite:
  1342. @example
  1343. make check
  1344. @end example
  1345. or you can install the compiled files:
  1346. @example
  1347. make install
  1348. @end example
  1349. This will install your classes into @code{$PREFIX/share/java} (and its
  1350. sub-directories). Here @code{$PREFIX} is the directory you specified
  1351. to configure with the @code{--prefix} option, or @code{/usr/local} if you
  1352. did not specify a @code{--prefix} option.
  1353. To use the installed files, you need to set @code{CLASSPATH} so
  1354. that @code{$PREFIX/share/java/kawa.jar} is in the path:
  1355. @example
  1356. CLASSPATH=$PREFIX/share/java/kawa.jar
  1357. export CLASSPATH
  1358. @end example
  1359. This is done automatically if you use the @samp{kawa} script.
  1360. @anchor{configure options}
  1361. @cindex configure options
  1362. @subsubsection Configure options
  1363. The @code{configure} script takes a number of options.
  1364. The @code{--help} switch gives you a list of options.
  1365. The following are some of the more common or important ones.
  1366. @table @asis
  1367. @item @code{--prefix=@var{install-dir}}
  1368. @itemx @code{--prefix @var{install-dir}}
  1369. By default @code{make install} will install the compiled @code{.jar}
  1370. files info @code{/usr/local/share/java},
  1371. the @code{kawa} command into @code{/usr/local/bin},
  1372. and so on in @code{/usr/local}.
  1373. The @code{--prefix} option causes the files to be installed
  1374. under @code{@var{install-dir}} instead of @code{/usr/local}.
  1375. For example to install the @code{.jar} in @code{/opt/kawa/share/java}
  1376. and otherwise use @code{/opt/kawa} do:
  1377. @example
  1378. ./configure --prefix=/opt/kawa
  1379. @end example
  1380. @item @code{--with-java-source=@var{version}}
  1381. As distributed, the Kawa source code requires Java 8.
  1382. If you only have Java 7, Java 6, or Java 5, use the @code{--with-java-source} option:
  1383. @example
  1384. ./configure --with-java-source=6
  1385. @end example
  1386. Kawa no longer supports older verisons of Java (JDK 1.4 or older).
  1387. It might be possible to use a tool
  1388. like @uref{http://retroweaver.sourceforge.net/, Retroweaver}
  1389. on the Kawa @code{.jar} to fix up Java 5 dependencies.
  1390. Contact the Kawa author if you want to be a tester for this.
  1391. @item @code{--with-docbook-stylesheet[=@var{path}]}
  1392. Build the documentation (this manual) as an electronic book
  1393. (in ebook format) or a website, using
  1394. the DocBook xslt stylesheets.
  1395. (You can build the documentation without DocBook, but using
  1396. it enables nicer-looking and more functional documentation.)
  1397. The stylesheets are found using @var{path};
  1398. the file @code{@var{path}/epub3/chunk.xsl} needs to exist.
  1399. (For example, on Fedora 25 @var{path} can be @code{/usr/share/sgml/docbook/xsl-ns-stylesheets},
  1400. while on Debian use @code{/usr/share/xml/docbook/stylesheet/docbook-xsl-ns}.)
  1401. @item @code{--with-domterm}
  1402. @itemx @code{--with-domterm=@var{domterm_home}}
  1403. Compile with extra support for the @ref{Using DomTerm,DomTerm}
  1404. terminal emulator library, where @code{@var{domterm_home}}
  1405. is such that @code{@var{domterm_home}/lib/domterm.jar} exists.
  1406. (Some DomTerm support is built-in regardless.)
  1407. If you use this option along with @code{--with-javafx}
  1408. then creating a new @ref{REPL Console,REPL} window
  1409. will create a DomTerm window.
  1410. As an optional convenience, you can use the @code{domterm.jar}
  1411. in the Kawa binary distribution.
  1412. @item @code{--with-jline3}
  1413. @itemx @code{--with-jline3=@var{jline3.jar}}
  1414. Build support for using @uref{https://github.com/jline/jline3,JLine 3},
  1415. which is a library for handling console input, similar to GNU readline.
  1416. If specified, the @var{jline3.jar} is added to the classpath of the
  1417. generated @code{kawa.sh} or @code{kawa} shell program.
  1418. An advantage of @code{--with-jline3} (compared to
  1419. @code{--enable-kawa-frontend}) is that the former works without native code
  1420. (on most Unix-like platforms), and it does not require a C wrapper program.
  1421. As an optional convenience, you can use the @code{jline.jar}
  1422. in the Kawa binary distribution.
  1423. @item @code{--with-domterm}
  1424. @itemx @code{--with-domterm=@var{domterm.jar}}
  1425. Compile with extra support for the @ref{Using DomTerm,DomTerm}
  1426. terminal emulator library. (Some DomTerm support is built-in regardless.)
  1427. If you use this option along with @code{--with-javafx}
  1428. then creating a new @ref{REPL Console,REPL} window
  1429. will create a DomTerm window.
  1430. As an optional convenience, you can use the @code{domterm.jar}
  1431. in the Kawa binary distribution.
  1432. @item @code{--with-servlet}
  1433. @itemx @code{--with-servlet=@var{servlet-jar}}
  1434. Build support for @ref{Servlets,servlets}, which are used in web servers.
  1435. This requires the @code{servlet-api.jar} (available various places including
  1436. @uref{http://tomcat.apache.org/,Tomcat} or
  1437. @uref{https://glassfish.java.net/,Glassfish}),
  1438. for @code{javax.servlet.Servlet} and related classes.
  1439. If this class isn't in your classpath, specify its location
  1440. as @code{@var{servlet-jar}}. For example:
  1441. @example
  1442. ./configure --with-servlet=/path/to/servlet-api.jar
  1443. @end example
  1444. @item @code{--enable-jemacs}
  1445. Build JEmacs (enable Emacs-like text editor) and support (a subset of)
  1446. the Emacs Lisp language. JEmacs is a proof of concept - not really
  1447. usable or maintained.
  1448. @item @code{--with-javafx}
  1449. @itemx @code{--with-javafx=@var{javafx-jar}}
  1450. @itemx @code{--with-javafx=@var{java-home}}
  1451. Set this flag to enable the convenience features
  1452. for @ref{Building JavaFX applications,JavaFX}.
  1453. The JavaFX classes are included in JDK 8 (but not OpenJDK 8),
  1454. and you don't need to specify @code{@var{javafx-jar}} or @code{@var{java-home}}.
  1455. For JDK 7 you need to specify @code{@var{javafx-jar}}
  1456. (the path to @code{javafx.rt}) or @code{@var{java-home}}
  1457. (the value of the @code{$JAVA_HOME}).
  1458. @item @code{--with-android=@var{android-jar}}
  1459. Build for the Android platform.
  1460. This requires @ref{Building for Android,special instructons}.
  1461. @item @code{--enable-kawa-frontend}
  1462. If you have the GNU @samp{readline} library installed, you might try
  1463. adding the @samp{--enable-kawa-frontend} flag.
  1464. This will build the
  1465. @samp{kawa} front-end program, which provides input-line editing
  1466. and an input history. You can get @samp{readline} from archives
  1467. of GNU programs, including @uref{ftp://www.gnu.org/}.
  1468. Note that using JLine, enabled by @code{--with-jline3},
  1469. is now recommended instead of using the @code{readline} frontend.
  1470. You may need to specify to @code{make} where to find
  1471. the @code{readline} include files (with @code{READLINE_INCLUDE_PATH})
  1472. and the library (with @code{READINE_LIB_PATH}).
  1473. For example on OS/X you need to do:
  1474. @example
  1475. make READLINE_INCLUDE_PATH=-I/usr/local/unix/readline/include \
  1476. READLINE_LIB_PATH=-L/usr/local/unix/readline/lib
  1477. @end example
  1478. @end table
  1479. @anchor{building-on-Windows-with-make}
  1480. @subsubsection Building on Windows using MinGW
  1481. The Kawa @code{configure} and @code{make} process assumes Unix-like
  1482. tools, which you can get from @uref{http://mingw.org, the MinGW project}.
  1483. Download the MingGW Installation Manager, and use it to install
  1484. at least @code{mingw-developer-toolkit}.
  1485. (Also installing @code{msys-groff} avoids a minor problem
  1486. building the documentation.)
  1487. The @code{C:\MinGW\msys\1.0\msys.bat} script creates a command window
  1488. with the @code{bash} shell and the @code{PATH} set up as needed.
  1489. Alternatively, you can use the standard Windows command prompt
  1490. if you set your @code{PATH} as described in @uref{http://mingw.org/wiki/Getting_Started, here}.
  1491. @subsubsection Building on Windows using Cygwin
  1492. The free @uref{http://sourceware.org/cygwin/,Cygwin}
  1493. environment can be used for building Kawa: The Kawa configure script
  1494. recognizes Cygwin, and modifies the classpath to use Windows-style
  1495. path separators.
  1496. Beyond the base packages, you probably want to install @code{autoconf},
  1497. @code{automake}, @code{git}, @code{texinfo}, @code{groff},
  1498. @code{make}, and @code{diffutils}.
  1499. Cygwin (unlike MinGW) has a current version of @code{makeinfo}, but
  1500. an undiagnosed bug still prevents building @code{kawa.info}.
  1501. You can work around that problem with @code{touch doc/kawa.info}.
  1502. @subsection Building the documentation
  1503. @subsubsection Plain HTML documentation
  1504. You can build a plain HTML version of the documentation
  1505. (using @code{makeinfo} from the @code{texinfo} distribution):
  1506. @example
  1507. cd doc && make kawa-html/index.html
  1508. @end example
  1509. In this case, point your browser at
  1510. @code{file:/@var{kawa_srcdir}/doc/kawa-html/index.html}.
  1511. @subsubsection Fancier HTML documentation
  1512. To build the documentation in a nicer form suitable for a web-site
  1513. you need @code{makeinfo} @emph{and} the DocBook XSLT tools
  1514. (and to have run @code{configure} with
  1515. the @code{--with-docbook-stylesheet} option):
  1516. @example
  1517. cd doc && make web/index.html
  1518. @end example
  1519. You can then point your browser at @code{file:/@var{kawa_srcdir}/doc/web/index.html}.
  1520. @subsubsection Using ebook readers or the --browse-manual option
  1521. To build an @code{EPUB} file suitable for ebook readers,
  1522. as well as enabling support for the
  1523. @ref{browse-manual-option,@code{kawa --browse-manual} option}, do:
  1524. @example
  1525. cd doc && make kawa-manual.epub
  1526. @end example
  1527. This also requires the DocBook XSLT tools.
  1528. @subsubsection Building a printable PDF file
  1529. To build a @code{pdf} file suitable for printing or online viewing do:
  1530. @example
  1531. cd doc && make kawa.pdf
  1532. @end example
  1533. The resulting @code{kawa.pdf} is somewhat unsatisfactory - when viewed online,
  1534. links aren't clickable. Furthermore, box drawing characters are missing.
  1535. @subsection Build Kawa using @code{ant}
  1536. Kawa now includes an Ant buildfile (@code{build.xml}).
  1537. @uref{http://ant.apache.org, Ant} is a part of the Apache
  1538. Jakarta project.
  1539. If you don't hava Ant installed,
  1540. get it from @uref{http://ant.apache.org/bindownload.cgi}.
  1541. The build is entirely Java based and works equally well on *nix, Windows,
  1542. and presumably most any other operating system.
  1543. Once Ant has been installed and configured (you may need to set the
  1544. @code{JAVA_HOME}, and @code{ANT_HOME} environment variables), you should
  1545. be able to change to the directory containing the @code{build.xml} file,
  1546. and invoke the @samp{ant} command. With the default settings, a
  1547. successful build will result in a @code{kawa-@value{VERSION}.jar} in the
  1548. current directory.
  1549. There are a few Ant "targets" of interest (they can be supplied on the
  1550. Ant command line):
  1551. @table @code
  1552. @item all
  1553. This is the default, it does @code{classes} and @code{jar}.
  1554. @item classes
  1555. Compiles all the files into @code{*.class} files into the directory
  1556. specified by the @code{build.dir} property.
  1557. @item jar
  1558. Builds a jar into into the directory
  1559. specified by the @code{dist.dir} property.
  1560. @item runw
  1561. Run Kawa in a GUI window.
  1562. @item clean
  1563. Deletes all files generated by the build, including the jar.
  1564. @end table
  1565. There is not yet a @code{test} target for running the testsuite.
  1566. There are various ``properties" that control what @code{ant} does. You can
  1567. override these on the command line or by editing the
  1568. @code{build.properties} file in the same directory as @code{build.xml}.
  1569. For example, the @code{build.dir} property tells @code{ant} where to
  1570. build temporary files, and where to leave the resulting @code{.jar}
  1571. file. For example, to leave the generated files in the sub-directory
  1572. named @code{BUILD} do:
  1573. @example
  1574. ant -Dbuild.dir=BUILD
  1575. @end example
  1576. A sample @code{build.properties} is provided and it contains
  1577. comments explaining many of the options.
  1578. Here are a few general properties that help to customize your build:
  1579. @table @code
  1580. @item build.dir
  1581. Path to put the temporary files used for building.
  1582. @item dist.dir
  1583. Path to put the resulting jar file.
  1584. @item version.local
  1585. A suffix to add to the version label for your customized version.
  1586. @item debug
  1587. Whether (true/false) the Javac "-g" option is enabled.
  1588. @item optimize
  1589. Whether (true/false) the Javac "-O" option is enabled.
  1590. @end table
  1591. Here are some Kawa-specific ones (all @code{true}/@code{false}):
  1592. @code{with-collections}, @code{with-references}, @code{with-awt},
  1593. @code{with-swing}, @code{enable-jemacs}, and @code{enable-servlet}>
  1594. See the sample @code{build.properties} for more information on these.
  1595. If you change any of the build properties, you will generally want to do
  1596. an @samp{ant clean} before building again as the build is often not able to
  1597. notice that kind of change. In the case of changing a directory path,
  1598. you would want to do the @code{clean} before changing the path.
  1599. A special note for NetBeans users:
  1600. For some reason the build-tools target which compiles an Ant task won't
  1601. compile with the classpath provided by NetBeans.
  1602. You may do @samp{ant build-tools} from the command line outside of NetBeans,
  1603. in which case you will not want to use the @code{clean} target as that
  1604. will delete the tool files as well.
  1605. You can use the @code{clean-build} and/or @code{clean-dist}
  1606. targets as appropriate. Alternatively you can add @code{ant.jar} to the
  1607. @code{build-tools} classpath by copying or linking it into a @code{lib/ext}
  1608. directory in Kawa's source directory (the one containing the @code{build.xml}
  1609. file).
  1610. @ignore
  1611. @subsection Compiling Kawa to native code with GCJ
  1612. @emph{Using GCJ is no longer supported. This section is for historial
  1613. reference, or if someone enhances GCJ enough to support Kawa.}
  1614. The GNU Compiler for the Java(tm) Programming Language
  1615. (@uref{http://gcc.gnu.org/java/,GCJ}) is part of the
  1616. GNU Compiler Collection (@uref{http://gcc.gnu.org/,GCC}).
  1617. It can compile Java source or bytecode
  1618. files into native code on supported systems.
  1619. Version 4.1 or later of GCC is recommended,
  1620. and only Intel x86-based Linux/GNU system have been tested with Kawa.
  1621. First, get and install GCC. Set @code{PREFIX} to where
  1622. you want to install GCJ, and configure it with these options:
  1623. @example
  1624. ./configure --enable-threads --enable-languages=c++,java --prefix $PREFIX
  1625. make bootstrap
  1626. make install
  1627. @end example
  1628. Make sure @code{gcj} is in your path and refers to the newly-installed
  1629. version, and if needed, set @code{LD_LIBRARY_PATH} to point to the
  1630. directory where @code{libgcj.so} was installed:
  1631. @example
  1632. PATH=$PREFIX/bin:$PATH
  1633. LD_LIBRARY_PATH=$PREFIX/lib
  1634. export LD_LIBRARY_PATH
  1635. @end example
  1636. To build Kawa, you need to specify @code{--with-gcj} to
  1637. @code{configure} which tells it to use GCJ.
  1638. @example
  1639. ./configure --with-gcj --prefix $PREFIX
  1640. @end example
  1641. Then as before:
  1642. @example
  1643. make
  1644. make install
  1645. @end example
  1646. Alternatively, you can use configure option
  1647. @code{--with-gcj-dbtool}. This allows gcj to automatically
  1648. find the kawa shared libraries from the @code{.jar} file.
  1649. @end ignore
  1650. @node Tutorial
  1651. @chapter Kawa Scheme Tutorial
  1652. @emph{This is obviously incomplete, but it may be useful,
  1653. especially if you're starting with Kawa from scratch.}
  1654. If you're new to Scheme you might also check out one of these tutorials:
  1655. Takafumi Shido's
  1656. @uref{http://www.shido.info/lisp/idx_scm_e.html,Yet Another Scheme Tutorial};
  1657. @c dead link Greg Badross @uref{http://www.cs.washington.edu/education/courses/341/99suq/lectures/scheme/,lecture notes};
  1658. Dorai Sitaram's @uref{http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-1.html,Teach Yourself Scheme in Fixnum Days}; or
  1659. Paul Wilson's @uref{ftp://ftp.cs.utexas.edu/pub/garbage/cs345/schintro-v14/schintro_toc.html,An Introduction to Scheme and its Implementation}.
  1660. @menu
  1661. * Tutorial - Introduction:: Introduction
  1662. * Tutorial - Booleans:: Booleans
  1663. * Tutorial - Numbers:: Numbers
  1664. * Tutorial - Functions:: Functions
  1665. * Tutorial - Variables:: Variables
  1666. * Tutorial - Pictures:: Pictures
  1667. * Tutorial - Sequences:: Lists and sequences
  1668. * Tutorial - Objects:: Creating and using objects
  1669. * Tutorial - Types:: Types and declarations
  1670. * Tutorial - Exceptions and errors::
  1671. * Tutorial - Classes:: Classes
  1672. * Tutorial - Other Java features::
  1673. @end menu
  1674. @node Tutorial - Introduction
  1675. @section Introduction
  1676. You've heard about all the hot scripting languages
  1677. -- you might even be tired of hearing about them.
  1678. But Kawa offers you something different than the
  1679. scripting-language @i{du-jour} can.
  1680. You may be interested in one that runs on the Java virtual machine,
  1681. either because you have to interact with other Java tools,
  1682. or because you like having access to all the Java packages out there.
  1683. Or maybe you don't care about Java, but you care about performance.
  1684. If so, let me tell you about Kawa, which is actually one of the
  1685. very oldest language implementations running on the Java Virtual Machine,
  1686. dating back to 1996.
  1687. The Kawa language is a dialect/implementation of the Scheme language.
  1688. (The Kawa project also supports other languages, including
  1689. @uref{http://www.w3.org/XML/Query,XQuery}
  1690. and @uref{http://jemacs.sourceforge.net,Emacs Lisp},
  1691. as well as tools for implementing mew programming languages,
  1692. but we won't cover that in this tutorial.)
  1693. @uref{http://www.schemers.org/,Scheme}
  1694. is an established language with many
  1695. @uref{http://community.schemewiki.org/?scheme-faq-standards#implementations,implementations},
  1696. a @uref{http://www.schemers.org/Documents/Standards/,standard} specification
  1697. (the traditional @uref{http://www.schemers.org/Documents/Standards/R5RS/,R5RS},
  1698. @uref{http://www.r6rs.org/,R6RS} which was ratified in 2007,
  1699. and @uref{http://www.r7rs.org/,R7RS} which was ratified in 2013),
  1700. and is used by universities for both teaching and research.
  1701. Scheme also has a reputation for being difficult to learn,
  1702. with a weird parenthesis-heavy syntax,
  1703. and hard-to-understand concepts like @uref{http://en.wikipedia.org/wiki/Continuation,continuations}.
  1704. Luckily, you don't need to understand continuations!
  1705. (Kawa doesn't fully implement them anyway.)
  1706. The following assumes that Kawa is already installed on your computer;
  1707. if not see these @ref{Installation,installation instructions}.
  1708. Running the @code{kawa} command in interactive mode
  1709. is a good way start learning Kawa:
  1710. @example
  1711. $ @kbd{kawa}
  1712. #|kawa:1|# @kbd{}
  1713. @end example
  1714. If you don't have @code{kawa} but you have a
  1715. Kawa ``jar'' and you have Java installed you can instead do:
  1716. @example
  1717. $ @kbd{java -jar kawa-@var{version-number}.jar}
  1718. #|kawa:1|# @kbd{}
  1719. @end example
  1720. The prompt string has the form of a Scheme comment,
  1721. to make it easier to cut-and-paste.
  1722. Kawa is expecting you type in an expression or command,
  1723. which it will evaluate, and then print out the result.
  1724. For example, a quoted string is a simple expression that evaluates to a
  1725. string value, which will print as itself, before printing the next prompt:
  1726. @example
  1727. #|kawa:1|# @kbd{"Hello, world!"}
  1728. Hello, world!
  1729. #|kawa:2|# @kbd{}
  1730. @end example
  1731. @c Thus the Kawa equivalent of the traditional
  1732. @c @uref{http://en.wikipedia.org/wiki/Hello_world,``hello world''} is trivial.
  1733. The most noticable difference from most other programming languages
  1734. is that Scheme uses ``prefix'' notation for function calls.
  1735. For example Kawa has a function @code{max} which returns the
  1736. largest value of the arguments.
  1737. Instead of @code{max(5, 7, 3)}
  1738. you write @code{(max 5 7 3)}:
  1739. @example
  1740. (max 5 7 3) @result{} 7
  1741. @end example
  1742. (We use the @code{@result{}} symbol above to indicate that
  1743. the expression @code{(max 5 7 3)} evaluates to the
  1744. value @code{7}.)
  1745. The prefix notation may feel a bit weird, but you quickly
  1746. get used to it, and it has some advantages.
  1747. One is consistency: What are special infix operators in most languages
  1748. are just regular functions in Scheme.
  1749. For example, addition is just a regular function call,
  1750. and @code{+} is just a regular function name:
  1751. @example
  1752. (+ 2.5 1.2) @result{} 3.7
  1753. @end example
  1754. The same prefix notation is used for special operations like assignments:
  1755. @example
  1756. #|kawa:1|# @kbd{(set! sqrt-of-2 (sqrt 2))}
  1757. #|kawa:2|# @kbd{sqrt-of-2}
  1758. 1.4142135623730951
  1759. @end example
  1760. @node Tutorial - Booleans
  1761. @section Booleans
  1762. Scheme uses the syntax @code{#t} and @code{#f}
  1763. for Boolean true and false value, respectively. For example, the
  1764. ``less-than'' function is named @code{<}.
  1765. Its result is true if the first argument is less than the second (or, if
  1766. there are more than two arguments, that they are in increasing order):
  1767. @example
  1768. (< 3 4) @result{} #t
  1769. (< -3 -4) @result{} #f
  1770. (< 2 3 5 7 11)) @result{} #t
  1771. @end example
  1772. The @code{if} special form takes two or three sub-expressions:
  1773. It evaluates the first expression.
  1774. If that is true it evaluates the second expression;
  1775. otherwise it evaluates the third expression, if provided:
  1776. @example
  1777. (if (< 3 4) (+ 5 5) (+ 5 6)) @result{} 10
  1778. @end example
  1779. We call @code{if} a special form rather than a function,
  1780. because for a function all the arguments are evaluated before the
  1781. function is called, but in a special form that is not neceassarily the case.
  1782. In addition to @code{#t} any value except @code{#f}
  1783. (and the Kawa-specific @code{#!null})
  1784. counts as ``true'' when evaluating the first expression of an @code{if}.
  1785. Unlike C or JavaScript both (zero) and @code{""} (the empty string) are true:
  1786. @example
  1787. (if 0 (+ 5 5) (+ 5 6)) @result{} 10
  1788. @end example
  1789. You can use @code{and}, @code{or},
  1790. and @code{not} to create complex boolean expressions.
  1791. Of these @code{and} and @code{or}
  1792. are special forms that only evaluate as many of the sub-expressions as needed.
  1793. @example
  1794. (if (not (and (>= i 0) (<= i 9)))
  1795. (display "error"))
  1796. @end example
  1797. You can use the @code{cond} form as an alternative to
  1798. @code{if}:
  1799. @example
  1800. (cond ((< 3 3) 'greater)
  1801. ((> 3 3) 'less)
  1802. (else ’equal)) @result{} equal
  1803. @end example
  1804. The null value (written as @code{#!null} in Kawa or @code{null} in Java)
  1805. is also considered as false.
  1806. @node Tutorial - Numbers
  1807. @section Numbers
  1808. @subheading Exact integers and fractions
  1809. Kawa has the usual syntax for decimal integers.
  1810. Addition, subtraction, and multiplication
  1811. are written using the usual @code{+},
  1812. @code{-}, and @code{*},
  1813. but these are all prefix functions that take a variable number of arguments:
  1814. @example
  1815. (+ 1 2 3) @result{} 6
  1816. (- 10 3 4) @result{} (- (- 10 3) 4) @result{} 3
  1817. (* 2 -6) @result{} -12
  1818. @end example
  1819. Kawa has arbitrary-precision integers.
  1820. Let us implement the @uref{http://en.wikipedia.org/wiki/Factorial,factorial} function.
  1821. Type in the following (we'll look at the syntax shortly):
  1822. @example
  1823. #|kawa:1|# @kbd{(define (factorial x)}
  1824. #|(---:2|# @kbd{ (if (< x 1) 1}
  1825. #|(---:3|# @kbd{ (* x (factorial (- x 1)))))}
  1826. @end example
  1827. (The prompt changes to indicate a continuation line.)
  1828. This binds the name @code{factorial}
  1829. to a new function, with formal parameter @code{x}.
  1830. This new function is immediately compiled to Java bytecodes,
  1831. and later a JIT compiler may compile it to native code.
  1832. A few tests:
  1833. @example
  1834. #|kawa:4|# @kbd{(list (factorial 3) (factorial 4))}
  1835. (6 24)
  1836. #|kawa:5|# @kbd{(factorial 30)}
  1837. 265252859812191058636308480000000
  1838. @end example
  1839. @subheading Floating-point real numbers
  1840. Given what was said above about being able to add, subtract and multiply integers,
  1841. the following may be unexpected:
  1842. @example
  1843. #|kawa:1|# @kbd{(/ 2 3)}
  1844. 2/3
  1845. #|kawa:2|# @kbd{(+ (/ 1 3) (/ 2 3))}
  1846. 1
  1847. @end example
  1848. In many languages, dividing two integers, as 2/3, would result in 0. At best,
  1849. the result would be a floating point number, similar to 0.666667. Instead,
  1850. Kawa has a @emph{rational} number type, which holds the results of divisions
  1851. @emph{exactly}, as a proper fraction. Hence, adding one third to two thirds
  1852. will always result in exactly one.
  1853. Floating-point real numbers are known in Kawa as @emph{inexact} numbers, as
  1854. they cannot be stored exactly. Consider:
  1855. @example
  1856. #|kawa:3|# @kbd{(exact? 2/3)}
  1857. #t
  1858. #|kawa:4|# @kbd{(exact? 0.33333333)}
  1859. #f
  1860. #|kawa:5|# @kbd{(exact->inexact 2/3)}
  1861. 0.6666666666666666
  1862. @end example
  1863. The first two examples check numbers for being @code{exact?}; there is a
  1864. corresponding @code{inexact?} test. The last shows how an exact number can be
  1865. converted to an inexact form.
  1866. Numbers are converted between exact and inexact versions when required
  1867. within operations or procedures:
  1868. @example
  1869. #|kawa:6|# @kbd{(+ 0.33333333 2/3)}
  1870. 0.9999999966666666
  1871. #|kawa:7|# @kbd{(inexact? (+ 0.33333333 2/3))}
  1872. #t
  1873. #|kawa:8|# @kbd{(sin 2/3)}
  1874. 0.618369803069737
  1875. @end example
  1876. @subheading Complex numbers
  1877. A @emph{complex} number is made from two parts: a @emph{real} part and an
  1878. @emph{imaginary} part. They are written @code{2+3i}. A complex number can
  1879. be manipulated just like other numbers:
  1880. @example
  1881. #|kawa:9|# @kbd{(+ 2+3i 5+2i)}
  1882. 7+5i
  1883. #|kawa:10|# @kbd{(* 2+3i 4-3i)}
  1884. 17+6i
  1885. #|kawa:11|# @kbd{(integer? (+ 2+3i -3i))}
  1886. #t
  1887. @end example
  1888. Notice how in the last example the result is an integer, which Kawa recognises.
  1889. Kawa also includes @ref{Quaternions,quaternion} numbers.
  1890. @subheading Units and dimensions
  1891. In many applications, numbers have a @emph{unit}. For example, 5 might be
  1892. a number of dollar bills, a weight on a scale, or a speed. Kawa enables us
  1893. to represent numbers as @emph{quantities}: numbers along with their unit.
  1894. For example, with weight, we might measure weight in pounds and ounces,
  1895. where an ounce is 1/16 of a pound.
  1896. Using Kawa, we can define units for our weight measurements, and specify the
  1897. units along with numbers:
  1898. @example
  1899. #|kawa:12|# @kbd{(define-base-unit pound "Weight")}
  1900. #|kawa:13|# @kbd{(define-unit ounce 0.0625pound)}
  1901. #|kawa:14|# @kbd{3pound}
  1902. 3.0pound
  1903. #|kawa:15|# @kbd{(+ 1pound 5ounce)}
  1904. 1.3125pound
  1905. @end example
  1906. In this example we define a base unit, the pound, and a unit based on it, the
  1907. ounce, which is valued at 0.0625 pounds (one sixteenth). Numbers can then be
  1908. written along with their unit (making them quantities). Arithmetic is possible
  1909. with quantities, as shown in the last line, and Kawa will do the smart thing
  1910. when combining units. In this case, 1 pound and 5 ounces is combined to make
  1911. 1.3125 pounds.
  1912. @node Tutorial - Functions
  1913. @section Functions
  1914. To declare a new function use @code{define},
  1915. which has the following form:
  1916. @example
  1917. (define (@var{function-name} @var{parameter-names}) @var{body})
  1918. @end example
  1919. This creates a new function named @var{function-name},
  1920. which takes @var{parameter-names} as parameters.
  1921. When the function is called, the @var{parameter-names}
  1922. are initialized with the actual arguments. Then @var{body}
  1923. is evaluated, and its value becomes the result of the call.
  1924. For example, in the @code{factorial} function we looked at recently,
  1925. the @var{function-name} is @code{factorial},
  1926. and the @var{parameter-names} is @code{x}:
  1927. @example
  1928. (define (factorial x)
  1929. (if (< x 1) 1
  1930. (* x (factorial (- x 1)))))
  1931. @end example
  1932. @subheading Anonymous functions
  1933. @c If you just evaluate a function nameA function is an actual variable you can evaluate xxx
  1934. An @emph{anonymous} function is simply a function which does not have a name.
  1935. We define an anonymous function using a @dfn{lambda expression}, which has
  1936. the following form:
  1937. @example
  1938. (lambda (@var{parameter-names}) @var{body})
  1939. @end example
  1940. The lambda expression has the @var{parameter-names} and @var{body} of a
  1941. function, but it has no name. What is the point of this?
  1942. An important example is creating a function to act on a list, perhaps using
  1943. @code{map}. The @code{map} function takes two parameters: the first is a
  1944. function which takes a value and returns a value; the second is a list. Here,
  1945. we want to double every number in the list.
  1946. The usual way of doing this is to create a named function, called
  1947. @code{double}, and then apply it to a list:
  1948. @example
  1949. #|kawa:1|# @kbd{(define (double x)}
  1950. #|.....2|# @kbd{ (* 2 x))}
  1951. #|kawa:3|# @kbd{(map double (list 1 2 3 4 5))}
  1952. (2 4 6 8 10)
  1953. @end example
  1954. Instead, anonymous functions make it easy to create a function to work on a
  1955. list, without having to define it in advance:
  1956. @example
  1957. #|kawa:4|# @kbd{(map (lambda (x) (* 2 x)) (list 1 2 3 4 5))}
  1958. (2 4 6 8 10)
  1959. #|kawa:5|# @kbd{(define y 3)}
  1960. #|kawa:6|# @kbd{(map (lambda (x) (* x y)) (list 1 2 3 4 5))}
  1961. (3 6 9 12 15)
  1962. @end example
  1963. The first example shows the double example rewritten as an anonymous function.
  1964. The second example shows how the anonymous function can be changed to
  1965. fit the place in which it is used: here, the value of @var{y} determines the
  1966. value by which the list values are multiplied.
  1967. Notice that we can name our anonymous functions, in just the same way we
  1968. name any value in Kawa, using @code{define}:
  1969. @example
  1970. (define double
  1971. (lambda (n)
  1972. (* 2 n)))
  1973. @end example
  1974. although more frequently we use the short-hand for defining functions, which we
  1975. have already met:
  1976. @example
  1977. (define (double n)
  1978. (* 2 n))
  1979. @end example
  1980. Anonymous functions are ``first-class values'' in Kawa, and can be passed to
  1981. other functions as arguments (like we did with @code{map}), and they can even
  1982. be created and returned by functions as results.
  1983. @subheading Optional, rest and keyword parameters
  1984. You can declare a function that takes optional arguments,
  1985. or a variable number of arguments. You can also use keyword parameters.
  1986. The following function illustrates the use of @emph{optional} arguments. The function
  1987. identifies an optional argument @code{z}: if the function is called with 3 arguments, @code{z}
  1988. will be bound to the third value, otherwise it will be @code{#f}.
  1989. @example
  1990. (define (addup x y #!optional z)
  1991. (if z
  1992. (+ x y z)
  1993. (+ x y)))
  1994. @end example
  1995. The following examples show @code{addup} applied to 2, 3 and invalid arguments. It is an error to
  1996. pass just one argument or more than three: @code{x} and @code{y} are compulsory, but @code{z} is
  1997. optional.
  1998. @example
  1999. #|kawa:12|# @kbd{(addup 1 2)}
  2000. 3
  2001. #|kawa:13|# @kbd{(addup 1 2 3)}
  2002. 6
  2003. #|kawa:14|# @kbd{(addup 1)}
  2004. /dev/stdin:14:1: call to 'addup' has too few arguments (1; min=2, max=3)
  2005. #|kawa:15|# @kbd{(addup 1 2 3 4)}
  2006. /dev/stdin:15:1: call to 'addup' has too many arguments (4; min=2, max=3)
  2007. @end example
  2008. In this example, a better way to define the function would be to include a
  2009. default value for @code{z}, for when its value is not given by the caller.
  2010. This is done as follows, with the same behavior as above:
  2011. @example
  2012. (define (addup x y #!optional (z 0))
  2013. (+ x y z))
  2014. @end example
  2015. You can include as many optional parameters as you wish, after the @code{#!optional}.
  2016. @emph{Rest} arguments are an alternative way to pass an undefined number of
  2017. arguments to a function. Here is @code{addup} written with rest arguments,
  2018. notice the variable name after the . (dot):
  2019. @example
  2020. (define (addup x y . args)
  2021. (+ x y (apply + args)))
  2022. @end example
  2023. The @code{args} are simply a list of all remaining values. The following now all work, as the
  2024. function only requires a minimum of two numbers:
  2025. @example
  2026. #|kawa:4|# @kbd{(addup 1 2)}
  2027. 3
  2028. #|kawa:5|# @kbd{(addup 1 2 3)}
  2029. 6
  2030. #|kawa:6|# @kbd{(addup 1 2 3 4 5 6 7 8)}
  2031. 36
  2032. @end example
  2033. An alternative way to identify the rest args is with @code{#!rest}:
  2034. @example
  2035. (define (addup x y #!rest args)
  2036. (+ x y (apply + args)))
  2037. @end example
  2038. Finally, it can be useful to identify parameters by name and, for this, Kawa
  2039. provides @emph{keyword} arguments. Consider the following function:
  2040. @example
  2041. #|kawa:38|# @kbd{(define (vector-3d #!key x y z)}
  2042. #|.....39|# @kbd{ (vector x y z))}
  2043. #|kawa:40|# @kbd{(vector-3d #:x 2 #:z 3 #:y 4)}
  2044. #(2 4 3)
  2045. @end example
  2046. @code{vector-3d} is defined with three keyword arguments: @code{x}, @code{y}, and @code{z}. When the
  2047. function is called, we identify the name for each value by writing @code{#:} at the start of the name.
  2048. This allows us to write the arguments in any order. Keyword parameters can also be given default
  2049. values, as with optional parameters. Keyword parameters with no default value, and no value in the caller,
  2050. will get the value @code{#f}.
  2051. In the caller, keywords are symbols with @code{#:} at the front (or @code{:} at
  2052. the end): @ref{Keywords,read more here}.
  2053. All these extended types of arguments are available both for ``named'' and for ``anonymous'' functions.
  2054. Optional, rest and keyword arguments can be mixed together, along with the usual arguments.
  2055. For details @ref{Extended formals,read more here.}
  2056. @node Tutorial - Variables
  2057. @section Variables
  2058. You can declare a variable using a @code{!} form.
  2059. This takes a variable name, and an expression. It declares a new
  2060. variable with the given name, and gives it the value of the expression.
  2061. @example
  2062. #|kawa:1|# @kbd{(! binary-kilo 1024)}
  2063. #|kawa:2|# @kbd{(! binary-mega (* binary-kilo binary-kilo))}
  2064. #|kawa:3|# @kbd{binary-mega}
  2065. 1048576
  2066. @end example
  2067. If you prefer, you can use @code{define} instead of @code{!}:
  2068. @example
  2069. #|kawa:1|# @kbd{(define binary-kilo 1024)}
  2070. #|kawa:2|# @kbd{(define binary-mega (* binary-kilo binary-kilo))}
  2071. #|kawa:3|# @kbd{binary-mega}
  2072. 1048576
  2073. @end example
  2074. The advantage of using @code{define} is that it is portable
  2075. to other Scheme implementations.
  2076. The advantages of using @code{!} is that it is shorter;
  2077. it generalizes to patterns (see later);
  2078. and it guards against accidentally ``shadowing'' a variable
  2079. by a nested variable with the same name.
  2080. A @code{!} (or @code{define}) typed into the command-line
  2081. defines a top-level variable.
  2082. You can also declare local variables, which are variables defined for
  2083. a given block of code. For example, in the following code @code{let}
  2084. is used to set up a local binding of @code{x} to 3: this does not affect
  2085. the outer binding of @code{x} to 5:
  2086. @example
  2087. (define x 5)
  2088. (let ((x 3))
  2089. (display x)) @result{} 3
  2090. (display x) @result{} 5
  2091. @end example
  2092. Alternative forms for defining local variables are
  2093. @code{let}, @code{let*}, or @code{letrec}/@code{letrec*}.
  2094. The differences are in the order in which definitions are made.
  2095. @code{let} evaluates all its definitions in the environment holding
  2096. at the start of the @code{let} statement. In the following example,
  2097. the local variables are defined using values from the global variables:
  2098. @example
  2099. (define x 5)
  2100. (define y 2)
  2101. (let ((x (+ 2 y)) ; uses value of global y, i.e. 2
  2102. (y (+ 3 x))) ; uses value of global x, i.e. 5
  2103. (display (list x y))) @result {} (4 8)
  2104. @end example
  2105. @code{let*} instead evaluates each definition in the environment holding
  2106. at the start of the @code{let*} statement, along with all @emph{previous}
  2107. local definitions. In the following example, @code{y} is now defined with the
  2108. @emph{local} value of @code{x}:
  2109. @example
  2110. (define x 5)
  2111. (define y 2)
  2112. (let* ((x (+ 2 y)) ; uses value of global y, i.e. 2
  2113. (y (+ 3 x))) ; uses value of local x, i.e. 4
  2114. (display (list x y))) @result {} (4 7)
  2115. @end example
  2116. @code{letrec/letrec*} are similar, but allow the definition of recursive
  2117. functions:
  2118. @example
  2119. (letrec ((is-even? (lambda (n) (and (not (= 1 n))
  2120. (or (zero? n)
  2121. (is-odd? (- n 1))))))
  2122. (is-odd? (lambda (n) (and (not (zero? n))
  2123. (or (= 1 n)
  2124. (is-even? (- n 1)))))))
  2125. (display (is-even? 11))) @result {} #f
  2126. @end example
  2127. @node Tutorial - Pictures
  2128. @section Composable pictures
  2129. The @code{pictures} library lets you create geometric shapes
  2130. and images, and combine them in interesting ways.
  2131. You first need to import the library:
  2132. @example
  2133. (import (kawa pictures))
  2134. @end example
  2135. The easiest way to use and learn the library
  2136. is with a suitable REPL, where you can type
  2137. expressions that evaluate to pictures values,
  2138. and view the resulting pictures directly on the console.
  2139. The easiest way is to start the @code{kawa} command with the @code{-w}
  2140. flag. Alternatively, you can use
  2141. a @ref{Using DomTerm,DomTerm}-based terminal emulator
  2142. such as @code{qtdomterm} (which is shown in the image below),
  2143. and then the @code{kawa} command.
  2144. @image{images/domterm-pictures-1}
  2145. The above image shows two simple examples: a filled
  2146. circle (radius 30 pixels, color magenta), and a non-filled rotated rectangle
  2147. (color maroon 3-pixel wide strokes).
  2148. See @ref{Composable pictures} for details and more examples.
  2149. @subheading Shapes and coordinates
  2150. A @dfn{shape} is a geometrical figure consisting of
  2151. one or more curves and lines. One kind of shape is a circle;
  2152. you can create one with the @code{circle} procedure,
  2153. specifying the radius in ``pixels''.
  2154. @example
  2155. #|kawa:1|# @kbd{(import (kawa pictures))}
  2156. #|kawa:2|# @kbd{(circle 30)}
  2157. @image{images/fill-circ-1}
  2158. @end example
  2159. It you print a shape, it will show it as a thin black curve.
  2160. A @dfn{point} has two real-numbered parts: the point's x-coordinate,
  2161. and its y-coordinate.
  2162. The x-coordinate increases as you move right along the page/screen,
  2163. while the y-coordinate increases as you move @emph{down}.
  2164. (Unlike traditional mathematics, where
  2165. the y-coordinate increases as you go up.)
  2166. The unit distance is one ``pixel'', which is defined as CSS or HTML.
  2167. You can create a point with @code{&P} operator.
  2168. For example:
  2169. @example
  2170. &P[30 20]
  2171. @end example
  2172. is a point 30 pixels right and 20 pixels down from the origin point.
  2173. To create a circle centered on that point do @code{(center 30 &P[30 20])}.
  2174. The expression @code{(rectangle &P[10 20] &P[50 40])} creates
  2175. a rectangle whose upper left corner is (10,20) and whose
  2176. lower right corner is (50,40).
  2177. A @dfn{dimension} is a pair, a width and height,
  2178. and is written:
  2179. @example
  2180. &D[@var{width} @var{height}]
  2181. @end example
  2182. In addition to being used for sizes,
  2183. a dimension is also used for relative offsets.
  2184. For example, the previous rectangle could also
  2185. be written @code{(rectangle &P[10 20] &D[40 20])}.
  2186. You can use @code{line} to create a line.
  2187. More generally, if you specify @var{n} points you get a
  2188. @dfn{polyline} of @var{n-1} line segments:
  2189. @example
  2190. #|kawa:3|# @kbd{(line &P[10 20] &P[50 60] &P[90 0])}
  2191. @image{images/polyline-1}
  2192. @end example
  2193. The same line using dimensions for relative offsets:
  2194. @example
  2195. #|kawa:4|# @kbd{(line &P[10 20] &D[40 20] &D[40 -60])}
  2196. @end example
  2197. A @dfn{closed shape} is one whose end point is the same as its start point.
  2198. The @code{polygon} function creates one using straight line segments
  2199. @example
  2200. #|kawa:5|# @kbd{(polygon &P[10 20] &P[50 60] &P[90 0])}
  2201. @image{images/polygon-1}
  2202. @end example
  2203. @subheading Colors and filling
  2204. You can override the default color (black) using the
  2205. @code{with-paint} procedure, which takes a color and a picture
  2206. to produce a new picture:
  2207. @example
  2208. #|kawa:6|# @kbd{(with-paint 'red (circle 32))}
  2209. @end example
  2210. The first argument can be either one of the standard CSS/HTML5 color
  2211. names (such as @code{'red} or @code{'medium-slate-blue}),
  2212. or an integer representing an sRGB color, usually written
  2213. as a hex literal in the form @code{#xRRGGBB}:
  2214. @example
  2215. #|kawa:7|# @kbd{(with-paint #x0808FF (circle 32))}
  2216. @end example
  2217. The name @code{with-paint} is because the first argument
  2218. can be not just a color, but a general ``paint'', such as
  2219. a gradient or a background image. However, we won't go into that.
  2220. If the shape is closed, you can ``fill'' its inside:
  2221. @example
  2222. (fill (circle 32))
  2223. @end example
  2224. You can change the color using @code{with-paint}:
  2225. @example
  2226. (with-paint 'goldenrod (fill (circle 32)))
  2227. @end example
  2228. or as an extra argument to @code{fill}:
  2229. @example
  2230. (fill 'goldenrod (circle 32))
  2231. @end example
  2232. draw TODO
  2233. @subheading Images
  2234. An image is a picture represented as a rectangular grid of color values.
  2235. It may be a photograph from a camera, or be created by a painting
  2236. program like Photoshop or gimp.
  2237. You can use @code{image-read} to read an image from a file,
  2238. typically a @code{.png} or @code{.jpg} file.
  2239. @example
  2240. #|kawa:10|# @kbd{(define img1 (image-read "http://pics.bothner.com/2013/Cats/06t.jpg"))}
  2241. #|kawa:11|# @kbd{img1}
  2242. @image{images/image-cat-1a}
  2243. @end example
  2244. @subheading Transforms TODO
  2245. @example
  2246. #|kawa:12|# @kbd{(scale 0.6 (rotate 30 img1))}
  2247. @image{images/image-cat-1b}
  2248. @end example
  2249. @subheading Combining and adjusting pictures TODO
  2250. @subheading Using and combining pictures TODO
  2251. @node Tutorial - Sequences
  2252. @section Lists and sequences
  2253. A @dfn{sequence} is a generalized array or list:
  2254. Zero or more values treated as a compound value.
  2255. Sequences have certain common operations, including indexing and iteration.
  2256. (@i{Technical note:} Sequences generally implement the @code{java.util.List}
  2257. interface, but Kawa will also treat strings and native
  2258. Java arrays as sequences.)
  2259. @subheading Lists
  2260. In traditional Lisp-family languages, the @dfn{list} is the
  2261. most important kind of sequence.
  2262. (Don't confuse Java's @code{List} interface with Kawa's use of the
  2263. word @i{list}. They're related, in that a Kawa ``list'' implements
  2264. the @code{List} interface, so any @i{list} is also @code{List},
  2265. but not vice versa.)
  2266. A list is implemented as a chain of linked @dfn{pairs}.
  2267. You can create a constant list by quoting a parenthesized list:
  2268. @example
  2269. '(3 4 (10 20 30) "a string")
  2270. @end example
  2271. See @ref{Lists} for details and operations.
  2272. @subheading Vectors
  2273. A @dfn{vector} is a sequence that is implemented by storing the elements
  2274. side-by-side in memory.
  2275. A vector uses less space than a list of the same length,
  2276. and is generally more efficient than a list.
  2277. To create a vector you can use a bracketed list:
  2278. @example
  2279. (! vec1 ['A 'B 'C 'D 'E 'F])
  2280. @end example
  2281. This creates a vector of 6 symbols and binds it to @code{vec1}.
  2282. To select an element you can use the traditional
  2283. @code{vector-ref} procedure:
  2284. @example
  2285. (vector-ref vec1 3) @result{} 'D
  2286. @end example
  2287. Alternatively, in Kawa you can use function-call notation:
  2288. @example
  2289. (vec1 3) @result{} 'D
  2290. @end example
  2291. You can also create a vector using the traditional @code{vector} constructor:
  2292. @example
  2293. (! vec2 (vector 'A 'B 'C 'D 'E 'F))
  2294. @end example
  2295. There is one important difference between @code{vec1} and @code{vec2}:
  2296. You can modify @code{vec2} by changing some or all of its elements.
  2297. You can't do that for @code{vec1}.
  2298. (We say that @code{vec1} is an @dfn{immutable} or @dfn{constant} vector,
  2299. while @code{vec1} is a @dfn{mutable} or @dfn{modifiable} vector.)
  2300. To change an element use either the traditional @code{vector-set!}
  2301. procedure, or function-call notation:
  2302. @example
  2303. (vector-set! vec2 2 'Y)
  2304. (set! (vec2 4) 'Z)
  2305. vec2 @result{} ['A 'B 'Y 'D 'Z 'F]
  2306. (vector-set! vec1 2 'Y) @result{} @i{throws exception}
  2307. @end example
  2308. See @ref{Vectors} for details and operations.
  2309. @subheading Java arrays and primitive vectors
  2310. See @ref{Array operations, Using Java arrays} for examples.
  2311. @subheading Indexing of general sequences
  2312. You can use function-call notation to index a generalized sequence,
  2313. whether it is a list, vector, any @code{java.util.List},
  2314. native Java array, or string:
  2315. @example
  2316. ((list 'A 'B 'C 'D) 2) @result{} 'C
  2317. ("abcdef" 3) @result{} @result{}
  2318. (! farr (float[] 1.5 3 4.5)) ;; native Java array
  2319. (farr 2) @result{} 4.5
  2320. @end example
  2321. Note that indexing a list with an index @var{i} will be slow, since it
  2322. has to step through the list @var{i} times. (So don't do that!)
  2323. @subheading Ranges
  2324. A @dfn{range} is a sequence of numbers in order,
  2325. spaced uniformly apart. Usually, these are (exact) integers
  2326. that increase by one. The usual notation is:
  2327. @example
  2328. [@var{start} <: @var{end}]
  2329. @end example
  2330. This is the sequence of integers starting with the integer @var{start}
  2331. (inclusive) and ending with the integer @var{end} (exclusive).
  2332. For example @code{[3 <: 7]} is the sequence @code{[3 4 5 6]}.
  2333. The @samp{<:} is a keyword; the @code{<} is a mnemonic for the
  2334. set of integers that are @code{<} the end value 6.
  2335. You can also use @code{<=:} if you want to include the upper bound:
  2336. @code{[4 <=: 8]} is @code{[4 5 6 7 8]}.
  2337. You can use @code{>=:} or @code{>:} for a decreasing range.
  2338. @code{[5 >=: 1]} or @code{[5 >: 0]} both evaluate to @code{[5 4 3 2 1]}.
  2339. You can also specifify a step value: @code{[1 by: 2 <=: 9]},
  2340. which evaluates to @code{[1 3 5 7 9]}.
  2341. (@ref{Ranges,Details here}.)
  2342. @subheading Using vector and ranges indexes
  2343. If an index is a sequence of integers,
  2344. the result is a new sequence (of the same type)
  2345. selecting only the elements matching the index values.
  2346. For example:
  2347. @example
  2348. #|kawa:2|# @kbd{(vec1 [3 5 2])}
  2349. #(D F C)
  2350. @end example
  2351. In general, @code{((V1 V2) I)} is @code{(V1 (V2 I))}.
  2352. You can use a range to create a slice - a contiguous subset of a list.
  2353. @example
  2354. #|kawa:3|# @kbd{(vec1 [2 <: 6])}
  2355. #(C D E F)
  2356. @end example
  2357. A range is different from a vector integer in that you can use
  2358. a range as the index in the LHS of a set!:
  2359. @example
  2360. #|kawa:4|# @kbd{(set! (vec1 [2 <: 4]) #(a b c d e))}
  2361. #|kawa:5|# @kbd{vec1}
  2362. #(A B a b c d e E F)
  2363. @end example
  2364. Notice how the number of replaced elements can be different
  2365. then the number of elements in the replacement value.
  2366. I.e. you can do insertion and deletion this way.
  2367. @example
  2368. #|kawa:7|# @kbd{(! str1 (string-copy "ABCDEF"))}
  2369. #|kawa:8|# @kbd{(set! (str1 [2 <: 5]) "98")}
  2370. AB98F
  2371. @end example
  2372. @node Tutorial - Objects
  2373. @section Creating and using objects
  2374. An @dfn{object} is a value that has the following features:
  2375. @itemize
  2376. @item
  2377. class - each object is an instance of a specific class,
  2378. making it part of the class hierarchy, which is an important
  2379. aspect of the type system;
  2380. @item
  2381. properties - various fields and methods, depending on the class;
  2382. @item
  2383. identity - it is distinct from all other objects,
  2384. even if all the properties are the same.
  2385. @end itemize
  2386. We later discuss @ref{Tutorial - Classes,how to write a new class}.
  2387. Here we assume you're using an existing class, which
  2388. could be written in Java or Scheme.
  2389. @subheading Creating a new object
  2390. To create a new object of class @code{T} you call @code{T} as if it
  2391. were a function, passing it the various constructor arguments:
  2392. @example
  2393. (java.io.File "src" "build.xml")
  2394. @end example
  2395. If there are keyword arguments they are used to initialize
  2396. the corresponding named properties:
  2397. @example
  2398. (! button1 (javax.swing.JButton text: "Do it!" tool-tip-text: "do it"))
  2399. @end example
  2400. This create a new @code{JButton} object (using @code{JButton}'s
  2401. default constructor), and sets the @code{text} and @code{tool-tip-text}
  2402. properties (by calling @code{JButton}'s @code{setText}
  2403. and @code{setToolTipText} methods).
  2404. If there are constructor arguments, they must come before the keywords.
  2405. For objects that have components or elements, you
  2406. can list these at the end. For example:
  2407. @example
  2408. (java.util.ArrayList 11 22 33)
  2409. @end example
  2410. This creates a fresh @code{java.util.ArrayList} (using the
  2411. default constructor), and then calls the @code{add} method 3 times.
  2412. If you prefer you can use the @code{make} procedure,
  2413. but that only handle simple constructor calls:
  2414. @example
  2415. (make java.io.File "src" "build.xml")
  2416. @end example
  2417. See @ref{Allocating objects} for details.
  2418. @subheading Calling instance methods
  2419. Given an object @var{obj} of a class that has a method @var{meth},
  2420. you can call it with argumens @var{v1} ... @var{v2} using @ref{Colon notation}:
  2421. @example
  2422. (@var{obj}:@var{meth} @var{v1} ... @var{v2})
  2423. @end example
  2424. For example:
  2425. @example
  2426. (button1:paintImmediately 10 10 30 20)
  2427. @end example
  2428. If you prefer, you can use the @code{invoke} procedure,
  2429. normally with a quoted method name:
  2430. @example
  2431. (invoke button1 'paintImmediately 10 10 30 20)
  2432. @end example
  2433. You need to use @code{invoke} (rather than colon notation)
  2434. if @var{obj} is a @code{Class} or a type expression, or its class
  2435. implements @code{gnu.mapping.HasNamedParts}.
  2436. See @ref{Method operations} for details.
  2437. @subheading Accessing properties
  2438. If @var{obj} has a field or property named @var{fld} you can also use colon
  2439. notation:
  2440. @example
  2441. @var{obj}:@var{fld}
  2442. @end example
  2443. You use the same syntax whether @var{fld} is an actual field in the
  2444. object, or a @dfn{property} (in the Java Beans sense). The
  2445. latter is implemented using a getter/setter pair:
  2446. Methods named @code{get@var{F}} and @code{set@var{F}}, respectively.
  2447. For example:
  2448. @example
  2449. button1:tool-tip-text
  2450. @end example
  2451. is equivalent to:
  2452. @example
  2453. (button1:getToolTipText)
  2454. @end example
  2455. You can also change a field or property using colon notation:
  2456. @example
  2457. (set! @var{obj}:@var{fld} @var{value})
  2458. @end example
  2459. For example:
  2460. @example
  2461. (set! button1:tool-tip-text "really do it!")
  2462. @end example
  2463. This is equivalent to:
  2464. @example
  2465. (button1:setToolTipText "really do it!")
  2466. @end example
  2467. Instead of colon notation, you can use the @code{field} procedure.
  2468. See @ref{Field operations} for details.
  2469. @subheading Static fields and methods
  2470. Kawa views static properties and methods as
  2471. properties and methods of the class itself.
  2472. To call a static method use the syntax:
  2473. @example
  2474. (@var{clas}:@var{meth} @var{v1} ... @var{vn})
  2475. @end example
  2476. For example:
  2477. @example
  2478. (java.math.BigDecimal:valueOf 12345 2) @result{} 123.45
  2479. @end example
  2480. To access a static field do @code{@var{clas}:@var{fld}}. For example:
  2481. @example
  2482. java.awt.Color:RED
  2483. @end example
  2484. You can also use the @code{static-field} and @code{invoke-static} procedures.
  2485. @node Tutorial - Types
  2486. @section Types and declarations
  2487. A @dfn{type} is a named value for a set
  2488. of objects with related properties.
  2489. For example, @code{vector} is the type for standard Scheme vectors.
  2490. You can use a type to specify that a variable can only have
  2491. values of the specified type:
  2492. @example
  2493. #|kawa:5|# @kbd{(define v ::vector #(3 4 5))}
  2494. #|kawa:6|# @kbd{v}
  2495. #(3 4 5)
  2496. #|kawa:7|# @kbd{(set! v 12)}
  2497. /dev/stdin:7:1: warning - cannot convert literal (of type gnu.math.IntNum) to vector
  2498. Value (12) for variable 'v' has wrong type (gnu.math.IntNum) (gnu.math.IntNum cannot be cast to gnu.lists.FVector)
  2499. at atInteractiveLevel$7.run(stdin:7)
  2500. at gnu.expr.ModuleExp.evalModule(ModuleExp.java:302)
  2501. at kawa.Shell.run(Shell.java:275)
  2502. at kawa.Shell.run(Shell.java:186)
  2503. at kawa.Shell.run(Shell.java:167)
  2504. at kawa.repl.main(repl.java:870)
  2505. Caused by: java.lang.ClassCastException: gnu.math.IntNum cannot be cast to gnu.lists.FVector
  2506. ... 6 more
  2507. @end example
  2508. Using a type specification catches errors, and makes your programs
  2509. more readable. It can also allow the Kawa compiler to generate code
  2510. that runs faster.
  2511. You can use a type to check that a value is an instance of the type,
  2512. using either the @code{instance?} function:
  2513. @example
  2514. (instance? #(3 4 5) vector) @result{} #t
  2515. (instance? '(3 4 5) vector) @result{} #f
  2516. @end example
  2517. As a convenience, you can use a type-name followed by a ``@code{?}'':
  2518. @example
  2519. (@var{type}? @var{val}) == (instance? @var{val} @var{type})
  2520. @end example
  2521. You can ``call'' a type as if it were a function,
  2522. which constructs a new instance of the type.
  2523. The following example shows how to construct a normal Scheme vector,
  2524. and a Java array of ints:
  2525. @example
  2526. #|kawa:1|# @kbd{(vector)}
  2527. #()
  2528. #|kawa:2|# @kbd{(instance? (vector) vector)}
  2529. #t
  2530. #|kawa:3|# @kbd{(define x (int[] 1 2 3))}
  2531. #|kawa:4|# @kbd{x}
  2532. [1 2 3]
  2533. #|kawa:5|# @kbd{(instance? x int[])}
  2534. #t
  2535. @end example
  2536. A fully-qualified Java class is a type name.
  2537. So are the names of Java primitive types.
  2538. So are Java array types, as shown above.
  2539. e.g. a JFrame is constructed by using its class name as a function:
  2540. @example
  2541. #|kawa:6|# @kbd{(javax.swing.JFrame)}
  2542. javax.swing.JFrame[frame0,0,25,0x0,invalid,hidden,layout=java.awt.BorderLayout,
  2543. title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,
  2544. rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,
  2545. layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,
  2546. flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
  2547. @end example
  2548. A type is a true run-time value:
  2549. @example
  2550. (define mytypes (list vector list string))
  2551. (instance? #(3 4 5) (car mytypes) @result{} #t
  2552. @end example
  2553. The @code{define-alias} form is useful for defining shorter names
  2554. for types, like a generalization of Java's @code{import} statement:
  2555. @example
  2556. (define-alias jframe javax.swing.JFrame)
  2557. @end example
  2558. @node Tutorial - Exceptions and errors
  2559. @section Exceptions and errors
  2560. Kawa supports the exception framework and forms
  2561. from R6RS and R7RS. See @ref{Exceptions} for details.
  2562. @subheading Native exception handling
  2563. You can also work with native Java exceptions at a low level.
  2564. The @code{primitive-throw} procedure throws a @code{Throwable} value.
  2565. It is implemented just like Java's @code{throw}.
  2566. @example
  2567. (primitive-throw (java.lang.IndexOutOfBoundsException "bad index"))
  2568. @end example
  2569. You can catch an exception with the @code{try-catch} syntax. For example:
  2570. @example
  2571. (try-catch
  2572. (do-a-bunch-of-stuff)
  2573. (ex java.lang.Throwable
  2574. (format #f "caught ~a~%~!" ex)
  2575. (exit)))
  2576. @end example
  2577. A @code{try-finally} does the obvious:
  2578. @example
  2579. (define (call-with-port port proc)
  2580. (try-finally
  2581. (proc port)
  2582. (close-port port)))
  2583. @end example
  2584. Both @code{try-catch} and @code{try-finally} are
  2585. expression forms that can return values, while the corresponding
  2586. Java forms are statements that cannot return values.
  2587. @node Tutorial - Classes
  2588. @section Classes
  2589. See @ref{Defining new classes} for the gory details; no tutorial yet.
  2590. @node Tutorial - Other Java features
  2591. @section Other Java features
  2592. @subheading Import
  2593. The @code{import} form can be used to avoid having to write
  2594. fully-qualified class names. For example:
  2595. @example
  2596. (import (class java.util
  2597. Map
  2598. (HashMap HMap)))
  2599. @end example
  2600. This defines aliases for two classes in the @code{java.util} package,
  2601. one with renaming:
  2602. @code{Map} is an alias for @code{java.util.Map},
  2603. and @code{HMap} is an alias for @code{java.util.HashMap}.
  2604. The @code{class} keyword is needed because the @code{import}
  2605. form is also used for Kawa's module system.
  2606. See @ref{importing-class-names} and @ref{Importing} for details.
  2607. @subheading Synchronized blocks
  2608. You can use a @code{synchronized} expression:
  2609. @example
  2610. (synchronized obj form1 ... formn)
  2611. @end example
  2612. This waits until it can get an exclusive lock on @var{obj}
  2613. and then evaluates @var{form1} through @var{formn}.
  2614. Unlike Java, this is an expression and returns the value of @var{formn}.
  2615. @subheading Annotations
  2616. You can write annotation declarations - see @ref{Annotations} for details.
  2617. Kawa does not yet support annotations on types,
  2618. or declaring new annotation classes.
  2619. @part Reference Documentation
  2620. @node Running
  2621. @chapter How to start up and run Kawa
  2622. The easiest way to start up Kawa is to run the @samp{kawa} program.
  2623. This finds your Java interpreter, and sets up @samp{CLASSPATH} correctly.
  2624. If you have installed Kawa such that @code{$PREFIX/bin} is in your @code{$PATH},
  2625. just do:
  2626. @example
  2627. kawa
  2628. @end example
  2629. However, @samp{kawa} only works if you have a Unix-like environment.
  2630. On some platforms, @samp{kawa} is a program that uses the GNU
  2631. @samp{readline} library to provide input line editing.
  2632. To run Kawa manually, you must start a Java Virtual Machine.
  2633. How you do this depends on the Java implementation.
  2634. For Oracle's JDK, and some other implementations, you must have the
  2635. Java evaluator (usually named @code{java}) in your @code{PATH}.
  2636. You must also make sure that the @code{kawa/repl.class} file,
  2637. the rest of the Kawa packages, and the standard Java
  2638. packages can be found by searching CLASSPATH.
  2639. @xref{Running Java}.
  2640. Then you do:
  2641. @example
  2642. java kawa.repl
  2643. @end example
  2644. In either case, you will then get the @samp{#|kawa:1|#} prompt,
  2645. which means you are
  2646. in the Kawa read-eval-print-loop. If you type a Scheme
  2647. expression, Kawa will evaluate it. Kawa will then print the
  2648. result (if there is a non-"void" result).
  2649. @menu
  2650. * Options:: Command-line arguments
  2651. * Scripts:: Running Command Scripts
  2652. * REPL Console:: The REPL (read-eval-print-loop) console
  2653. * Exiting:: Exiting Kawa
  2654. * Compiling:: Compiling to byte-code
  2655. @end menu
  2656. @node Options, Scripts, Running, Running
  2657. @section Command-line arguments
  2658. @cindex options
  2659. You can pass various flags to Kawa, for example:
  2660. @example
  2661. kawa -e '(display (+ 12 4))(newline)'
  2662. @end example
  2663. or:
  2664. @example
  2665. java kawa.repl -e '(display (+ 12 4))(newline)'
  2666. @end example
  2667. Either causes Kawa to print @samp{16}, and then exit.
  2668. At startup, Kawa executes an init file from the user's home
  2669. directory.
  2670. The init file is named @code{.kawarc.scm} on Unix-like systems
  2671. (those for which the file separator is @code{'/'}),
  2672. and @code{kawarc.scm} on other systems.
  2673. This is done before the read-eval-print loop
  2674. or before the first @code{-f} or @code{-c} argument. (It is not run
  2675. for a @code{-e} command, to allow you to set options to override
  2676. the defaults.)
  2677. @subsection Argument processing
  2678. Kawa processes the command-line arguments in order.
  2679. Options (which either start with @samp{-} or contain a @samp{=})
  2680. may ``use up'' one or more command arguments.
  2681. Some of the options (@samp{-c}, @samp{-e}, @samp{-f}, @samp{-s},
  2682. @samp{-C}, @code{-w}, @samp{--}, @code{--browse-manual})
  2683. are @dfn{action options}; others set various properties.
  2684. When all the command-line arguments have been ``used up''
  2685. and if no action options have been seen,
  2686. then Kawa enters an interactive read-eval-print loop.
  2687. (If an action option has been seen, we're done.)
  2688. If the next command-line argument is not an option
  2689. (does not start with @samp{-} nor contains a @samp{=})
  2690. then we're done if we've seen an action option (and the
  2691. last action option wasn't preceded by @code{--with-arg-count}).
  2692. (Presumably any remaining arguments were command-line-arguments
  2693. used by the action option.)
  2694. Otherwise, the first remaining argument names either a
  2695. file that is read and evaluated, or a compiled class.
  2696. In the former case, the whole file is read and compiled as a module
  2697. before being loaded (unlike the @code{-f} flag which reads and
  2698. evaluates the file command by command.)
  2699. If the argument is the fully-qualified name of a class,
  2700. then the class is loaded, an instance allocated,
  2701. and its @code{run} method invoked. If the class was compiled from
  2702. a Kawa Scheme module, then invoking @code{run} has the
  2703. effect of evaluating the module body.
  2704. The @code{command-line-arguments} vector is set to any remaining
  2705. arguments after the file/class name.
  2706. (This can be overridden with the @code{--with-arg-count} option.
  2707. Command-line processing continues if there are any further arguments.)
  2708. @subsection General options
  2709. @table @code
  2710. @item -e @var{expr}
  2711. Kawa evaluates @var{expr}, which contains one or more Scheme expressions.
  2712. Does not cause the @code{~/.kawarc.scm} init file to be run.
  2713. @item -c @var{expr}
  2714. Same as @samp{-e @var{expr}}, except that it
  2715. does cause the @code{~/.kawarc.scm} init file to be run.
  2716. @item -f @var{filename-or-url}
  2717. Kawa reads and evaluates expressions from the file named
  2718. by @var{filename-or-url}. If the latter is @samp{-},
  2719. standard input is read (with no prompting). Otherwise,
  2720. it is equivalent to evaluating @samp{(load "@var{filename-or-url}")}.
  2721. The @var{filename-or-url} is interpreted as a URL
  2722. if it is absolute - it starts with a "URI scheme" like @code{http:}.
  2723. @item -s
  2724. @itemx --
  2725. The remaining arguments (if any) are passed to @samp{command-line-arguments}
  2726. and (the @code{cdr} of) @code{(command-line}),
  2727. and an interactive read-eval-print loop is started.
  2728. This uses the same "console" as where you started up Kawa;
  2729. use @samp{-w} to get a new window.
  2730. @item --script @var{filename-or-url}
  2731. @itemx --script@var{N} @var{filename-or-url}
  2732. The global variable @samp{command-line-arguments} is set to the remaining
  2733. arguments (if any).
  2734. Kawa reads and evaluates expressions from the file named
  2735. by @var{filename-or-url}.
  2736. If @code{script} is followed by an integer @var{N},
  2737. then @var{N} lines are skipped first.
  2738. Skipping some initial lines is useful if you want to have a non-Kawa
  2739. preamble before the actual Kawa code.
  2740. One use for this is for Kawa shell scripts (@pxref{Scripts}).
  2741. @item -w
  2742. @itemx -w@var{sub-option}
  2743. Creates a new top-level window, and runs an interactive read-eval-print
  2744. in the new window. See @ref{New-Window}.
  2745. Same as @code{-e (scheme-window #t)}.
  2746. You can specify multiple @samp{-w} options, and also use @samp{-s}.
  2747. @item --help
  2748. Prints out some help.
  2749. @item --version
  2750. Prints out the Kawa version number, and then exits.
  2751. If Kawa was built with a @code{.git} repository present,
  2752. also prints the result of @code{git describe}.
  2753. @anchor{browse-manual-option}
  2754. @item --browse-manual
  2755. @itemx --browse-manual=@var{command}
  2756. Browse a local copy of the documentation (this manual).
  2757. This creates a mini web-server that reads
  2758. from @code{doc/kawa-manual.epub}, which is
  2759. included in the binary distributions, but not built by default from source.
  2760. If no @var{command} is specified, creates a new window or tab
  2761. in your default web browser.
  2762. If @var{command} is a string containing @code{%U},
  2763. then Kawa replaces @code{%U} with a URL that references itself,
  2764. and then executes the resulting command.
  2765. If @var{command} does not contain @code{%U}, then
  2766. @var{command} becomes @var{command}@code{" %U"}.
  2767. For example to use the Firefox browser to browse the manual do either of:
  2768. @example
  2769. kawa --browse-manual=firefox
  2770. kawa --browse-manual="firefox %U"
  2771. @end example
  2772. @item --server @var{portnum}
  2773. Start a server listening from connections on the specified @var{portnum}.
  2774. Each connection using the Telnet protocol causes a new read-eval-print-loop
  2775. to start. This option allows you to connect using any
  2776. Telnet client program to a remote "Kawa server".
  2777. @item --with-arg-count=@var{argc}
  2778. This option is used before an action option (such as @code{-f}).
  2779. The @var{argc} arguments after the action become the
  2780. value of the @code{command-line-arguments} during the action.
  2781. When the action is finished, command-line-processing resumes
  2782. after skipping the @var{argc} arguments.
  2783. For example:
  2784. @example
  2785. $ kawa -f a.scm -f b.scm x y
  2786. @end example
  2787. When evaluating @code{a.scm} the @code{command-line-arguments}
  2788. by default is @emph{all} the remaining arguments: @code{["-f" "b.scm" "x" "y"]}.
  2789. Then @code{b.scm} is evaluated with @code{command-line-arguments}
  2790. set to @code{["x" "y"]}
  2791. @example
  2792. $ kawa --with-arg-count=0 -f a.scm -f b.scm x y
  2793. @end example
  2794. In this case @code{a.scm} is evaluated with @code{command-line-arguments}
  2795. set to the empty vector @code{[]}, and then @code{b.scm} is evaluated with @code{command-line-arguments}
  2796. set to @code{["x" "y"]}
  2797. @example
  2798. $ kawa --with-arg-count=4 -f a.scm -f b.scm x y
  2799. @end example
  2800. In this case @code{a.scm} is evaluated with @code{command-line-arguments}
  2801. set to @code{["-f" "b.scm" "x" "y"]}. Since command-line processing
  2802. skips the arguments specified by @code{--with-arg-count=4},
  2803. in this case @code{b.scm} is not evaluated.
  2804. @end table
  2805. @subsection Options for language selection
  2806. @table @code
  2807. @item --scheme
  2808. Set the default language to Scheme.
  2809. (This is the default unless you select another language,
  2810. or you name a file with a known extension on the command-line.)
  2811. @item --r5rs
  2812. @itemx --r6rs
  2813. @itemx --r7rs
  2814. Provide better compatibility with the specified Scheme standards.
  2815. (This is a work-in-progress.)
  2816. For example @code{--r6rs} aims to disable Kawa extensions
  2817. that conflict with R6RS. It does not aim to disable all extensions,
  2818. only incompatible extensions.
  2819. These extensions disable the colon operator and keyword literals,
  2820. as well as the use of initial @samp{@@} as a splicing operator.
  2821. The ``@code{l}'' exponent suffix of a number literal creates a
  2822. floating-point double, rather than a @code{BigInteger}.
  2823. Selecting @code{--r5rs} makes symbols by default
  2824. case-insensitive.
  2825. @item --elisp
  2826. @itemx --emacs
  2827. @itemx --emacs-lisp
  2828. Set the default language to Emacs Lisp.
  2829. (The implementation is quite incomplete.)
  2830. @item --lisp
  2831. @itemx --clisp
  2832. @itemx --clisp
  2833. @itemx --commonlisp
  2834. @itemx --common-lisp
  2835. Set the default language to CommonLisp.
  2836. (The implementation is @emph{very} incomplete.)
  2837. @item --krl
  2838. Set the default language to KRL. See @ref{KRL}.
  2839. @item --brl
  2840. Set the default language to KRL, in BRL-compatibility mode. See @ref{KRL}.
  2841. @item --xquery
  2842. Set the default language to the draft XML Query language.
  2843. See the @uref{http://www.gnu.org/software/qexo/,Kawa-XQuery page}
  2844. for more information.
  2845. @item --xslt
  2846. Set the default language to XSLT (XML Stylesheet Language Transformations).
  2847. (The implementation is @emph{very} incomplete.)
  2848. See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
  2849. for more information.
  2850. @item --pedantic
  2851. Try to follow the approprate language specification to the letter,
  2852. even in corner cases, and even if it means giving up some
  2853. Kawa convenience features. This flag so far only affects
  2854. the XQuery parser, but that will hopefully change.
  2855. @end table
  2856. @subsection Options for warnings and errors
  2857. @table @code
  2858. @cindex @code{--warn-@var{whatever}}
  2859. @cindex @code{--no-warn-@var{whatever}}
  2860. @pindex @code{warn-undefined-variable}
  2861. @item --warn-undefined-variable
  2862. Emit a warning if the code references a variable which is neither in
  2863. lexical scope nor in the compile-time dynamic (global) environment.
  2864. This is useful for catching typos.
  2865. (A @code{define-variable} form can be used to silence warnings.
  2866. It declares to the compiler that a variable is to be resolved dynamically.)
  2867. This defaults to on;
  2868. to turn it off use the @code{--no-warn-undefined-variable} flag.
  2869. @pindex warn-unknown-member
  2870. @item --warn-unknown-member
  2871. Emit a warning if the code references a named member (field or method)
  2872. for which there is no match in the compile-time type of the receiver.
  2873. This defaults to on;
  2874. to turn it off use the @code{--no-warn-unknown-member} flag.
  2875. @pindex warn-invoke-unknown-method
  2876. @item --warn-invoke-unknown-method
  2877. Emit a warning if the @code{invoke} function calls a named method
  2878. for which there is no matching method in the compile-time type of the receiver.
  2879. This defaults to the value of @code{--warn-unknown-member},
  2880. to turn it off use the @code{--no-warn-invoke-unknown-method} flag.
  2881. @pindex warn-unused
  2882. @item --warn-unused
  2883. Emit a warning if a variable is unused or code never executed. This defaults
  2884. to on; to turn it off use the @code{--no-warn-unused} flag.
  2885. @pindex warn-uninitialized
  2886. @item --warn-uninitialized
  2887. Warn if accessing an uninitialized variable.
  2888. This defaults to on; to turn it off use the @code{--no-warn-uninitialized} flag.
  2889. @cindex warn-unreachable
  2890. @item --warn-unreachable
  2891. Emit a warning if the code can never be executed. This defaults to on;
  2892. to turn it off use the @code{--no-warn-unreachable} flag.
  2893. @cindex warn-void-used
  2894. @item --warn-void-used
  2895. Emit a warning if an expression depends on an expression
  2896. that is void (always has zero values), including call to @code{void}
  2897. functions and method. Also warn if an expression depends on a
  2898. conditional (@code{if}) that has no ``else'' clause.
  2899. Examples include using the value of @code{set-car!} as
  2900. an argument to a function, or to initialize a variable.
  2901. This defaults to on;
  2902. to turn it off use the @code{--no-warn-void-used} flag.
  2903. @pindex warn-as-error
  2904. @item --warn-as-error
  2905. Treat a compilation warning as if it were an error and halt compilation.
  2906. @item --max-errors=@var{value}
  2907. Print no more than @var{value} errors or warnings (at a time).
  2908. The value @code{-1} removes the limit.
  2909. The initial default is 20. (A single error may so confuse Kawa
  2910. that it prints very many useless error messages.)
  2911. @end table
  2912. An option can be followed by a value, as
  2913. in @code{--warn-invoke-unknown-method=no}.
  2914. For boolean options, the values @code{yes}, @code{true}, @code{on}, or @code{1}
  2915. enable the option, while @code{no}, @code{false}, @code{off},
  2916. or @code{0} disable it.
  2917. You can also negate an option by prefixing it with @code{no-}:
  2918. The option @code{--no-warn-unknown-member}
  2919. is the same as @code{--warn-unknown-member=no}.
  2920. These options can also be used in the module source, using
  2921. @code{module-compile-options} or @code{with-compile-options}.
  2922. (In that case they override the options on the command line.)
  2923. @subsection Options for setting variables
  2924. @table @code
  2925. @item @var{name}=@var{value}
  2926. Set the global variable with the specified @var{name} to the given @var{value}.
  2927. The type of the @var{value} is currently unspecified; the plan is for it
  2928. to be like XQuery's @dfn{untyped atomic} which can be coerced as needed.
  2929. @item @{@var{namespace-uri}@}@var{local-name}=@var{value}
  2930. Set the global variable with the specified namespace uri and
  2931. namespace-local name to the given value.
  2932. @end table
  2933. These options are processed when invoking the @code{kawa}
  2934. application (i.e. the @code{kawa.repl} application).
  2935. If you want a Kawa application compiled with @code{--main}
  2936. to process these these assignments, call the
  2937. @code{process-command-line-assignments} utility function.
  2938. @table @code
  2939. @item -D@var{variable-name}=@var{variable-value}
  2940. Sets the JVM property @var{variable-name} to @var{variable-value},
  2941. using the @code{setProperty} method of @code{java.lang.System}.
  2942. @end table
  2943. @subsection Options for the REPL console
  2944. @table @asis
  2945. @item @code{--console}
  2946. @itemx @code{--no-console}
  2947. Usually Kawa can detect when the standard input port is a ``console''
  2948. or ``terminal'', but these are useful for overriding that detection.
  2949. The @code{--console} flag is useful when the standard input is a pipe,
  2950. but you want to direct Kawa to treat it as an interactive terminal.
  2951. The @code{--no-console} flag was useful for older pre-Java-6
  2952. implementations that did not have the @code{java.lang.Console} class.
  2953. @item @code{console:type=}@var{console-types}
  2954. @itemx @code{console:use-jline=}[@code{yes}|@code{no}]
  2955. @itemx @code{console:jline-mouse=}[@code{yes}|@code{no}]
  2956. See the @ref{REPL Console} section.
  2957. @item @code{console:prompt1=@var{prompt1}}
  2958. @itemx @code{console:prompt2=@var{prompt2}}
  2959. Initialize @ref{input-prompt1,@code{input-prompt1} and @code{input-prompt2}}, respectively.
  2960. @end table
  2961. See also the @code{--output-format} flag.
  2962. @subsection Options for controlling output formatting
  2963. @cindex @code{--output-format}
  2964. @table @code
  2965. @item --output-format @var{format}
  2966. @itemx --format @var{format}
  2967. Change the default output format to that specified by @var{format}.
  2968. See @ref{Named output formats} for more information and a list.
  2969. @end table
  2970. @table @code
  2971. @item out:base=@var{integer}
  2972. The number base (radix) to use by default when printing rational numbers.
  2973. Must be an integer between 2 and 36, and the default is of course 10.
  2974. For example the option @code{out:base=16} produces hexadecimal output.
  2975. Equivalent to setting the @code{*print-base*} variable.
  2976. @item out:radix=no|yes
  2977. If true, prints an indicator of the radix used when printing rational numbers.
  2978. The default is @code{no}.
  2979. Equivalent to setting the @code{*print-radix*} variable.
  2980. @item out:doctype-system=@var{system-identifier}
  2981. If @code{out:doctype-system} is specified then a @code{DOCTYPE} declaration
  2982. is written before writing a top-level XML element, using
  2983. the specified @var{system-identifier}.
  2984. @item out:doctype-public=@var{public-identifier}
  2985. Ignored unless @code{out:doctype-system} is also specified,
  2986. in which case the @var{public-identifier} is written
  2987. as the public identifiers of the @code{DOCTYPE} declaration.
  2988. @item out:xml-indent=@var{kind}
  2989. Controls whether extra line breaks and indentation are added
  2990. when printing XML.
  2991. If @var{kind} is @code{always} or @code{yes} then newlines and
  2992. appropriate indentation are added before and after each element.
  2993. If @var{kind} is @code{pretty} then the pretty-printer is used
  2994. to only add new lines when an element otherwise won't fit on a single line.
  2995. If @var{kind} is @code{no} (the default) then no extra line breaks
  2996. or indentation are added.
  2997. @item out:line-length=@var{columns}
  2998. @itemx out:right-margin=@var{columns}
  2999. Specifies the maximum number of number of columns in a line
  3000. when the pretty-printer decides where to break a line.
  3001. (The two options are equivalent.)
  3002. @end table
  3003. @subsection Options for compiling and optimizing
  3004. @table @code
  3005. @item --target @var{version}
  3006. The @var{version} can be a JDK or Java specification version:
  3007. @code{5}, @code{6}, or @code{7}.
  3008. The JDK versions @code{1.5} and @code{1.6} are equivalent to @code{5}
  3009. or @code{6}, respectively.
  3010. Specify a JVM (classfile) version to target. This is useful
  3011. if (for example) you use Java 6, but want to create @code{.class} files
  3012. that can run on Java 5. In that case specify @code{--target 5}.
  3013. @end table
  3014. The following options control which calling conventions are used:
  3015. @table @code
  3016. @item --full-tailcalls
  3017. Use a calling convention that supports proper tail recursion.
  3018. @item --no-full-tailcalls
  3019. Use a calling convention that does not support proper tail recursion.
  3020. Self-tail-recursion (i.e. a recursive call to the current function)
  3021. is still implemented correctly, assuming that the called function
  3022. is known at compile time.
  3023. @item --no-inline
  3024. Disable inlining of known functions and methods.
  3025. The generated code runs slower, but you can more reliably trace procedures.
  3026. Normally Kawa will assume that a procedure @code{fn}
  3027. declared using a @code{(define (fn args) body)} form is constant,
  3028. assuming it isn't modified in the current module. However, it is
  3029. possible some other module might modify the binding of @code{fn}.
  3030. You can use the @code{--no-inline} to disable the assumption that @code{fn}
  3031. is constant.
  3032. @end table
  3033. The default is currently @code{--no-full-tailcalls} because
  3034. it is usually faster.
  3035. It is also closer to the Java call model, so may be better for people
  3036. primarily interested in using Kawa for scripting Java systems.
  3037. Both calling conventions can co-exist: Code compiled
  3038. with @code{--full-tailcalls} can call code compiled
  3039. with @code{--no-full-tailcalls} and vice versa.
  3040. These options can also be used in the module source, using
  3041. @code{module-compile-options} or @code{with-compile-options}.
  3042. (In that case they override the options on the command line.)
  3043. The options @samp{-C}, @samp{-d}, @samp{-T}, @samp{-P}, @samp{--main}
  3044. @samp{--applet}, and @code{--servlet} are used to compile a Scheme file;
  3045. see @ref{Files compilation}.
  3046. The options @samp{--module-static}, @code{--module-nonstatic},
  3047. @code{--no-module-static}, and @code{--module-static-run}
  3048. control how a module is mapped to a Java class; see @ref{static-or-non-modules}.
  3049. The option @samp{--connect @var{portnum}} is only used by
  3050. the @samp{kawa} front-end program.
  3051. @subsection Options for debugging
  3052. The following options are useful if you want to debug or understand
  3053. how Kawa works.
  3054. @table @code
  3055. @item --debug-dump-zip
  3056. Normally, when Kawa loads a source file, or evaluates a non-trivial expression,
  3057. it generates new internal Java classes but does not write them out. This
  3058. option asks it to write out generated classes in a @samp{.zip} archive
  3059. whose name has the prefix @samp{kawa-zip-dump-}.
  3060. @item --debug-print-expr
  3061. Kawa translates source language forms into an internal @code{Expression}
  3062. data structure. This option causes that data structure to be written out
  3063. in a readable format to the standard output.
  3064. @item --debug-print-final-expr
  3065. Similar to the previous option, but prints out the @code{Expression} after
  3066. various transformations and optimizations have been done, and just before
  3067. code generation.
  3068. @item --debug-syntax-pattern-match
  3069. Prints logging information to standard error when a @code{syntax-rules}
  3070. or @code{syntax-case} pattern matches.
  3071. @item --debug-error-prints-stack-trace
  3072. Prints a stack trace with any error found during compilation.
  3073. @item --debug-warning-prints-stack-trace
  3074. Prints a stack trace with any warning found during compilation.
  3075. @end table
  3076. @subsection Options for web servers
  3077. JDK 6 (or later) includes a complete web server library.
  3078. @table @code
  3079. @item --http-auto-handler @var{context-path} @var{appdir}
  3080. Register a web application handler that uses files
  3081. in the directory @var{appdir} to handle HTTP (web) requests
  3082. containing the given @var{context-path}. That is it handles
  3083. requests that start with @code{http://localhost:@var{port}@var{context-path}}.
  3084. (This assumes the @var{context-path} starts with a @code{/}.)
  3085. @xref{Self-configuring page scripts}.
  3086. @item --http-start @var{port}
  3087. Start the web server, listing on the specified @var{port}.
  3088. @end table
  3089. @subsection Options for the JVM
  3090. The @code{kawa} front-end can pass options to the @code{java} launcher,
  3091. using @code{-J} or @code{-D} options.
  3092. These must be given @emph{before} any other arguments.
  3093. For example:
  3094. @example
  3095. kawa -J-Xms48m -Dkawa.command.name=foo foo.scm
  3096. @end example
  3097. is equivalent to (ignoring classpath issues):
  3098. @example
  3099. java -Xms48m -Dkawa.command.name=foo kawa.repl foo.scm
  3100. @end example
  3101. You can also pass a @code{-D} option (but not a @code{-J} option) after the
  3102. class name, in which case it is processed by the Kawa command-line processor
  3103. rather than the @code{java} launcher. The effect is normally the same.
  3104. @table @code
  3105. @item -J@var{jvm-option}
  3106. Passes the @var{jvm-option} to the @code{java} command,
  3107. before the class-name (@code{kawa.repl}) and Kawa options.
  3108. @item -D@var{variable-name}=@var{variable-value}
  3109. Sets the JVM property @var{variable-name} to @var{variable-value}.
  3110. Equivalent to @code{-J-D@var{variable-name}=@var{variable-value}}.
  3111. @end table
  3112. @node Scripts
  3113. @section Running Command Scripts
  3114. If you write a Kawa application, it is convenient to be able
  3115. to execute it directly (from the command line or clicking an icon, say),
  3116. without have to explicitly run @code{kawa} or @code{java}.
  3117. On Unix-like systems the easiest way to do this is to
  3118. write a small shell script that runs your Kawa application.
  3119. For modest-sized applications it is convenient if the shell script
  3120. and the Kawa code can be in the same file.
  3121. Unix-like systems support a mechanism where a @dfn{script} can
  3122. specify a program that should execute it. The convention
  3123. is that the first line of the file should start with the two characters
  3124. @samp{#!} followed by the absolute path of the program that should
  3125. process (interpret) the script.
  3126. (Windows has @dfn{batch files}, which are similar.)
  3127. This convention works well for script languages that use @samp{#}
  3128. to indicate the start of a comment, since the interpreter will
  3129. automatically ignore the line specifying the interpreter filename.
  3130. Scheme, however, uses @samp{#} as a multi-purpose prefix,
  3131. and Kawa specifically uses @samp{#!} as a prefix for
  3132. various @ref{Special named constants} such as @code{#!optional}.
  3133. Kawa does recognize the three-character sequence @samp{#!/} at the
  3134. beginning of a file as special, and ignores it.
  3135. Here is an example:
  3136. @example
  3137. #!/usr/local/bin/kawa
  3138. (format #t "The command-line was:~@{ ~w~@}~%" (command-line))
  3139. @end example
  3140. If you copy this text to a file named @code{/home/me/bin/scm-echo},
  3141. set the execute permission, and make sure it is in your @code{PATH},
  3142. then you can execute it just by naming it on command line:
  3143. @example
  3144. $ chmod +x /home/me/bin/scm-echo
  3145. $ PATH=/home/me/bin:$PATH
  3146. $ scm-env a b
  3147. The command-line was: "/home/me/bin/scm-echo" "a" "b"
  3148. @end example
  3149. The system kernel will automatically execute @code{kawa}, passing it the
  3150. filename as an argument.
  3151. Note that the full path-name of the @code{kawa} interpreter
  3152. must be hard-wired into the script. This means you may have to edit
  3153. the script depending on where Kawa is installed on your system.
  3154. Another possible problem is that the interpreter must be an
  3155. actual program, not a shell script. Depending on how you configure
  3156. and install Kawa, @code{kawa} can be a real program or a script.
  3157. You can avoid both problems by the @code{env} program, available on
  3158. most modern Unix-like systems:
  3159. @example
  3160. #!/usr/bin/env kawa
  3161. (format #t "The command-line was:~@{ ~w~@}~%" (command-line))
  3162. @end example
  3163. This works the same way, but assumes @code{kawa} is in the
  3164. command @code{PATH}.
  3165. @subsection Setting kawa options in the script
  3166. If you need to specify extra arguments to @code{kawa},
  3167. you can run arbitrary shell command inside Scheme block comments.
  3168. Here is an example:
  3169. @example
  3170. #!/bin/sh
  3171. #|
  3172. exec kawa out:base=16 out:radix=yes "$0" "$*"
  3173. |#
  3174. (format #t "The command-line is:~@{ ~w~@}.~%" (command-line))
  3175. (display "It has ")
  3176. (display (apply + (map string-length (command-line))))
  3177. (display " characters.")
  3178. (newline)
  3179. @end example
  3180. The trick is to hide the shell code from Kawa inside
  3181. a @code{#|...|#} block-comment. The start of the block comment
  3182. is a line starting with a @code{#}, so it is treated as a comment by the shell.
  3183. You can then invoke @code{kawa} (or @code{java} directly)
  3184. as you prefer, setting up class-path and jars as needed,
  3185. and passing whatever arguments you want.
  3186. (The shell replaces the @code{"$0"} by the name of the script, and
  3187. replaces the @code{"$@@"} by the remaining arguments passed to the script.)
  3188. You need to make sure the shell finishes before it reaches
  3189. the end of the block comment or the Scheme code, which would confuse it.
  3190. The example uses @code{exec}, which tells the shell to @emph{replace}
  3191. itself by @var{kawa};
  3192. an alternative is to use the shell @code{exit} command.
  3193. If you copy the above file to @code{/tmp/sch-echo} and make
  3194. that file executable, you can run it directly:
  3195. @example
  3196. $ /tmp/scm-echo "a b" "c d"
  3197. The command-line is: "/tmp/scm-echo" "a b c d".
  3198. It has #x14 characters.
  3199. @end example
  3200. When the Kawa reader sees the initial @code{#/} it sets
  3201. the command name to the file name, so it can be used by a future
  3202. call to @code{(command-name)}. If you want to override
  3203. this you can use the @code{-Dkawa.command.name=@var{name}} option.
  3204. Using comments this way has the advantage that you have the
  3205. option of running the script ``manually'' if you prefer:
  3206. @example
  3207. $ kawa /tmp/scm-echo out:base=8 "x y"
  3208. The command-line is: "/tmp/scm-echo" "out:base=8" "x y".
  3209. It has 26 characters.
  3210. @end example
  3211. @subsection Other ways to pass options using meta-arg or --script
  3212. An argument consisting of just a @code{\} (backslash)
  3213. causes Kawa to read the @emph{second} line looking for
  3214. options. (Quotes and backslashes work like in the shell.)
  3215. These replace the backslash in the command line.
  3216. This is a less verbose mechanism, but it requires an
  3217. absolute path to @code{kawa}, due to shell limitations.
  3218. @example
  3219. #!/usr/bin/kawa \
  3220. --scheme --full-tailcalls
  3221. (format #t "The command-line is:~@{ ~w~@}.~%" (command-line))
  3222. @end example
  3223. In this case the effective command line received by Kawa will
  3224. be @code{--scheme}, @code{--full-tailcalls}, followed by the
  3225. script filename, followed by other arguments specified when
  3226. running the script.
  3227. The backslash used this way originated in
  3228. @uref{http://www.scsh.net, scsh} where it is called the @dfn{meta-arg}.
  3229. (Unlike scsh, Kawa's @code{#!} is not a block comment,
  3230. but a rest-of-line, though the backslash causes the following line
  3231. to also be skipped.)
  3232. An alternative method is to use the @code{--script2} option,
  3233. which tells Kawa to execute the script after ignoring
  3234. the initial two lines. For example:
  3235. @example
  3236. #!/bin/sh
  3237. exec kawa --commonlisp out:base=16 --script2 "$0" "$@@"
  3238. (setq xx 20) (display xx) (newline)
  3239. @end example
  3240. This is slightly more compact than using block-comments as shown earlier,
  3241. but it has the disadvantage that you can't explicitly
  3242. use @code{kawa} or @code{java} to run the script unless you
  3243. make sure to pass it the @code{--script2} option.
  3244. @subsection Scripts for compiled code
  3245. If you compile your Kawa application to class files (or better:
  3246. a @code{jar} file), you probably still want to write a small
  3247. shell script to set things up. Here is one method:
  3248. @example
  3249. #!/bin/sh
  3250. export CLASSPATH=/my/path
  3251. exec kawa -Dkawa.command.name="$0" foo "$@@"
  3252. @end example
  3253. Using the @code{kawa} front-end is a convenience, since it automatically
  3254. sets up the paths for the Kawa classes, and (if enabled) it
  3255. provides readline support for the default input port.
  3256. Setting the @code{kawa.command.name} property to @code{"$0"}
  3257. (the filename used to invoke the script) enables
  3258. @code{(command-line}) to use the script name as the command name.
  3259. You can invoke @code{java} directly, which is necessary when
  3260. running a @code{jar} file:
  3261. @example
  3262. #!/bin/sh
  3263. exec java -cp /path/to/kawa -Dkawa.command.name="$0" foo.jar "$@@"
  3264. @end example
  3265. @ignore
  3266. (It is in principle possible to compile a Kawa application to
  3267. ``a native executable'', for example using @code{gcj}.
  3268. However, this is no longer supported, as gcj is no longer
  3269. being actively developed.)
  3270. @end ignore
  3271. @node REPL Console
  3272. @section The REPL (read-eval-print-loop) console
  3273. The read-eval-print-loop (REPL) console is a convenient way to
  3274. do simple programming, test out things, and experiment.
  3275. As the name implies, the REPL repeatedly (in a loop)
  3276. prints out a prompt, reads an input command, evaluates it, then prints the result.
  3277. The REPL is started when you invoke the @code{kawa} command
  3278. with no arguments. For example:
  3279. @example
  3280. $ @kbd{kawa}
  3281. #|kawa:1|# @kbd{(define pi (* 2 (asin 1)))}
  3282. #|kawa:2|# @kbd{(list pi (sqrt pi))}
  3283. (3.141592653589793 1.7724538509055159)
  3284. #|kawa:3|# @kbd{}
  3285. @end example
  3286. The colors and styles used for the prompt and the user input
  3287. depend on user preference and the capabilities of the console device.
  3288. (If you read this on a color screen you should see pale green for the
  3289. prompt and pale yellow for the user input;
  3290. this matches the defaults for the DomTerm console.)
  3291. You can @ref{Prompts,change the prompt string} if you want.
  3292. The default format depends on the (programming) language used;
  3293. the one shown above is used for Scheme.
  3294. It has the form of a comment, which can be convenient for copying
  3295. and pasting lines.
  3296. You can @ref{Named output formats,change the output formatting} with
  3297. the @code{--output-format} command-line option.
  3298. The basic console has few frills, but should work in any enviroment
  3299. where you have a console or terminal. It has no dependencies,
  3300. except the kawa @code{.jar} file (and Java):
  3301. @example
  3302. $ @kbd{java kawa-@value{VERSION}.jar}
  3303. #|kawa:2|# @kbd{}
  3304. @end example
  3305. On rare occason you may need to specify the @code{--console} flag.
  3306. @subsection Input line editing and history
  3307. When typing a command in a console it is helpful to go back
  3308. and correct mistakes, repeat and edit previous commands, and so on.
  3309. How well you can do this varies a lot depending on which tools you use.
  3310. Kawa delegates input editing to an external tool.
  3311. The recommended and default input-editing tool is
  3312. the @uref{https://github.com/jline/jline3,JLine3 library},
  3313. which is bundled with the Kawa binary distribution.
  3314. JLine3 handles the normal editing comands, including arrow keys
  3315. for moving around in the input, and deleting with backspace or delete.
  3316. In general, JLine3 uses the same keybindings as GNU readline,
  3317. which are based on Emacs key-bindings.
  3318. You can use the up-arrow to move to previous commands in the
  3319. input history and down-arrow to go forwards.
  3320. Control-R (``reverse search'' searches backwards in the history
  3321. for a previous command that contains the search string.
  3322. Multi-line commands are treated as a unit by JLine3:
  3323. If Kawa determines that input is ``incomplete'' it will
  3324. ask for continuation lines - and you can go back and edit previous
  3325. lines in the same command.
  3326. You can explicitly create a multi-line command with Escape-Space.
  3327. An entry in the command history may be multiple lines.
  3328. Tab-completion works for Kawa-Scheme identifiers: If you type TAB
  3329. after an identifier, Kawa will present a list of possible completions.
  3330. There are multiple alternatives to using JLine3.
  3331. You can use GNU readline (if you configured with @code{--enable-kawa-frontend}).
  3332. You can use a front-end program like @code{rlfe} or @code{fep}.
  3333. You can use Emacs shell or scheme mode.
  3334. You can also use DomTerm in line-edit mode, where the browser handles
  3335. the editing.
  3336. @table @asis
  3337. @item @code{console:use-jline=}[@code{yes}|@code{no}]
  3338. Disable (with @code{no}) or enable (with @code{yes}, which is the default)
  3339. input line editing with JLine.
  3340. @item @code{console:console:jline-mouse=}[@code{yes}|@code{no}]
  3341. Enable (with @code{yes}) mouse click reporting from
  3342. most xterm-like terminals to JLine, which means you
  3343. can move the input cursor with the mouse.
  3344. This is disabled by default because it conflicts with other useful mouse
  3345. actions (text selection using drag; middle-button paste; right-button
  3346. context menu; and wheel mouse scrolling).
  3347. If you enable mouse-reporting, on most terminals you can get the
  3348. standard behavior when pressing the shift key. E.g. to enable selection,
  3349. drag with the shift key pressed. (However, mouse-wheel scrolling
  3350. may not work even with shift pressed.)
  3351. @end table
  3352. @anchor{New-Window}
  3353. @subsection Running a Command Interpreter in a new Window
  3354. Instead of using an existing terminal window for Kawa's REPL console,
  3355. you can request a new window.
  3356. The command-line options @code{-w} creates a new window.
  3357. Kawa also creates a new window when it needs to create a REPL
  3358. (for example if invoked with no options) and it is not running
  3359. in a console.
  3360. You have a number of options for how the window appears and
  3361. what it supports, controlled by text following @code{-w}.
  3362. All except @code{-wswing} (and @code{-wconsole}) use DomTerm,
  3363. so they depend on some kind of web browser technology.
  3364. All except @code{-wswing} by default use JLine3 input editing,
  3365. if available.
  3366. @table @asis
  3367. @item @code{-w}
  3368. Pick the default/preferred console implementation.
  3369. You can specify your preference with the @code{console:type=} option,
  3370. which is followed by one of the options below (without the @code{"-w"} prefix),
  3371. It can also be list of options separated by semi-colons, in which
  3372. case they are tried in order.
  3373. The current default (it may change) is as if you specified:
  3374. @example
  3375. console:type="google-chrome;browser;javafx;swing;console"
  3376. @end example
  3377. @item @code{-wbrowser}
  3378. Creates a Kawa window or tab in your preferred desktop browser.
  3379. Kawa starts a builtin HTTP and WebSocket server to communicate with the browser.
  3380. @item @code{-wbrowser=@var{command}}
  3381. Uses @var{command} to display the Kawa REPL.
  3382. The @var{command} should include the pattern @code{%U}, which Kawa replaces
  3383. with a URL that it listens to.
  3384. (Alternatively, it can use the pattern @code{%W}, which Kawa replaces
  3385. with the port number of its WebSocket server. However, this feature may be removed.)
  3386. If the is no @code{%} in the @var{command}, Kawa add @code{" %U"}.
  3387. Thus @code{-wbrowser=firefox} is the same as @code{-wbrowser="firefox %U"}.
  3388. @item @code{-wgoogle-chrome}
  3389. Creates a new Google Chrome window in ``app mode'' - i.e. with no location or menu bar.
  3390. This is the same as @code{-wbrowser="google-chrome --app=%U"}.
  3391. @c @item @code{-wqtdomterm}
  3392. @c Uses the @code{QtDomTerm} application.
  3393. @c Same as @code{-wbrowser="qtdomterm --connect localhost:%W"}, where @code{%W}
  3394. @c is the port of the WebSocke server that Kawa starts.
  3395. @item @code{-wjavafx}
  3396. Creates a new window using JavaFX WebView, which runs in the same JVM as Kawa.
  3397. While this doesn't currently have much in the way of Kawa-specific menus
  3398. or other features, it has the most potential for adding them in the future.
  3399. However, it does require JavaFX, which is not always available,
  3400. and which does not see a lot of love from Oracle. (It uses an old version of WebKit.)
  3401. @item @code{-wswing}
  3402. Create a console using the Swing toolkit.
  3403. This is the old implementation of @code{-w}.
  3404. It is deprecated because it only supports the builtin Swing line editing.
  3405. (I.e. neither DomTerm or JLine3 features are available, though
  3406. ``printing'' @ref{Composable pictures,pictures} does work.)
  3407. @item @code{-wserve}
  3408. @itemx @code{-wserve=}@var{port}
  3409. Starts up an HTTP server (along with a WebSocket server),
  3410. but does not automatically create any browser windows.
  3411. Instead you can use any modern browser to load @code{http://localhost:@var{port}/}.
  3412. If @var{port} is not specified, the systems selects it (and prints it out).
  3413. @item @code{-wconsole}
  3414. Same as @code{"--"} - i.e. it uses the existing console.
  3415. @item @code{console:type=}@var{preference-list}
  3416. Specify the behavior of plain @code{-w}.
  3417. @end table
  3418. @anchor{Using DomTerm}
  3419. @subsection Using DomTerm
  3420. @uref{http://domterm.org,DomTerm} is a family of terminal emulators that use
  3421. the DomTerm JavaScript library.
  3422. You can either have Kawa start DomTerm:
  3423. @example
  3424. $ kawa @var{options} -w
  3425. @end example
  3426. or start a DomTerm terminal emulator and have it start Kawa:
  3427. @example
  3428. $ domterm kawa @var{options} --
  3429. @end example
  3430. (You can also start a shell in a @code{domterm} window, and then start @code{kawa}.)
  3431. Either approach works and both give you the benefits of DomTerm:
  3432. @itemize
  3433. @item
  3434. A xterm/ansi-compatible terminal emulator,
  3435. which means you can use (for example) JLine3 for input editing.
  3436. @item
  3437. You can ``print'' images, @ref{Composable pictures,pictures}, or HTML elements.
  3438. @item
  3439. Pretty-printing is handled by the terminal,
  3440. which means line-breaking is re-computed when window width changes.
  3441. @item
  3442. Hide/show buttons allow you to temporarily hide/unhide the output from a specific command.
  3443. @item
  3444. You can save a session as an HTML file,
  3445. which can be viewed later.
  3446. (Still with dynamic line-breaking and pretty-printing, as well as working hide/show buttons.)
  3447. The file is actually XHTML, so it can be processed with XML-reading tools.
  3448. @item
  3449. Distinct styles for prompts, input, error output and regular output,
  3450. which can be customized with CSS.
  3451. @end itemize
  3452. For now it is recommended to use both DomTerm and JLine3.
  3453. @deffn Procedure domterm-load-stylesheet stylesheet [name]
  3454. The string @var{stylesheet} should be a literal CSS stylesheet
  3455. which is downloaded into the current DomTerm console.
  3456. The new stylesheet is given the attribute @code{name=@var{name}},
  3457. where @var{name} defaults to @code{"Kawa"}. If there is an
  3458. existing stylesheey whose @code{name} attribute is @var{name},
  3459. it is replaced.
  3460. In this example we change the background color to light gray:
  3461. @example
  3462. (domterm-load-stylesheet "div.domterm @{ background-color: lightgray@}")
  3463. @end example
  3464. @end deffn
  3465. @node Exiting
  3466. @section Exiting Kawa
  3467. Kawa normally keeps running as long as there is an active
  3468. read-eval-print loop still awaiting input or there is an unfinished
  3469. other computation (such as requested by a @samp{-e} or @samp{-f} option).
  3470. To close a read-eval-print-loop, you can type the special
  3471. literal @code{#!eof} at top level. This is recognized as end-of-file.
  3472. Typing an end-of-file character (normally ctrl-D under Unix)
  3473. should also work, but that depends on your operating system
  3474. and terminal interface.
  3475. If the read-eval-print-loop
  3476. is in a new window, you can select @samp{Close} from the @samp{File} menu.
  3477. To exit the entire Kawa session, call the
  3478. @ref{Exiting the current process,@code{exit} procedure} (with 0 or 1 integer arguments).
  3479. @node Compiling, , , Running
  3480. @section Compiling to byte-code
  3481. All Scheme functions and source files are invisibly compiled
  3482. into internal Java byte-codes.
  3483. (A traditional interpreter is used for macro-expansion.
  3484. Kawa used to also interpret ``simple'' expressions in interactive mode,
  3485. but always compiling makes things more consistent, and allows for
  3486. better stack traces on errors.)
  3487. To save speed when loading large Scheme source files, you probably
  3488. want to pre-compile them and save them on your local disk.
  3489. There are two ways to do this.
  3490. You can compile a Scheme source file to a single archive file.
  3491. You do this using the @code{compile-file} function.
  3492. The result is a single file that you can move around and @code{load}
  3493. just like the @code{.scm} source file. You just specify the name
  3494. of the archive file to the @code{load} procedure.
  3495. Currently, the archive is a "zip" archive and has extension ".zip";
  3496. a future release will probably use "Java Archive" (jar) files.
  3497. The advantage of compiling to an archive is that it is simple
  3498. and transparent.
  3499. Alternatively, you can compile a Scheme source file to a
  3500. collection of @samp{.class} files.
  3501. You then use the standard Java class loading mechanism to load the code.
  3502. The compiled class files do have to be installed somewhere
  3503. in the @code{CLASSPATH}.
  3504. @menu
  3505. * Files compilation:: Compiling to a set of .class files
  3506. * Archive compilation:: Compiling to an archive file
  3507. * Compiling using Ant::
  3508. * Application compilation:: Compiling to a standalone application
  3509. * Applet compilation:: Compiling to an applet
  3510. * Compiling to executable:: Compiling to a native executable
  3511. @end menu
  3512. @node Files compilation
  3513. @subsection Compiling to a set of .class files
  3514. Invoking @samp{kawa} (or @samp{java kawa.repl}) with
  3515. the @samp{-C} flag will compile
  3516. a @samp{.scm} source file into one or more @samp{.class} files:
  3517. @example
  3518. kawa --main -C myprog.scm
  3519. @end example
  3520. You run it as follows:
  3521. @example
  3522. kawa [-d @var{outdirectory}] [-P @var{prefix}] [-T @var{topname}] [--main | --applet | --servlet] -C @var{infile} ...
  3523. @end example
  3524. Note the @samp{-C} must come last, because @samp{Kawa} processes the
  3525. arguments and options in order,
  3526. Here:
  3527. @table @code
  3528. @item -C @var{infile} ...
  3529. The Scheme source files we want to compile.
  3530. @item -d @var{outdirectory}
  3531. The directory under which the resulting @samp{.class} files will be.
  3532. The default is the current directory.
  3533. @item -P @var{prefix}
  3534. A string to prepend to the generated class names.
  3535. The default is the empty string.
  3536. @item -T @var{topname}
  3537. The name of the "top" class - i.e. the one that contains the code
  3538. for the top-level expressions and definitions.
  3539. The default is generated from the @var{infile} and @var{prefix}.
  3540. @item --main
  3541. Generate a @code{main} method so that the resulting "top" class can
  3542. be used as a stand-alone application. @xref{Application compilation}.
  3543. @item --applet
  3544. The resulting class inherits from @code{java.applet.Applet},
  3545. and can be used as an applet. @xref{Applet compilation}.
  3546. @item --servlet
  3547. The resulting class implements @code{javax.servlet.http.HttpServlet},
  3548. and can be used as a servlet in a servlet container like Tomcat.
  3549. @end table
  3550. When you actually want to load the classes, the @var{outdirectory}
  3551. must be in your @samp{CLASSPATH}.
  3552. You can use the @code{require} syntax or the @code{load} function to load the code,
  3553. by specifying the top-level class, either as a file name
  3554. (relative to @var{outdirectory}) or as a class name.
  3555. E.g. if you did:
  3556. @example
  3557. kawa -d /usr/local/share/java -P my.lib. -T foo -C foosrc.scm
  3558. @end example
  3559. you can use either:
  3560. @example
  3561. (require my.lib.foo)
  3562. @end example
  3563. or:
  3564. @example
  3565. (load "my.lib.foo")
  3566. @end example
  3567. Using @code{require} is preferred as it imports the definitions
  3568. from @code{my.lib.foo} into the compile-time environment,
  3569. while @code{load} only imports the definitions into the run-time environment.
  3570. If you are compiling a Scheme source file (say @samp{foosrc.scm})
  3571. that uses macros defined in some other file (say @samp{macs.scm}),
  3572. you need to make sure the definitions are visible to the compiler.
  3573. One way to do that is with the @samp{-f}:
  3574. @example
  3575. kawa -f macs.scm -C foosrc.scm
  3576. @end example
  3577. Many of the options @ref{Options,,described earlier} are
  3578. relevant when compiling. Commonly used options include language selection,
  3579. the @code{--warn-xxx} options, and @code{--full-tailcalls}.
  3580. @node Archive compilation
  3581. @subsection Compiling to an archive file
  3582. @deffn Procedure compile-file source-file compiled-archive
  3583. Compile the @var{source-file}, producing a @code{.zip} archive
  3584. @var{compiled-file}.
  3585. For example, to byte-compile a file @samp{foo.scm} do:
  3586. @example
  3587. (compile-file "foo.scm" "foo")
  3588. @end example
  3589. This will create @samp{foo.zip}, which contains
  3590. byte-compiled JVM @code{.class} files.
  3591. You can move this file around, without worrying about class paths.
  3592. To load the compiled file, you can later @code{load} the
  3593. named file, as in either @code{(load "foo")} or @code{(load "foo.zip")}.
  3594. This should have the same effect as
  3595. loading @samp{foo.scm}, except you will get the faster byte-compiled versions.
  3596. @end deffn
  3597. @node Compiling using Ant
  3598. @subsection Compiling using Ant
  3599. @cindex kawac
  3600. Many Java projects use @uref{http://ant.apache.org, Ant}
  3601. for building Java projects. Kawa includes a @code{<kawac>}
  3602. Ant task that simplifies compiling Kawa source files to classes.
  3603. See the @code{build.xml} in the Kawa source distribution for examples.
  3604. See the @uref{ant-kawac.html, @code{kawac} task documentation} for details.
  3605. @node Application compilation
  3606. @subsection Compiling to a standalone application
  3607. A Java application is a Java class with a special method
  3608. (whose name is @code{main}). The application can be invoked directly
  3609. by naming it in the Java command.
  3610. If you want to generate an application from a Scheme program,
  3611. create a Scheme source file with the definitions you need, plus
  3612. the top-level actions that you want the application to execute.
  3613. For example, assuming your Scheme file is
  3614. @code{MyProgram.scm}, you have two ways at your disposal to
  3615. compile this Scheme program to a standalone application:
  3616. @enumerate
  3617. @item
  3618. Compile
  3619. in the regular way described in the previous section, but add the
  3620. @code{--main} option.
  3621. @example
  3622. kawa --main -C MyProgram.scm
  3623. @end example
  3624. The @code{--main} option will compile all Scheme programs
  3625. received in arguments to standalone applications.
  3626. @item
  3627. Compile
  3628. in the regular way decribed in the previous section, but add the
  3629. @code{main: #t} module compile option to your module.
  3630. @example
  3631. ;; MyProgram.scm
  3632. (module-name <myprogram>)
  3633. (module-compile-options main: #t)
  3634. @end example
  3635. @example
  3636. kawa -C MyProgram.scm
  3637. @end example
  3638. This way you can compile multiple Scheme programs at once, and
  3639. still control which one(s) will compile to standalone application(s).
  3640. @end enumerate
  3641. Both methods will create a @code{MyProgram.class} which you can either
  3642. @code{load} (as described in the previous section), or invoke as an application:
  3643. @example
  3644. java MyProgram [@var{args}]
  3645. @end example
  3646. Your Scheme program can access the command-line arguments @var{args}
  3647. by using the global variable @samp{command-line-arguments},
  3648. or the R6RS function @samp{command-line}.
  3649. If there is no explicit @code{module-export} in a module compiled
  3650. with @code{--main} then no names are exported. (The default
  3651. otherwise is for all names to be exported.)
  3652. @node Applet compilation, Compiling to executable, Application compilation, Compiling
  3653. @subsection Compiling to an applet
  3654. An applet is a Java class that inherits from @code{java.applet.Applet}.
  3655. The applet can be downloaded and run in a Java-capable web-browser.
  3656. To generate an applet from a Scheme program, write the Scheme
  3657. program with appropriate definitions of the functions @samp{init},
  3658. @samp{start}, @samp{stop} and @samp{destroy}. You must declare these
  3659. as zero-argument functions with a @code{<void>} return-type.
  3660. Here is an example, based on the scribble applet in Flanagan's
  3661. "Java Examples in a Nutshell" (O'Reilly, 1997):
  3662. @example
  3663. (define-private last-x 0)
  3664. (define-private last-y 0)
  3665. (define (init) :: void
  3666. (let ((applet (this)))
  3667. (applet:addMouseListener
  3668. (object (java.awt.event.MouseAdapter)
  3669. ((mousePressed e)
  3670. (set! last-x (e:getX))
  3671. (set! last-y (e:getY)))))
  3672. (applet:addMouseMotionListener
  3673. (object (java.awt.event.MouseMotionAdapter)
  3674. ((mouseDragged e)
  3675. (let ((g (applet:getGraphics))
  3676. (x (e:getX))
  3677. (y (e:getY)))
  3678. (g:drawLine last-x last-y x y)
  3679. (set! last-x x)
  3680. (set! last-y y)))))))
  3681. (define (start) :: void (format #t "called start.~%~!"))
  3682. (define (stop) :: void (format #t "called stop.~%~!"))
  3683. (define (destroy) :: void (format #t "called destroy.~%~!"))
  3684. @end example
  3685. You compile the program with the @samp{--applet} flag in addition to the
  3686. normal @samp{-C} flag:
  3687. @example
  3688. java kawa.repl --applet -C scribble.scm
  3689. @end example
  3690. You can then create a @samp{.jar} archive containing your applet:
  3691. @example
  3692. jar cf scribble.jar scribble*.class
  3693. @end example
  3694. Finally, you create an @samp{.html} page referencing your applet
  3695. and its support @code{jar}s:
  3696. @example
  3697. <html><head><title>Scribble testapp</title></head>
  3698. <body><h1>Scribble testapp</h1>
  3699. You can scribble here:
  3700. <br>
  3701. <applet code="scribble.class" archive="scribble.jar, kawa-@value{VERSION}.jar" width=200 height=200>
  3702. Sorry, Java is needed.</applet>
  3703. </body></html>
  3704. @end example
  3705. The problem with using Kawa to write applets is that the Kawa @code{.jar}
  3706. file is quite big, and may take a while to download over a network connection.
  3707. Some possible solutions:
  3708. @itemize
  3709. @item
  3710. Try to strip out of the Kawa @code{.jar} any classes your
  3711. applet doesn't need.
  3712. @item
  3713. Java 2 provides a mechanism to install a @uref{http://java.sun.com/docs/books/tutorial/ext/basics/download.html,
  3714. download extension}.
  3715. @item
  3716. Consider some alternative to applets, such as
  3717. @uref{http://java.sun.com/products/javawebstart/,Java Web Start}.
  3718. @end itemize
  3719. @node Compiling to executable, , Applet compilation, Compiling
  3720. @subsection Compiling to a native executable
  3721. In the past it was possible to compile a Scheme program to native code using GCJ.
  3722. However, using GCJ with Kawa is no longer supported,
  3723. as GCJ is no longer being actively maintained.
  3724. @ignore
  3725. You can compile your Scheme program to native code using GCJ,
  3726. as long as you have built Kawa using GCJ.
  3727. First, you need to compile the Scheme code to a set of @code{.class} files;
  3728. see @ref{Files compilation}.
  3729. @example
  3730. kawa --main -C myprog.scm
  3731. @end example
  3732. Then to create an executable @code{myprog} do:
  3733. @example
  3734. gckawa --main=myprog myprog*.class -o myprog
  3735. @end example
  3736. The @code{gckawa} is a simple shell script that calls @code{gcj}.
  3737. The reason for the wildcard in @code{myprog*.class} is that sometimes
  3738. Kawa will generate some helper classes in addition to @code{myprog.class}.
  3739. The @code{--main} option tell @code{gcj} which class contains
  3740. the @code{main} method it should use. The @code{-o} option names
  3741. the resulting executable program. The @code{-lkawa} option tells
  3742. the linker it should link with the kawa shared library, and
  3743. the @code{-L$PREFIX/bin} option tells the linker where it can
  3744. find that library.
  3745. @end ignore
  3746. @node Syntax
  3747. @chapter Syntax
  3748. @menu
  3749. * Syntax notation::
  3750. * Lexical and datum syntax::
  3751. * Lexical syntax::
  3752. * Datum syntax::
  3753. * Hash-prefixed forms::
  3754. * Primitive expression syntax::
  3755. * Colon notation:: Property access using colon notation
  3756. * Bodies::
  3757. * Syntax and conditional compilation::
  3758. * Macros::
  3759. * Named quasi-literals::
  3760. @end menu
  3761. @node Syntax notation, Lexical and datum syntax, , Syntax
  3762. @section Notation
  3763. The formal syntax for Kawa Scheme is written in an extended @acronym{BNF}.
  3764. Non--terminals are written @var{like-this}. Case is insignificant
  3765. for non--terminal names.
  3766. Literal text (terminals) are written @stxlit{like this}.
  3767. All spaces in the grammar are for legibility.
  3768. @c @meta{Empty} stands for the empty string.
  3769. The following extensions to @acronym{BNF} are used to make the
  3770. description more concise: @arbno{@meta{thing}} or @meta{thing}@code{...}
  3771. both mean zero or more occurrences of @meta{thing},
  3772. and @atleastone{@meta{thing}} means at least one @meta{thing}.
  3773. Some non-terminal names refer to the Unicode scalar values of the same
  3774. name: @meta{character-tabulation} (U+0009), @meta{linefeed} (U+000A),
  3775. @meta{carriage-return} (U+000D), @meta{line-tabulation} (U+000B),
  3776. @meta{form-feed} (U+000C), @meta{space} (U+0020), @meta{next-line}
  3777. (U+0085), @meta{line-separator} (U+2028), and @meta{paragraph-separator}
  3778. (U+2029).
  3779. @node Lexical and datum syntax, Lexical syntax, Syntax notation, Syntax
  3780. @section Lexical and datum syntax
  3781. The syntax of Scheme code is organized in three levels:
  3782. @enumerate
  3783. @item
  3784. the @emph{lexical syntax} that describes how a program text is split
  3785. into a sequence of lexemes,
  3786. @item
  3787. the @emph{datum syntax}, formulated in terms of the lexical syntax, that
  3788. structures the lexeme sequence as a sequence of @emph{syntactic data},
  3789. where a syntactic datum is a recursively structured entity,
  3790. @item
  3791. the @emph{program syntax} formulated in terms of the datum syntax,
  3792. imposing further structure and assigning meaning to syntactic data.
  3793. @end enumerate
  3794. Syntactic data (also called @emph{external representations}) double as a
  3795. notation for objects, and the @func{read} and
  3796. @func{write} procedures can be used for reading and writing syntactic data,
  3797. converting between their textual representation and the corresponding
  3798. objects. Each syntactic datum represents a corresponding
  3799. @emph{datum value}. A syntactic datum can be used in a program to obtain the
  3800. corresponding datum value using @code{quote}.
  3801. @c FIXME (@ref{base expressions quotation}).
  3802. Scheme source code consists of syntactic data and (non--significant)
  3803. comments. Syntactic data in Scheme source code are called @emph{forms}.
  3804. (A form nested inside another form is called a @emph{subform}.)
  3805. Consequently, Scheme's syntax has the property that any sequence of
  3806. characters that is a form is also a syntactic datum representing some
  3807. object. This can lead to confusion, since it may not be obvious out of
  3808. context whether a given sequence of characters is intended to be a
  3809. representation of objects or the text of a program. It is also a source
  3810. of power, since it facilitates writing programs such as interpreters or
  3811. compilers that treat programs as objects (or vice versa).
  3812. A datum value may have several different external representations. For
  3813. example, both @code{#e28.000} and @code{#x1c} are syntactic data
  3814. representing the exact integer object 28, and the syntactic data
  3815. @code{(8 13)}, @code{( 08 13 )}, @code{(8 . (13 . ()))} all represent a
  3816. list containing the exact integer objects 8 and 13. Syntactic data that
  3817. represent equal objects (in the sense of @func{equal?})
  3818. are always equivalent as forms of a program.
  3819. Because of the close correspondence between syntactic data and datum
  3820. values, we sometimes uses the term @emph{datum} for either a
  3821. syntactic datum or a datum value when the exact meaning is apparent from
  3822. the context.
  3823. @c An implementation must not extend the lexical or datum syntax in any
  3824. @c way, with one exception: it need not treat the syntax
  3825. @c @code{#!<identifier>}, for any <identifier> (@ref{lex syntax
  3826. @c identifiers}) that is not @code{r6rs}, as a syntax violation, and it may
  3827. @c use specific @code{#!}--prefixed identifiers as flags indicating that
  3828. @c subsequent input contains extensions to the standard lexical or datum
  3829. @c syntax. The syntax @code{#!r6rs} may be used to signify that the input
  3830. @c afterward is written with the lexical syntax and datum syntax described
  3831. @c by this report. @code{#!r6rs} is otherwise treated as a comment;
  3832. @c @ref{lex syntax whitespace and comments}.
  3833. @node Lexical syntax, Datum syntax, Lexical and datum syntax, Syntax
  3834. @section Lexical syntax
  3835. The lexical syntax determines how a character sequence is split into a
  3836. sequence of lexemes, omitting non--significant portions such as comments
  3837. and whitespace. The character sequence is assumed to be text according
  3838. to the @uref{http://unicode.org/,Unicode standard}.
  3839. Some of the lexemes, such as
  3840. identifiers, representations of number objects, strings etc., of the
  3841. lexical syntax are syntactic data in the datum syntax, and thus
  3842. represent objects. Besides the formal account of the syntax, this
  3843. section also describes what datum values are represented by these
  3844. syntactic data.
  3845. The lexical syntax, in the description of comments, contains a forward
  3846. reference to @meta{datum}, which is described as part of the datum
  3847. syntax. Being comments, however, these @meta{datum}s do not play a
  3848. significant role in the syntax.
  3849. Case is significant except in representations of booleans, number
  3850. objects, and in hexadecimal numbers specifying Unicode scalar values.
  3851. For example, @code{#x1A} and @code{#X1a} are equivalent. The identifier
  3852. @code{Foo} is, however, distinct from the identifier @code{FOO}.
  3853. @subsection Formal account
  3854. @noindent
  3855. @var{Interlexeme-space} may occur on either side of any lexeme, but not
  3856. within a lexeme.
  3857. @meta{Identifier}s, @code{.}, @meta{number}s, @meta{character}s, and
  3858. @meta{boolean}s, must be terminated by a @meta{delimiter} or by the end
  3859. of the input.
  3860. @c The following two characters are reserved for future extensions to the
  3861. @c language: @code{@{ @}}
  3862. @display
  3863. @stxdef{lexeme} @stxref{identifier} | @var{boolean} | @stxref{number}
  3864. | @var{character} | @stxref{string}
  3865. | @stxlit{(} | @stxlit{)} | @stxlit{[} | @stxlit{]} | @stxlit{#(}
  3866. | @stxlit{'} | @stxlit{`} | @stxlit{,} | @stxlit{,@@} | @stxlit{.}
  3867. | @stxlit{#'} | @stxlit{#`} | @stxlit{#,} | @stxlit{#,@@}
  3868. @stxdef{delimiter} @stxlit{(} | @stxlit{)} | @stxlit{[} | @stxlit{]} | @stxlit{"} | @stxlit{;} | @stxlit{#}
  3869. | @stxref{whitespace}
  3870. @end display
  3871. ((UNFINISHED))
  3872. @subsection Line endings
  3873. Line endings are significant in Scheme in single--line comments
  3874. and within string literals.
  3875. In Scheme source code, any of the line endings in @meta{line-ending}
  3876. marks the end of a line. Moreover, the two--character line endings
  3877. @meta{carriage-return} @meta{linefeed} and @meta{carriage-return}
  3878. @meta{next-line} each count as a single line ending.
  3879. In a string literal, a @meta{line-ending} not preceded by a @code{\}
  3880. stands for a linefeed character, which is the standard line--ending
  3881. character of Scheme.
  3882. @subsection Whitespace and comments
  3883. @display
  3884. @stxdef{intraline-whitespace} @var{space} | @var{character-tabulation}
  3885. @stxdef{whitespace} @stxref{intraline-whitespace}
  3886. | @var{linefeed} | @var{line-tabulation} | @var{form-feed}
  3887. | @var{carriage-return} | @var{next-line}
  3888. | @i{any character whose category is Zs, Zl, or Zp}
  3889. @stxdef{line-ending} @var{linefeed} | @var{carriage return}
  3890. | @var{carriage-return} @var{linefeed} | @var{next-line}
  3891. | @var{carriage-return} @var{next-line} | @var{line-separator}
  3892. @stxdef{comment} @stxlit{;} all subsequent characters up to a @var{line-ending}
  3893. or @var{paragraph-separator}
  3894. | @stxref{nested-comment}
  3895. | @stxlit{#;} @stxref{interlexeme-space} @stxref{datum}
  3896. | @stxref{shebang-comment}
  3897. @stxdef{nested-comment} @stxlit{#|} @stxref{comment-text} @stxref{comment-cont}* @stxlit{|#}
  3898. @stxdef{comment-text} character sequence not containing @stxlit{#|} or @stxlit{|#}
  3899. @stxdef{comment-cont} @stxref{nested-comment} @stxref{comment-text}
  3900. @stxdef{atmosphere} @stxref{whitespace} | @stxref{comment}
  3901. @stxdef{interlexeme-space} @arbno{@var{atmosphere}}
  3902. @end display
  3903. As a special case the characters @stxlit{#!/} are treated as starting a comment,
  3904. but only at the beginning of file. These characters are used on
  3905. Unix systems as an @uref{http://en.wikipedia.org/wiki/Shebang_(Unix), Shebang interpreter directive}.
  3906. The Kawa reader skips the entire line.
  3907. If the last non-whitespace character is @stxlit{@backslashchar{}}
  3908. (backslash) then the following line is also skipped, and so on.
  3909. @display
  3910. @stxdef{shebang-comment} @stxlit{#!} @var{absolute-filename} text up to non-escaped @var{line-ending}
  3911. @end display
  3912. @noindent
  3913. @emph{Whitespace} characters are spaces, linefeeds, carriage returns,
  3914. character tabulations, form feeds, line tabulations, and any other
  3915. character whose category is Zs, Zl, or Zp. Whitespace is used for
  3916. improved readability and as necessary to separate lexemes from each
  3917. other. Whitespace may occur between any two lexemes, but not within a
  3918. lexeme. Whitespace may also occur inside a string, where it is
  3919. significant.
  3920. The lexical syntax includes several comment forms. In all cases,
  3921. comments are invisible to Scheme, except that they act as delimiters,
  3922. so, for example, a comment cannot appear in the middle of an identifier
  3923. or representation of a number object.
  3924. A semicolon (@code{;}) indicates the start of a line comment. The
  3925. comment continues to the end of the line on which the semicolon appears.
  3926. Another way to indicate a comment is to prefix a @stxref{datum}
  3927. with @code{#;}, possibly with
  3928. @meta{interlexeme-space} before the @meta{datum}. The comment consists
  3929. of the comment prefix @code{#;} and the @meta{datum} together. This
  3930. notation is useful for ``commenting out'' sections of code.
  3931. Block comments may be indicated with properly nested @code{#|} and
  3932. @code{|#} pairs.
  3933. @example
  3934. #|
  3935. The FACT procedure computes the factorial of a
  3936. non-negative integer.
  3937. |#
  3938. (define fact
  3939. (lambda (n)
  3940. ;; base case
  3941. (if (= n 0)
  3942. #;(= n 1)
  3943. 1 ; identity of *
  3944. (* n (fact (- n 1))))))
  3945. @end example
  3946. @c The lexeme @code{#!r6rs}, which signifies that the program text that
  3947. @c follows is written with the lexical and datum syntax described in this
  3948. @c report, is also otherwise treated as a comment.
  3949. @subsection Identifiers
  3950. @display
  3951. @stxdef{identifier} @stxref{initial} @stxref{subsequent}*
  3952. | @stxref{peculiar-identifier}
  3953. @stxdef{initial} @stxref{constituent} | @stxref{special-initial}
  3954. | @stxref{inline-hex-escape}
  3955. @stxdef{letter} @stxlit{a} | @stxlit{b} | @stxlit{c} | ... | @stxlit{z}
  3956. | @stxlit{A} | @stxlit{B} | @stxlit{C} | ... | @stxlit{Z}
  3957. @stxdef{constituent} @stxref{letter}
  3958. | @i{any character whose Unicode scalar value is greater than
  3959. 127, and whose category is Lu, Ll, Lt, Lm, Lo, Mn,
  3960. Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co}
  3961. @stxdef{special-initial} @stxlit{!} | @stxlit{$} | @stxlit{%} | @stxlit{&} | @stxlit{*} | @stxlit{/} | @stxlit{<} | @stxlit{=}
  3962. | @stxlit{>} | @stxlit{?} | @stxlit{^} | @stxlit{_} | @stxlit{~}
  3963. @stxdef{subsequent} @stxref{initial} | @stxref{digit}
  3964. | @i{any character whose category is Nd, Mc, or Me}
  3965. | @stxref{special-subsequent}
  3966. @stxdef{digit} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7} | @stxlit{8} | @stxlit{9}
  3967. @stxdef{oct-digit} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7}
  3968. @stxdef{hex-digit} @stxref{digit}
  3969. | @stxlit{a} | @stxlit{A} | @stxlit{b} | @stxlit{B} | @stxlit{c} | @stxlit{C} | @stxlit{d} | @stxlit{D} | @stxlit{e} | @stxlit{E} | @stxlit{f} | @stxlit{F}
  3970. @stxdef{special-subsequent} @stxlit{+} | @stxlit{-} | @stxlit{.} | @stxlit{@@}
  3971. @stxdef{escape-sequence} @stxref{inline-hex-escape}
  3972. | @stxlit{\\}@stxref{character-except-x}
  3973. | @stxref{multi-escape-sequence}
  3974. @stxdef{inline-hex-escape} @stxlit{\\x}@stxref{hex-scalar-value}@stxlit{;}
  3975. @stxdef{hex-scalar-value} @stxref{hex-digit}+
  3976. @stxdef{multi-escape-sequence} @stxlit{|}@arbno{@stxref{symbol-element}}@stxlit{|}
  3977. @stxdef{symbol-element} @i{any character except} @stxlit{|} @i{or} @stxlit{@backslashchar{}}
  3978. | @stxref{inline-hex-escape} | @stxref{mnemonic-escape} | @stxlit{@backslashchar{}|}
  3979. @stxdef{character-except-x} @i{any character except @code{x}}
  3980. @stxdef{peculiar-identifier} @stxlit{+} | @stxlit{-} | @stxlit{...} | @stxlit{->} @arbno{@var{subsequent}}
  3981. @end display
  3982. Most identifiers allowed by other programming languages are also
  3983. acceptable to Scheme. In general, a sequence of letters, digits, and
  3984. ``extended alphabetic characters'' is an identifier when it begins with
  3985. a character that cannot begin a representation of a number object. In
  3986. addition, @code{+}, @code{-}, and @code{...} are identifiers, as is a
  3987. sequence of letters, digits, and extended alphabetic characters that
  3988. begins with the two--character sequence @code{->}. Here are some
  3989. examples of identifiers:
  3990. @example
  3991. lambda q soup
  3992. list->vector + V17a
  3993. <= a34kTMNs ->-
  3994. the-word-recursion-has-many-meanings
  3995. @end example
  3996. Extended alphabetic characters may be used within identifiers as if they
  3997. were letters. The following are extended alphabetic characters:
  3998. @example
  3999. ! $ % & * + - . / < = > ? @@ ^ _ ~
  4000. @end example
  4001. Moreover, all characters whose Unicode scalar values are greater than
  4002. 127 and whose Unicode category is Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd,
  4003. Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co can be used within
  4004. identifiers. In addition, any character can be used within an
  4005. identifier when specified using an @meta{escape-sequence}. For example,
  4006. the identifier @code{H\x65;llo} is the same as the identifier
  4007. @code{Hello}.
  4008. Kawa supports two additional non-R6RS ways of making
  4009. identifiers using special characters, both taken from Common Lisp:
  4010. Any character (except @code{x}) following a backslash is treated
  4011. as if it were a @var{letter};
  4012. as is any character between a pair of vertical bars.
  4013. @c , and the identifier @code{\x3BB;} is the same as the
  4014. @c identifier $\lambda$.
  4015. Identifiers have two uses within Scheme programs:
  4016. @itemize
  4017. @item
  4018. Any identifier may be used as a @ref{variable-reference,,variable}
  4019. or as a @ref{macro-reference,,syntactic keyword}.
  4020. @item
  4021. When an identifier appears as or with in @ref{literal-expression,,literal},
  4022. it is being used to denote a @ref{Simple symbols,,symbol}.
  4023. @end itemize
  4024. In contrast with older versions of Scheme, the syntax distinguishes
  4025. between upper and lower case in identifiers and in characters
  4026. specified via their names, but not in numbers, nor in inline hex
  4027. escapes used in the syntax of identifiers, characters, or strings.
  4028. The following directives give explicit control over case folding.
  4029. @deffn Syntax #!fold-case
  4030. @deffnx Syntax #!no-fold-case
  4031. These directives may appear anywhere comments are permitted and are
  4032. treated as comments, except that they affect the reading of subsequent
  4033. data. The @code{#!fold-case} directive causes the @code{read}
  4034. procedure to case-fold (as if by @code{string-foldcase}) each
  4035. identifier and character name subsequently read from the same
  4036. port. The @code{#!no-fold-case} directive causes the @code{read}
  4037. procedure to return to the default, non-folding behavior.
  4038. @end deffn
  4039. Note that colon @code{:} is treated specially for
  4040. @ref{Colon notation, colon notation} in Kawa Scheme,
  4041. though it is a @var{special-initial} in standard Scheme (R6RS).
  4042. @subsection Numbers
  4043. ((INCOMPLETE))
  4044. @display
  4045. @stxdef{number} ((TODO))
  4046. | @stxref{quantity}
  4047. @stxdef{decimal} @stxref{digit}+ @stxref{optional-exponent}
  4048. | @stxlit{.} @stxref{digit}+ @stxref{optional-exponent}
  4049. | @stxref{digit}+ @stxlit{.} @stxref{digit}+ @stxref{optional-exponent}
  4050. @end display
  4051. @display
  4052. @stxdef{optional-exponent} @i{empty}
  4053. | @stxref{exponent-marker} @stxref{optional-sign} @stxref{digit}+
  4054. @stxdef{exponent-marker} @stxlit{e} | @stxlit{s} | @stxlit{f} | @stxlit{d} | @stxlit{l}
  4055. @end display
  4056. The letter used for the exponent in a floating-point literal determines
  4057. its type:
  4058. @table @asis
  4059. @item @stxlit{e}
  4060. Returns a @code{gnu.math.DFloat} - for example @code{12e2}.
  4061. Note this matches the default when there is no @stxref{exponent-marker}.
  4062. @item @stxlit{s} or @stxlit{f}
  4063. Returns a primitive @code{float} (or @code{java.lang.Float}
  4064. when boxed as an object) - for example @code{12s2} or @code{12f2}.
  4065. @item @stxlit{d}
  4066. Returns a primitive @code{double} (or @code{java.lang.Double} when boxed)
  4067. - for example @code{12d2}.
  4068. @item @stxlit{l}
  4069. Returns a @code{java.math.BigDecimal} - for example @code{12l2}.
  4070. @end table
  4071. @display
  4072. @stxdef{optional-sign} @i{empty} | @stxlit{+} | @stxlit{-}
  4073. @stxdef{digit-2} @stxlit{0} | @stxlit{1}
  4074. @stxdef{digit-8} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7}
  4075. @stxdef{digit-10} @stxref{digit}
  4076. @stxdef{digit-16} @stxref{digit-10} | @stxlit{a} | @stxlit{b} | @stxlit{c} | @stxlit{d} | @stxlit{e} | @stxlit{f}
  4077. @end display
  4078. @node Datum syntax, Hash-prefixed forms, Lexical syntax, Syntax
  4079. @section Datum syntax
  4080. The datum syntax describes the syntax of syntactic data in terms of a
  4081. sequence of @meta{lexeme}s, as defined in the lexical syntax.
  4082. The following grammar describes the syntax of syntactic data in terms of
  4083. various kinds of lexemes defined in the grammar in section ``Lexical
  4084. Syntax'':
  4085. @display
  4086. @stxdef{datum} @stxref{defining-datum}
  4087. | @stxref{nondefining-datum}
  4088. | @stxref{defined-datum}
  4089. @stxdef{nondefining-datum} @stxref{lexeme-datum}
  4090. | @stxref{compound-datum}
  4091. @stxdef{lexeme-datum} @stxref{boolean} | @meta{number}
  4092. | @stxref{character} | @stxref{string} | @stxref{symbol}
  4093. @stxdef{symbol} @stxref{identifier}
  4094. @stxdef{compound-datum} @stxref{list} | @stxref{vector} | @stxref{uniform-vector} | @stxref{array-literal} | @stxref{extended-string-literal} | @stxref{xml-literal}
  4095. @stxdef{list} @stxlit{(}@stxref{datum}*@stxlit{)}
  4096. | @stxlit{(}@atleastone{@stxref{datum}} @stxlit{.} @stxref{datum}@stxlit{)}
  4097. | @stxref{abbreviation}
  4098. @stxdef{vector} @stxlit{#(}@arbno{@stxref{datum}}@stxlit{)}
  4099. @end display
  4100. @c FIXME: add to abbrev-prefix: @stxlit{#,} | @stxlit{#,@@}
  4101. @anchor{datum labels}
  4102. @subsection Datum labels
  4103. @display
  4104. @stxdef{datum-label} @stxlit{#}@stxref{indexnum}@stxlit{=}
  4105. @stxdef{defining-datum} @atleastone{@stxref{datum-label}}@stxref{nondefining-datum}
  4106. @stxdef{defined-datum} @stxlit{#}@stxref{indexnum}@stxlit{#}
  4107. @stxdef{indexnum} @atleastone{@stxref{digit}}
  4108. @end display
  4109. The lexical syntax @code{#@meta{n}=@meta{datum}} reads the
  4110. same as @meta{datum}, but also results in @meta{datum} being
  4111. labelled by @meta{n}, which must a sequence of digits.
  4112. The lexical syntax @code{#@meta{n}#} serves as a reference to some
  4113. object labelled by @code{#@meta{n}=}; the result is the same object
  4114. (in the sense of @code{eq?}) as the @code{#@meta{n}=}.
  4115. Together, these syntaxes permit the notation of structures
  4116. with shared or circular substructure.
  4117. @example
  4118. (let ((x (list 'a 'b 'c)))
  4119. (set-cdr! (cddr x) x)
  4120. x) @result{} #0=(a b c . #0#)
  4121. @end example
  4122. The scope of a datum label is the portion of the outermost
  4123. datum in which it appears that is to the right of the label.
  4124. Consequently, a reference @code{#@meta{n}#} can occur
  4125. only after a label @code{#@meta{n}=};
  4126. it is an error to attempt a forward reference.
  4127. In addition, it is an error if the reference appears as the labelled
  4128. object itself (as in @code{#@meta{n}=#@var{n}#}), because the object
  4129. labelled by @code{#@var{n}=} is not well defined in this case.
  4130. @subsection Abbreviations
  4131. @display
  4132. @stxdef{abbreviation} @stxref{r6rs-abbreviation} | @stxref{kawa-abbreviation}
  4133. @stxdef{r6rs-abbreviation} @stxref{abbrev-prefix} @stxref{datum}
  4134. @stxdef{abbrev-prefix} @stxlit{'} | @stxlit{`} | @stxlit{,} | @stxlit{,@@}
  4135. | @stxlit{#'} | @stxlit{#`}
  4136. @stxdef{kawa-abbreviation} XXX
  4137. @end display
  4138. The following abbreviations are expanded at read-time:
  4139. @table @asis
  4140. @item @stxlit{'}@meta{datum}
  4141. means @stxlit{(quote} @meta{datum}@stxlit{)}.
  4142. @item @stxlit{`}@meta{datum}
  4143. means @stxlit{(quasiquote} @meta{datum}@stxlit{)}.
  4144. @item @stxlit{,}@meta{datum}
  4145. means @stxlit{(unquote} @meta{datum}@stxlit{)}.
  4146. @item @stxlit{,@@}@meta{datum}
  4147. means @stxlit{(unquote-splicing} @meta{datum}@stxlit{)}.
  4148. @item @stxlit{#'}@meta{datum}
  4149. means @stxlit{(syntax} @meta{datum}@stxlit{)}.
  4150. @item @stxlit{#`}@meta{datum}
  4151. means @stxlit{(quasisyntax} @meta{datum}@stxlit{)}.
  4152. @item @stxlit{#,}@meta{datum}
  4153. means @stxlit{(unsyntax} @meta{datum}@stxlit{)}.
  4154. This abbreviation is currently only recognized when nested inside an explicit
  4155. @stxlit{#`}@meta{datum} form,
  4156. because of a conflict with SRFI-10 named constructors.
  4157. @item @stxlit{#,@@}@meta{datum}
  4158. means @stxlit{(unsyntax-splicing} @meta{datum}@stxlit{)}.
  4159. @item @meta{datum1}@stxlit{:}@meta{datum2}
  4160. means @stxlit{($lookup$} @meta{datum1} @stxlit{(quasiquote} @meta{datum2}@stxlit{))}.
  4161. @xref{Colon notation}.
  4162. @item @stxlit{[}@meta{expression} ...@stxlit{]}
  4163. means @stxlit{($bracket-list$} @meta{expression} ...@stxlit{)}.
  4164. @item @meta{operator}@stxlit{[}@meta{expression} ...@stxlit{]}
  4165. means @stxlit{($bracket-apply$} @meta{operator} @meta{expression} ...@stxlit{)}.
  4166. @end table
  4167. @node Hash-prefixed forms
  4168. @section Hash-prefixed forms
  4169. A number of different special forms are indicated by an
  4170. initial hash (number) symbols (@code{#}).
  4171. Here is a table summarizing them.
  4172. Case is ignored for the character followed the @code{#}.
  4173. Thus @code{#x} and @code{#X} are the same.
  4174. @table @asis
  4175. @item @stxlit{#:}@var{keyword}
  4176. Guile-style @ref{Keywords,keyword} syntax.
  4177. @item @stxlit{#\\}
  4178. @ref{meta-character, Character literals, Character literals}.
  4179. @item @stxlit{#!}
  4180. @xref{Special named constants}.
  4181. @item @stxlit{#`}@var{datum}
  4182. Equivalent to @code{(quasisyntax @var{datum})}.
  4183. Convenience syntax for syntax-case macros.
  4184. @item @stxlit{#'}@var{datum}
  4185. Equivalent to @code{(syntax @var{datum})}.
  4186. Convenience syntax for syntax-case macros.
  4187. @item @stxlit{#,}@var{datum}
  4188. Equivalent to @code{(unsyntax @var{datum})}.
  4189. Currently only recognized when inside a @code{#`@var{template}} form.
  4190. Convenience syntax for syntax-case macros.
  4191. @item @stxlit{#,(}@var{name} @var{datum} ...@stxlit{)}
  4192. Special named constructors.
  4193. This syntax is deprecated, because it conflicts with @code{unsyntax}.
  4194. It is only recognized when @emph{not} in a @code{#`@var{template}} form.
  4195. @item @stxlit{#,@@}@var{datum}
  4196. Equivalent to @code{(unsyntax-splicing @var{datum})}.
  4197. @item @stxlit{#(}
  4198. A vector.
  4199. @item @stxlit{#|}
  4200. Start of nested-comment.
  4201. @item @stxlit{#/}@var{regex}@stxlit{/}
  4202. @xref{Regular expressions}.
  4203. @item @stxlit{#<}
  4204. @xref{XML literals}.
  4205. @item @stxlit{#;}@var{datum}
  4206. A datum comment - the @var{datum} is ignored.
  4207. (An @var{interlexeme-space} may appear before the @var{datum}.)
  4208. @item @stxlit{#}@var{number}@stxlit{=}@var{datum}
  4209. A reference definition, allowing cyclic and shared structure.
  4210. Equivalent to the @var{datum}, but also defines an association between
  4211. the integer @var{number} and that @var{datum}, which can be
  4212. used by a subsequent @code{#@var{number}#} form.
  4213. @item @stxlit{#}@var{number}@stxlit{#}
  4214. A back-reference, allowing cyclic and shared structure.
  4215. @item @stxlit{#}@var{R}@stxlit{a}@var{datum}
  4216. An @ref{array-literals,array literal},
  4217. for a multi-dimensional array of rank @var{R}.
  4218. @item @stxlit{#b}
  4219. A binary (base-2) number.
  4220. @item @stxlit{#d}
  4221. A decimal (base-10) number.
  4222. @item @stxlit{#e}
  4223. A prefix to treat the following number as exact.
  4224. @item @stxlit{#f}
  4225. @itemx @stxlit{#false}
  4226. The standard boolean false object.
  4227. @item @stxlit{#f}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
  4228. A uniform vector of floating-point numbers.
  4229. The parameter @var{n} is a precision, which can be 32 or 64.
  4230. @xref{Uniform vectors}.
  4231. @item @stxlit{#i}
  4232. A prefix to treat the following number as inexact.
  4233. @item @stxlit{#o}
  4234. An octal (base-8) number.
  4235. @item @stxlit{#}@var{base}@stxlit{r}
  4236. A number in the specified @var{base} (radix).
  4237. @item @stxlit{#s}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
  4238. A uniform vector of signed integers.
  4239. The parameter @var{n} is a precision, which can be 8, 16, 32, or 64.
  4240. @xref{Uniform vectors}.
  4241. @item @stxlit{#t}
  4242. @itemx @stxlit{#true}
  4243. The standard boolean true object.
  4244. @item @stxlit{#u}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
  4245. A uniform vector of unsigned integers.
  4246. The parameter @var{n} is a precision, which can be 8, 16, 32, or 64.
  4247. @xref{Uniform vectors}.
  4248. @item @stxlit{#x}
  4249. A hexadecimal (base-16) number.
  4250. @end table
  4251. The follow named constructor forms are supported:
  4252. @table @asis
  4253. @item @stxlit{#,(path} @var{path}@stxlit{)}
  4254. @item @stxlit{#,(filepath} @var{path}@stxlit{)}
  4255. @item @stxlit{#,(URI} @var{path}@stxlit{)}
  4256. @item @stxlit{#,(symbol} @var{local-name} [@var{uri} [@var{prefix}]]@stxlit{)}
  4257. @itemx @stxlit{#,(symbol} @var{local-name} @var{namespace}@stxlit{)}
  4258. @item @stxlit{#,(namespace} @var{uri} [@var{prefix}]@stxlit{)}
  4259. @item @stxlit{#,(duration} @var{duration}@stxlit{)}
  4260. @end table
  4261. @node Primitive expression syntax
  4262. @section Primitive expression syntax
  4263. @display
  4264. @stxdef{expression} @stxref{literal-expression} | @stxref{variable-reference}
  4265. | @stxref{procedure-call} | TODO
  4266. @end display
  4267. @anchor{literal-expression}
  4268. @subsection Literal expressions
  4269. @display
  4270. @stxdef{literal-expression} @stxlit{(quote} @stxref{datum}@stxlit{)}
  4271. | @stxlit{'} @stxref{datum}
  4272. | @var{constant}
  4273. @stxdef{constant} @var{number} | @meta{boolean} | @meta{character} | @meta{string}
  4274. @end display
  4275. @code{(quote @var{datum})} evaluates to @var{datum},
  4276. which may be any external representation of a Scheme object.
  4277. This notation is used to include literal constants in Scheme code.
  4278. @example
  4279. (quote a) @result{} a
  4280. (quote #(a b c)) @result{} #(a b c)
  4281. (quote (+ 1 2)) @result{} (+ 1 2)
  4282. @end example
  4283. @code{(quote @var{datum})} may be abbreviated as @code{'@var{datum}}.
  4284. The two notations are equivalent in all respects.
  4285. @example
  4286. ’a @result{} a
  4287. ’#(a b c) @result{} #(a b c)
  4288. ’() @result{} ()
  4289. ’(+ 1 2) @result{} (+ 1 2)
  4290. ’(quote a) @result{} (quote a)
  4291. ’’a @result{} (quote a)
  4292. @end example
  4293. Numerical constants, string constants, character constants,
  4294. bytevector constants, and boolean constants evaluate to
  4295. themselves; they need not be quoted.
  4296. @example
  4297. 145932 @result{} 145932
  4298. #t @result{} #t
  4299. "abc" @result{} "abc"
  4300. @end example
  4301. @c #vu8(2 24 123) @result{} #vu8(2 24 123)
  4302. Note that @ref{Keywords,keywords} need to be quoted,
  4303. unlike some other Lisp/Scheme dialect, including Common Lisp,
  4304. and earlier versions of Kawa. (Kawa currently evaluates a non-quoted
  4305. keyword as itself, but that will change.)
  4306. @anchor{variable-reference}
  4307. @subsection Variable references
  4308. @display
  4309. @stxdef{variable-reference} @stxref{identifier}
  4310. @end display
  4311. An expression consisting of a variable is a variable reference if it is
  4312. not a macro use (see below). The value of the variable reference is the
  4313. value stored in the location to which the variable is bound. It is a
  4314. syntax violation to reference an unbound variable.
  4315. The following example assumes the base library has been
  4316. imported:
  4317. @example
  4318. (define x 28)
  4319. x @result{} 28
  4320. @end example
  4321. @subsection Procedure calls
  4322. @display
  4323. @stxdef{procedure-call} @stxlit{(}@stxref{operator} @stxref{operand} @dots{})
  4324. @stxdef{operator} @stxref{expression}
  4325. @stxdef{operand} @stxref{expression}
  4326. | @stxref{keyword} @stxref{expression}
  4327. | @code{@@} @stxref{expression}
  4328. | @code{@@:} @stxref{expression}
  4329. @end display
  4330. A procedure call consists of expressions for the procedure to be called
  4331. and the arguments to be passed to it, with enclosing parentheses. A
  4332. form in an expression context is a procedure call if @meta{operator} is
  4333. not an identifier bound as a syntactic keyword.
  4334. When a procedure call is evaluated, the operator and operand expressions
  4335. are evaluated (in an unspecified order) and the resulting procedure is
  4336. passed the resulting arguments.
  4337. @example
  4338. (+ 3 4) @result{} 7
  4339. ((if #f + *) 3 4) @result{} 12
  4340. @end example
  4341. The syntax @stxref{keyword} @var{expression} is a @dfn{keyword argument}.
  4342. This is a mechanism for specifying arguments using a name rather than position,
  4343. and is especially useful for procedures with many optional paramaters.
  4344. Note that @stxref{keyword} must be literal, and cannot be the
  4345. result from evaluating a non-literal expression.
  4346. (This is a change from previous versions of Kawa,
  4347. and is different from Common Lisp and some other Scheme dialects.)
  4348. An expression prefixed by @code{@@} or @code{@@:} is
  4349. a splice argument. The following expression must evaluate to an
  4350. ``argument list'' (see @ref{Application and Arguments Lists} for details);
  4351. each element in the argument
  4352. becomes a separate argument when call the @var{operator}.
  4353. (This is very similar to the ``spread'' operator is EcmaScript 6.)
  4354. @node Colon notation
  4355. @section Property access using colon notation
  4356. @cindex colon notation
  4357. The @dfn{colon notation} accesses named parts (properties) of a value.
  4358. It is used to get and set fields, call methods, construct compound symbols,
  4359. and more.
  4360. Evaluating the form @code{@var{owner}:@var{property}}
  4361. evaluates the @code{@var{owner}} then it extracts the named @code{@var{property}} of the result.
  4362. @display
  4363. @stxdef{property-access-abbreviation} @stxref{property-owner-expression}@stxlit{:}@stxref{property-name}
  4364. @stxdef{property-owner-expression} @stxref{expression}
  4365. @stxdef{property-name} @stxref{identifier} | @stxlit{,}@stxref{expression}
  4366. @end display
  4367. The @var{property-name} is usually a literal name,
  4368. but it can be an unquoted @var{expression} (i.e. following a @code{,}),
  4369. in which case the name is evaluated at run-time.
  4370. No separators are allowed on either side of the colon.
  4371. The input syntax @code{@var{owner}:@var{part}} is translated by
  4372. the Scheme reader to the internal representation @code{($lookup$ @var{owner} (quasiquote @var{part}))}.
  4373. @subsection Part lookup rules
  4374. Evaluation proceeds as follows.
  4375. First @var{property-owner-expression} is
  4376. evaluated to yield an @var{owner} object.
  4377. Evaluating the @var{property-name} yields a @var{part} name,
  4378. which is a simple symbol: Either
  4379. the literal @var{identifier}, or the result of evaluating the
  4380. property-name @var{expression}.
  4381. If the @var{expression} evaluates to a string, it is converted to
  4382. a symbol, as if using @code{string->symbol}.
  4383. @itemize
  4384. @item
  4385. If the @var{owner} implements @code{gnu.mapping.HasNamedParts},
  4386. then the result is that of invoking the @code{get} method of the @var{owner}
  4387. with the @var{part} name as a parameter.
  4388. As a special case of this rule, if @var{owner} is a
  4389. @code{gnu.mapping.Namespace}, then the result is the
  4390. @ref{Namespaces,compound symbol in that namespace}.
  4391. @item
  4392. If @var{owner} is a @code{java.lang.Class} or a @code{gnu.bytecode.ObjectType},
  4393. the result is the static member named @var{part}
  4394. (i.e. a static field, method, or member class).
  4395. @item
  4396. If @var{owner} is a @code{java.lang.Package} object, we get the member
  4397. class or sub-package named @var{part}.
  4398. @item
  4399. Otherwise, we look for a named member (instance member or field).
  4400. Note you can't use colon notation to invoke instance methods
  4401. of a @code{Class}, because it will match a previous rule.
  4402. For example if you want to invoke the @code{getDeclaredMethod}
  4403. method of the @code{java.util.List} , you can't write @code{(java.util.List:getDeclaredMethod} because that will look for a static method in @code{java.util.List}.
  4404. Instead, use the @code{invoke} or @code{invoke-sttic} method. For example:
  4405. @code{(invoke java.util.List 'getDeclaredMethod)}.
  4406. @end itemize
  4407. If the colon form is on the left-hand-side of an assignment (@code{set!}),
  4408. then the named part is modified as appropriate.
  4409. @c We will look into examples and details below.
  4410. @c @subsection The @code{HasNamedParts} case
  4411. @c @subsection Static parts of classes and packages
  4412. @c @subsection Instance parts
  4413. @subsection Specific cases
  4414. Some of these are deprecated;
  4415. more compact and readable forms are usually preferred.
  4416. @subsubsection Invoking methods
  4417. @display
  4418. @stxlit{(}@var{instance}@stxlit{:}@stxref{method-name} @var{arg} ...@stxlit{)}
  4419. @stxlit{(}@var{class}@stxlit{:}@stxref{method-name} @var{instance} @var{arg} ...@stxlit{)}
  4420. @stxlit{(}@var{class}@stxlit{:}@stxref{method-name} @var{arg} ...@stxlit{)}
  4421. @stxlit{(*:}@stxref{method-name} @var{instance} @var{arg} ...@stxlit{)}
  4422. @end display
  4423. For details @pxref{Method operations}.
  4424. @subsubsection Accessing fields
  4425. @display
  4426. @var{class}@stxlit{:}@stxref{field-name}
  4427. @var{instance}@stxlit{:}@stxref{field-name}
  4428. @stxlit{(}@var{prefix}@stxlit{:.}@stxref{field-name} @var{instance}@stxlit{)}
  4429. @end display
  4430. For details @pxref{Field operations}.
  4431. @subsubsection Type literal
  4432. @display
  4433. @stxlit{(}@stxref{type}@stxlit{:<>)}
  4434. @end display
  4435. Returns the @var{type}.
  4436. Deprecated; usually you can just write:
  4437. @example
  4438. @var{type}
  4439. @end example
  4440. @subsubsection Type cast
  4441. @display
  4442. @stxlit{(}@stxref{type}@stxlit{:}@stxlit{@atchar{}} @stxref{expression}@stxlit{)}
  4443. @end display
  4444. Performs a cast.
  4445. Deprecated; usually you can just write:
  4446. @example
  4447. ->@var{type}
  4448. @end example
  4449. @subsubsection Type test
  4450. @display
  4451. @stxlit{(}@stxref{type}@stxlit{:instanceof?} @stxref{expression}@stxlit{)}
  4452. @end display
  4453. Deprecated; usually you can just write:
  4454. @example
  4455. (@var{type}? @var{expression})
  4456. @end example
  4457. @subsubsection New object construction
  4458. @display
  4459. @stxlit{(}@stxref{type}@stxlit{:new} @var{arg} ...@stxlit{)}
  4460. @end display
  4461. Deprecated; usually you can just write:
  4462. @display
  4463. @stxlit{(}@stxref{type} @var{arg} ...@stxlit{)}
  4464. @end display
  4465. @subsubsection Getting array length
  4466. @display
  4467. @stxref{expression}@stxlit{:length}
  4468. @stxlit{(}@stxref{expression}@stxlit{:.length)}
  4469. @end display
  4470. @node Bodies
  4471. @section Programs and Bodies
  4472. @anchor{program units}
  4473. @subheading Program units
  4474. A @meta{program-unit} consists of a sequence of definitions and expressions.
  4475. @display
  4476. @stxdef{program-unit} @atleastone{@stxref{library-definition}} [@stxref{statements}]
  4477. | @stxref{statements}
  4478. @stxdef{statements} @atleastone{@stxref{statement}}
  4479. @stxdef{statement} @var{definition} | @stxref{expression} | @stxlit{(begin} @arbno{@stxref{statement}} @stxlit{)}
  4480. @end display
  4481. Typically a @meta{program-unit} corresponds to a single source file
  4482. (i.e.a named file in the file system). Evaluating a @meta{program-unit}
  4483. first requires the Kawa processor to analyze
  4484. the whole @meta{program-unit} to determine which names are defined by the
  4485. definitions, and then evaluates each @meta{statement} in order in the context
  4486. of the defined names. The value of an @meta{expression} is normally
  4487. discarded, but may be printed out instead, depending on the evaluating context.
  4488. The read-eval-print-loop (REPL) reads one or more lines until it gets
  4489. a valid @meta{program-unit}, and evaluates it as above, except that the
  4490. values of expressions are printed to the console (as if using the
  4491. @code{display} function). Then the REPL reads and evaluates
  4492. another @meta{program-unit}, and so on. A definition in an earlier
  4493. @meta{program-unit} is remembered and is visible in a later @meta{program-unit}
  4494. unles it is overridden.
  4495. @cindex encoding specifier
  4496. @cindex coding specifier
  4497. A comment in the first 2 lines of a source file may contain an encoding
  4498. specification. This can be used to tell the reader what kind of character
  4499. set encoding is used for the file. This only works for a character
  4500. encoding that is compatible with ASCII (in the sense that if the
  4501. high-order bit is clear then it's an ASCII character),
  4502. and that are no non-ASCI characters in the lines upto and including
  4503. the encoding specification.
  4504. A basic example is:
  4505. @example
  4506. ;; -*- coding: utf-8 -*-
  4507. @end example
  4508. In general any string that matches the following regular expression works:
  4509. @example
  4510. coding[:=]\s*([-a-zA-Z0-9]+)
  4511. @end example
  4512. @subheading Libraries
  4513. @anchor{implicit library}
  4514. A @meta{program-unit} may contain @meta{library-definitions}.
  4515. In addition, any @meta{statements} in @meta{program-unit} comprise
  4516. an @dfn{implicit library}, in that it can be given a name, and referenced
  4517. from other libraries.
  4518. Certain names defined in the @meta{program-unit} can be exported,
  4519. and then they can be imported by other libraries.
  4520. For more information @pxref{Module classes}.
  4521. It is recommended but not required that:
  4522. @itemize
  4523. @item
  4524. There should be at most one @meta{library-definition} in a @meta{program-unit}.
  4525. @item
  4526. The @meta{library-name} of the @meta{library-definition} should
  4527. match the name of the source file. For example:
  4528. @example
  4529. (define-library (foo bar) ...)
  4530. @end example
  4531. should be in a file named @code{foo/bar.scm}.
  4532. @item
  4533. If there is a @meta{library-definition}, there should
  4534. be no extra @meta{statements} - i.e no implicit library definition.
  4535. (It is disallowed to @code{export} any definitions from the
  4536. implicit library if there is also a @meta{library-definition}.)
  4537. @end itemize
  4538. Following these recommendations makes it easier to locate
  4539. and organize libraries.
  4540. However, having multiple libraries in a single @meta{program-unit}
  4541. is occasionally useful for source distribution and for testing.
  4542. @subheading Bodies
  4543. The @meta{body} of a @func{lambda}, @func{let}, @func{let*},
  4544. @func{let-values}, @func{let*-values}, @func{letrec}, or @func{letrec*}
  4545. expression, or that of a definition with a body consists of zero or more
  4546. definitions or expressions followed by a final expression.
  4547. (Standard Scheme requires that all definitions precede all expressions.)
  4548. @display
  4549. @stxdef{body} @arbno{@stxref{statement}}
  4550. @end display
  4551. Each identifier defined by a definition is local to the @meta{body}.
  4552. That is, the identifier is bound, and the region of the binding is the
  4553. entire @meta{body}.
  4554. Example:
  4555. @example
  4556. (let ((x 5))
  4557. (define foo (lambda (y) (bar x y)))
  4558. (define bar (lambda (a b) (+ (* a b) a)))
  4559. (foo (+ x 3)))
  4560. @result{} 45
  4561. @end example
  4562. When @func{begin}, @func{let-syntax}, or @func{letrec-syntax} forms
  4563. occur in a body prior to the first expression, they are spliced into the
  4564. body. Some or all of the body, including portions wrapped in
  4565. @func{begin}, @func{let-syntax}, or @func{letrec-syntax} forms, may be
  4566. specified by a macro use.
  4567. An expanded @meta{body} containing variable definitions can be
  4568. converted into an equivalent @func{letrec*} expression.
  4569. (If there is a definition following expressions you may need to
  4570. convert the expressions to dummy definitions.) For example,
  4571. the @func{let} expression in the above example is equivalent to
  4572. @example
  4573. (let ((x 5))
  4574. (letrec* ((foo (lambda (y) (bar x y)))
  4575. (bar (lambda (a b) (+ (* a b) a))))
  4576. (foo (+ x 3))))
  4577. @end example
  4578. @node Syntax and conditional compilation
  4579. @section Syntax and conditional compilation
  4580. @subheading Feature testing
  4581. @deffn Syntax cond-expand @arbno{@stxref{cond-expand-clause}} [@stxlit{(else} command-or-definition*@stxlit{)}]
  4582. @display
  4583. @stxdef{cond-expand-clause} @stxlit{(}@var{feature-requirement} @var{command-or-definition}*@stxlit{)}
  4584. @findex @i{fff-rec}
  4585. @stxdef{feature-requirement} @stxref{feature-identifier}
  4586. | @stxlit{(and} @arbno{@stxref{feature-requirement}}@stxlit{)}
  4587. | @stxlit{(or} @arbno{@stxref{feature-requirement}}@stxlit{)}
  4588. | @stxlit{(not} @stxref{feature-requirement}@stxlit{)}
  4589. | @stxlit{(library} @stxref{library-name}@stxlit{)}
  4590. @stxdef{feature-identifier} a symbol which is the name or alias of a SRFI
  4591. @end display
  4592. The @code{cond-expand} form tests for the existence of features at
  4593. macro-expansion time. It either expands into the body of one of its
  4594. clauses or signals an error during syntactic
  4595. processing. @code{cond-expand} expands into the body of the first clause
  4596. whose feature requirement is currently satisfied; the @code{else}
  4597. clause, if present, is selected if none of the previous clauses is
  4598. selected.
  4599. The implementation has a set of
  4600. feature identifiers which are ``present'', as well as a set
  4601. of libraries which can be imported.
  4602. The value of a
  4603. @meta{feature-requirement} is determined by replacing each
  4604. @meta{feature-identifier} by @code{#t} if it is present
  4605. (and @code{#f} otherwise);
  4606. replacing @code{(library @meta{library-name})}
  4607. by @code{#t} if @meta{library-name} is importable (and @code{#f} otherwise);
  4608. and then evaluating the resulting expression as a Scheme boolean expression
  4609. under the normal interpretation of @code{and}, @code{or}, and @code{not}.
  4610. Examples:
  4611. @example
  4612. (cond-expand
  4613. ((and srfi-1 srfi-10)
  4614. (write 1))
  4615. ((or srfi-1 srfi-10)
  4616. (write 2))
  4617. (else))
  4618. @end example
  4619. @example
  4620. (cond-expand
  4621. (command-line
  4622. (define (program-name) (car (argv)))))
  4623. @end example
  4624. The second example assumes that @code{command-line} is an alias for some
  4625. feature which gives access to command line arguments. Note that an error
  4626. will be signaled at macro-expansion time if this feature is not present.
  4627. You can use @code{java-6}, @code{java-7}, @code{java-8},
  4628. or @code{java-9} to check if the underlying Java
  4629. is a specific version or newer.
  4630. For example the name @code{java-7} matches for
  4631. either Java 7, Java 8, or newer, as
  4632. reported by @code{System} property @code{"java.version"}.
  4633. You can use @code{class-exists:@var{ClassName}} to check
  4634. if @code{@var{ClassName}} exists at compile-time.
  4635. The identifier @code{class-exists:org.example.MyClass}
  4636. is roughly equivalent to the test @code{(library (org example MyClass))}.
  4637. (The latter has some special handling for @code{(srfi ...)} as well
  4638. as builtin Kawa classes.)
  4639. The feature @code{in-http-server} is defined in a
  4640. @ref{Self-configuring page scripts,self-configuring web page scripts},
  4641. and more specifically @code{in-servlet} in a @ref{Servlets,servlet container}.
  4642. @end deffn
  4643. @deffn Procedure features
  4644. Returns a list of feature identifiers which @code{cond-expand}
  4645. treats as true.
  4646. This not a complete list - for example @code{class-exists:@var{ClassName}}
  4647. feature identifiers are not included.
  4648. It is an error to modify this list.
  4649. Here is an example of what @code{features} might return:
  4650. @example
  4651. (features) @result{}
  4652. (complex exact-complex full-unicode java-7 java-6 kawa
  4653. ratios srfi-0 srfi-4 srfi-6 srfi-8 srfi-9 srfi-11
  4654. srfi-16 srfi-17 srfi-23 srfi-25 srfi-26 srfi-28 srfi-30
  4655. srfi-39 string-normalize-unicode threads)
  4656. @end example
  4657. @end deffn
  4658. @subheading File inclusion
  4659. @anchor{include}
  4660. @anchor{include-relative}
  4661. @deffn Syntax include @atleastone{path}
  4662. @deffnx Syntax include-relative @atleastone{path}
  4663. @deffnx Syntax include-ci @atleastone{path}
  4664. These take one or more path names expressed as string literals,
  4665. find corresponding files, read the contents of the files in the specified order
  4666. as if by repeated applications of @code{read}, and effectively
  4667. replace the @code{include} with a @code{begin} form
  4668. containing what was read from the files.
  4669. You can control the search path used for @code{include}
  4670. by setting the @code{kawa.include.path} property. For example:
  4671. @example
  4672. $ kawa -Dkawa.include.path="|:/opt/kawa-includes"
  4673. @end example
  4674. The special @code{"|"} path element means to search
  4675. relative to the directory containing the including source file.
  4676. The default search path is @code{"|:."} which means to first
  4677. search the directory containing the including source file,
  4678. and then search the directory specified by @code{(current-path)}.
  4679. The search path for @code{include-relative} prepends @code{"|"}
  4680. before the search path used by @code{include}, so it always
  4681. searches first the directory containing the including source file.
  4682. Note that if the default search path is used then @code{include}
  4683. and @code{include-relative} are equivalent; there is only a difference
  4684. if the @code{kawa.include.path} property changes the default.
  4685. Using @code{include-ci} is like @code{include}, except that it reads each
  4686. file as if it began with the @code{#!fold-case} directive.
  4687. @end deffn
  4688. @node Macros
  4689. @section Macros
  4690. @anchor{macro-reference}
  4691. Libraries and top--level programs can define and use new kinds of
  4692. derived expressions and definitions called @emph{syntactic abstractions}
  4693. or @emph{macros}. A syntactic abstraction is created by binding a
  4694. keyword to a @emph{macro transformer} or, simply, @emph{transformer}.
  4695. The transformer determines how a use of the macro (called a @emph{macro
  4696. use}) is transcribed into a more primitive form.
  4697. Most macro uses have the form:
  4698. @example
  4699. (@meta{keyword} @meta{datum} @dots{})
  4700. @end example
  4701. @noindent
  4702. where @meta{keyword} is an identifier that uniquely determines the kind
  4703. of form. This identifier is called the @emph{syntactic keyword}, or
  4704. simply @emph{keyword}. The number of @meta{datum}s and the syntax of
  4705. each depends on the syntactic abstraction.
  4706. Macro uses can also take the form of improper lists, singleton
  4707. identifiers, or @func{set!} forms, where the second subform of the
  4708. @func{set!} is the keyword:
  4709. @example
  4710. (@meta{keyword} @meta{datum} @dots{} . @meta{datum})
  4711. @meta{keyword}
  4712. (set! @meta{keyword} @meta{datum})
  4713. @end example
  4714. The @func{define-syntax}, @func{let-syntax} and @func{letrec-syntax}
  4715. forms create bindings for keywords, associate them with macro
  4716. transformers, and control the scope within which they are visible.
  4717. The @func{syntax-rules} and @func{identifier-syntax} forms create
  4718. transformers via a pattern language. Moreover, the @func{syntax-case}
  4719. form allows creating transformers via arbitrary Scheme code.
  4720. Keywords occupy the same name space as variables. That is, within the
  4721. same scope, an identifier can be bound as a variable or keyword, or
  4722. neither, but not both, and local bindings of either kind may shadow
  4723. other bindings of either kind.
  4724. Macros defined using @func{syntax-rules} and @func{identifier-syntax}
  4725. are ``hygienic'' and ``referentially transparent'' and thus preserve
  4726. Scheme's lexical scoping.
  4727. @itemize
  4728. @item
  4729. If a macro transformer inserts a binding for an identifier (variable or
  4730. keyword) not appearing in the macro use, the identifier is in effect
  4731. renamed throughout its scope to avoid conflicts with other identifiers.
  4732. @item
  4733. If a macro transformer inserts a free reference to an identifier, the
  4734. reference refers to the binding that was visible where the transformer
  4735. was specified, regardless of any local bindings that may surround the
  4736. use of the macro.
  4737. @end itemize
  4738. Macros defined using the @func{syntax-case} facility are also hygienic
  4739. unless @func{datum->syntax} is used.
  4740. Kawa supports most of the @code{syntax-case} feature.
  4741. Syntax definitions are valid wherever definitions are.
  4742. They have the following form:
  4743. @deffn Syntax define-syntax keyword @stxref{transformer-spec}
  4744. The @var{keyword} is a identifier, and @var{transformer-spec}
  4745. is a function that maps syntax forms to syntax forms,
  4746. usually an instance of @code{syntax-rules}.
  4747. If the @code{define-syntax} occurs at the top level, then the top-level
  4748. syntactic environment is extended by binding the @var{keyword}
  4749. to the specified transformer, but existing references to any top-level
  4750. binding for @var{keyword} remain unchanged. Otherwise, it is an
  4751. @dfn{internal syntax definition}, and is local to the @var{body}
  4752. in which it is defined.
  4753. @example
  4754. (let ((x 1) (y 2))
  4755. (define-syntax swap!
  4756. (syntax-rules ()
  4757. ((swap! a b)
  4758. (let ((tmp a))
  4759. (set! a b)
  4760. (set! b tmp)))))
  4761. (swap! x y)
  4762. (list x y)) @result{} (2 1)
  4763. @end example
  4764. Macros can expand into definitions in any context that permits them.
  4765. However, it is an error for a definition to define an identifier
  4766. whose binding has to be known in order to determine the meaning
  4767. of the definition itself, or of any preceding definition that belongs
  4768. to the same group of internal definitions.
  4769. @end deffn
  4770. @deffn Syntax define-syntax-case name @stxlit{(}literals@stxlit{)} @stxlit{(}pattern expr@stxlit{)} ...
  4771. A convenience macro to make it easy to define @code{syntax-case}-style macros.
  4772. Defines a macro with the given @var{name} and list of @var{literals}.
  4773. Each @var{pattern} has the form of a @code{syntax-rules}-style pattern,
  4774. and it is matched against the macro invocation syntax form.
  4775. When a match is found, the corresponding @var{expr} is evaluated.
  4776. It must evaluate to a syntax form,
  4777. which replaces the macro invocation.
  4778. @example
  4779. (define-syntax-case macro-name (literals)
  4780. (pat1 result1)
  4781. (pat2 result2))
  4782. @end example
  4783. is equivalent to:
  4784. @example
  4785. (define-syntax macro-name
  4786. (lambda (form)
  4787. (syntax-case form (literals)
  4788. (pat1 result1)
  4789. (pat2 result2))))
  4790. @end example
  4791. @end deffn
  4792. @deffn Syntax define-macro @stxlit{(}name lambda-list@stxlit{)} form ...
  4793. @emph{This form is deprecated.}
  4794. Functionally equivalent to @code{defmacro}.
  4795. @end deffn
  4796. @deffn Syntax defmacro name lambda-list form ...
  4797. @emph{This form is deprecated.}
  4798. Instead of
  4799. @example
  4800. (defmacro (@var{name} ...)
  4801. (let ... `(... ,@var{exp} ...)))
  4802. @end example
  4803. you should probably do:
  4804. @example
  4805. (define-syntax-case @var{name} ()
  4806. ((_ ...) (let #`(... #,@var{exp} ...))))
  4807. @end example
  4808. and instead of
  4809. @example
  4810. (defmacro (@var{name} ... @var{var} ...) `(... @var{var} ...))
  4811. @end example
  4812. you should probably do:
  4813. @example
  4814. (define-syntax-case @var{name} ()
  4815. ((_ ... @var{var} ...) #`(... @var{var} ...))
  4816. @end example
  4817. Defines an old-style macro a la Common Lisp,
  4818. and installs @code{(lambda @var{lambda-list} @var{form} ...)}
  4819. as the expansion function for @var{name}.
  4820. When the translator sees an application of @var{name},
  4821. the expansion function is called with the rest of the application
  4822. as the actual arguments. The resulting object must be a Scheme
  4823. source form that is futher processed (it may be repeatedly macro-expanded).
  4824. @end deffn
  4825. @deffn Procedure gentemp
  4826. Returns a new (interned) symbol each time it is called.
  4827. The symbol names are implementation-dependent.
  4828. (This is not directly macro-related, but is often used in conjunction
  4829. with @code{defmacro} to get a fresh unique identifier.)
  4830. @end deffn
  4831. @deffn Procedure expand form
  4832. The result of evaluating @var{form} is treated as a Scheme expression,
  4833. syntax-expanded to internal form, and then converted back to (roughly)
  4834. the equivalent expanded Scheme form.
  4835. This can be useful for debugging macros.
  4836. To access this function, you must first @code{(require 'syntax-utils)}.
  4837. @example
  4838. (require 'syntax-utils)
  4839. (expand '(cond ((> x y) 0) (else 1))) @result{} (if (> x y) 0 1)
  4840. @end example
  4841. @end deffn
  4842. @subsection Pattern language
  4843. A @meta{transformer-spec} is an expression that evaluates to a
  4844. transformer procedure, which takes an input form and returns a
  4845. resulting form. You can do general macro-time compilation with such a
  4846. procedure, commonly using @code{syntax-case} (which is documented
  4847. in the R6RS library specification).
  4848. However, when possible it is better to use the simpler
  4849. pattern language of @code{syntax-rules}:
  4850. @display
  4851. @stxdef{transformer-spec}
  4852. @stxlit{(syntax-rules (} @arbno{@stxref{tr-literal}} @stxlit{)} @arbno{@stxref{syntax-rule}}@stxlit{)}
  4853. | @stxlit{(syntax-rules} @stxref{ellipsis} @stxlit{(} @arbno{@stxref{tr-literal}} @stxlit{)} @arbno{@stxref{syntax-rule}}@stxlit{)}
  4854. | @stxref{expression}
  4855. @stxdef{syntax-rule} @stxlit{(}@stxref{list-pattern} @stxref{syntax-template}@stxlit{)}
  4856. @stxdef{tr-literal} @stxref{identifier}
  4857. @stxdef{ellipsis} @stxref{identifier}
  4858. @end display
  4859. An instance of @code{syntax-rules} produces a new
  4860. macro transformer by specifying a sequence of hygienic
  4861. rewrite rules. A use of a macro whose keyword is associated
  4862. with a transformer specified by @code{syntax-rules} is matched
  4863. against the patterns contained in the @meta{syntax-rule}s
  4864. beginning with the leftmost syntax rule . When a match is
  4865. found, the macro use is transcribed hygienically according
  4866. to the template.
  4867. The optional @meta{ellipsis} species a symbol used to indicate
  4868. repetition; it defaults to @code{...} (3 periods).
  4869. @display
  4870. @stxdef{syntax-pattern}
  4871. @stxref{identifier} | @stxref{constant} | @stxref{list-pattern} | @stxref{vector-pattern}
  4872. @stxdef{list-pattern} @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  4873. | @stxlit{(} @stxref{syntax-pattern} @arbno{@stxref{syntax-pattern}} @stxlit{.} @stxref{syntax-pattern} @stxlit{)}
  4874. | @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  4875. | @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{.} @stxref{syntax-pattern}@stxlit{)}
  4876. @stxdef{vector-pattern} @stxlit{#(} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  4877. | @stxlit{#(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  4878. @end display
  4879. An identifier appearing within a pattern can be an underscore
  4880. (@code{_}), a literal identifier listed in the list of @meta{tr-literal}s,
  4881. or the @meta{ellipsis}. All other identifiers appearing within a
  4882. pattern are pattern variables.
  4883. The outer @var{syntax-list} of the pattern in a @meta{syntax-rule}
  4884. must start with an identifier. It is not involved in the matching and
  4885. is considered neither a pattern variable nor a literal identifier.
  4886. Pattern variables match arbitrary input elements and are
  4887. used to refer to elements of the input in the template.
  4888. It is an error for the same pattern variable to appear more
  4889. than once in a @meta{syntax-pattern}.
  4890. Underscores also match arbitrary input elements but are
  4891. not pattern variables and so cannot be used to refer to
  4892. those elements. If an underscore appears in the literals
  4893. list, then that takes precedence and underscores in the
  4894. pattern match as literals. Multiple underscores can
  4895. appear in a @meta{syntax-pattern}.
  4896. Identifiers that appear in @code{(@arbno{@meta{tr-literal}})} are interpreted
  4897. as literal identifiers to be matched against corresponding
  4898. elements of the input. An element in the input matches a
  4899. literal identifier if and only if it is an identifier and either
  4900. both its occurrence in the macro expression and its occurrence
  4901. in the macro definition have the same lexical binding,
  4902. or the two identifiers are the same and both have no lexical
  4903. binding.
  4904. A subpattern followed by ellipsis can match zero or
  4905. more elements of the input, unless ellipsis appears in the
  4906. literals, in which case it is matched as a literal.
  4907. More formally, an input expression @var{E} matches a pattern @var{P}
  4908. if and only if:
  4909. @itemize @bullet
  4910. @item
  4911. @var{P} is an underscore (@stxlit{_}); or
  4912. @item
  4913. @var{P} is a non-literal identifier; or
  4914. @item
  4915. @var{P} is a literal identifier and @var{E} is an identifier with the
  4916. same binding; or
  4917. @item
  4918. @var{P} is a list @stxlit{(}@var{P@sub{1}} ... @var{P@sub{n}}@stxlit{)} and
  4919. @var{E} is a list of @var{n} elements
  4920. that match @var{P@sub{1}} through @var{P@sub{n}}, respectively; or
  4921. @item
  4922. @var{P} is an improper list
  4923. @stxlit{(}@var{P@sub{1}} ... @var{P@sub{n}} @stxlit{.} @var{P@sub{n+1}}@stxlit{)} and
  4924. @var{E} is a list or improper list of @var{n} or more elements that
  4925. match @var{P@sub{1}} through @var{P@sub{n}}, respectively,
  4926. and whose @var{n}th tail matches @var{P@sub{n+1}}; or
  4927. @item
  4928. @var{P} is of the form
  4929. @stxlit{(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}}@stxlit{)} where @var{E} is a proper list of @var{n} elements,
  4930. the first @var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
  4931. respectively, whose
  4932. next @var{n-k-l} elements each match @var{P@sub{e}}, and whose remaining
  4933. @var{l} elements match @var{P@sub{k+1}} through @var{P@sub{k+l}}; or
  4934. @item
  4935. @var{P} is of the form
  4936. @stxlit{(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}} @stxlit{.} @var{P@sub{x}}@stxlit{)}
  4937. where @var{E} is a list or improper list of @var{n} elements,
  4938. the first @var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
  4939. whose next @var{n-k-l} elements each match @var{P@sub{e}}, and whose
  4940. remaining @var{l} elements match @var{P@sub{k+1}} through @var{P@sub{k+l}},
  4941. and whose @var{n}th and final @code{cdr} matches @var{P@sub{x}}; or
  4942. @item
  4943. @var{P} is a vector of the form
  4944. @stxlit{#(}@var{P@sub{1}} ... @var{P@sub{n}}@stxlit{)} and @var{E} is a
  4945. vector of @var{n} elements that match @var{P@sub{1}} through @var{P@sub{n}}; or
  4946. @item
  4947. @var{P} is of the form
  4948. @stxlit{#(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}}@stxlit{)}
  4949. where @var{E} is a vector of @var{n} elements the first
  4950. @var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
  4951. whose next @var{n-k-l} elements each match @var{P@sub{e}},
  4952. and whose remaining @var{l} elements match @var{P@sub{k+1}}
  4953. through @var{P@sub{k+l}}; or
  4954. @item
  4955. @var{P} is a constant and E is equal to @var{P} in the sense of the
  4956. @code{equal?} procedure.
  4957. @end itemize
  4958. It is an error to use a macro keyword, within the scope of
  4959. its binding, in an expression that does not match any of
  4960. the patterns.
  4961. @display
  4962. @stxdef{syntax-template} @stxref{identifier} | @stxref{constant}
  4963. | @stxlit{(}@arbno{@stxref{template-element}}@stxlit{)}
  4964. | @stxlit{(}@stxref{template-element} @arbno{@stxref{template-element}} @stxlit{.} @stxref{syntax-template} @stxlit{)}
  4965. | @stxlit{(} @stxref{ellipsis} @stxref{syntax-template}@stxlit{)}
  4966. @stxdef{template-element} @stxref{syntax-template} [@stxref{ellipsis}]
  4967. @end display
  4968. When a macro use is transcribed according to the template
  4969. of the matching @meta{syntax-rule}, pattern variables that occur
  4970. in the template are replaced by the elements they match in
  4971. the input. Pattern variables that occur in subpatterns followed
  4972. by one or more instances of the identifier @meta{ellipsis} are
  4973. allowed only in subtemplates that are followed by as many
  4974. instances of @meta{ellipsis} . They are replaced in the output by
  4975. all of the elements they match in the input, distributed as
  4976. indicated. It is an error if the output cannot be built up
  4977. as specified.
  4978. Identifiers that appear in the template but are not pattern
  4979. variables or the identifier @meta{ellipsis} are inserted into the output
  4980. as literal identifiers. If a literal identifier is inserted as a
  4981. free identifier then it refers to the binding of that identifier
  4982. within whose scope the instance of @code{syntax-rules} appears.
  4983. If a literal identifier is inserted as a bound identifier then
  4984. it is in effect renamed to prevent inadvertent captures of
  4985. free identifiers.
  4986. A template of the
  4987. form @stxlit{(}@meta{ellipsis} @meta{template}@stxlit{)} is
  4988. identical to @meta{template}, except that @meta{ellipses}
  4989. within the template have no special meaning.
  4990. That is, any @meta{ellipses} contained within
  4991. @meta{template} are treated as ordinary identifiers. In particular,
  4992. the template @stxlit{(}@meta{ellipsis} @meta{ellipsis}@stxlit{)}
  4993. produces a single @meta{ellipsis}. This allows syntactic
  4994. abstractions to expand into code containing ellipses.
  4995. @example
  4996. (define-syntax be-like-begin
  4997. (syntax-rules ()
  4998. ((be-like-begin name)
  4999. (define-syntax name
  5000. (syntax-rules ()
  5001. ((name expr (... ...))
  5002. (begin expr (... ...))))))))
  5003. (be-like-begin sequence)
  5004. (sequence 1 2 3 4) @result{} 4
  5005. @end example
  5006. @subsection Identifier predicates
  5007. @deffn Procedure {identifier?} @var{obj}
  5008. Return @true{} if @var{obj} is an identifier, i.e., a syntax object
  5009. representing an identifier, and @false{} otherwise.
  5010. The @func{identifier?} procedure is often used within a fender to verify
  5011. that certain subforms of an input form are identifiers, as in the
  5012. definition of @code{rec}, which creates self--contained recursive
  5013. objects, below.
  5014. @example
  5015. (define-syntax rec
  5016. (lambda (x)
  5017. (syntax-case x ()
  5018. ((_ x e)
  5019. (identifier? #'x)
  5020. #'(letrec ((x e)) x)))))
  5021. (map (rec fact
  5022. (lambda (n)
  5023. (if (= n 0)
  5024. 1
  5025. (* n (fact (- n 1))))))
  5026. '(1 2 3 4 5)) @result{} (1 2 6 24 120)
  5027. (rec 5 (lambda (x) x)) @result{} exception
  5028. @end example
  5029. @end deffn
  5030. The procedures @func{bound-identifier=?} and @func{free-identifier=?}
  5031. each take two identifier arguments and return @true{} if their arguments
  5032. are equivalent and @false{} otherwise. These predicates are used to
  5033. compare identifiers according to their @emph{intended use} as free
  5034. references or bound identifiers in a given context.
  5035. @deffn Procedure {bound-identifier=?} @vari{id} @varii{id}
  5036. @vari{id} and @varii{id} must be identifiers.
  5037. The procedure @func{bound-identifier=?} returns @true{} if a binding for
  5038. one would capture a reference to the other in the output of the
  5039. transformer, assuming that the reference appears within the scope of the
  5040. binding, and @false{} otherwise.
  5041. In general, two identifiers are @func{bound-identifier=?} only if both
  5042. are present in the original program or both are introduced by the same
  5043. transformer application (perhaps implicitly, see @func{datum->syntax}).
  5044. The @func{bound-identifier=?} procedure can be used for detecting
  5045. duplicate identifiers in a binding construct or for other preprocessing
  5046. of a binding construct that requires detecting instances of the bound
  5047. identifiers.
  5048. @end deffn
  5049. @deffn Procedure {free-identifier=?} @vari{id} @varii{id}
  5050. @vari{id} and @varii{id} must be identifiers.
  5051. The @func{free-identifier=?} procedure returns @true{} if and only if
  5052. the two identifiers would resolve to the same binding if both were to
  5053. appear in the output of a transformer outside of any bindings inserted
  5054. by the transformer. (If neither of two like--named identifiers resolves
  5055. to a binding, i.e., both are unbound, they are considered to resolve to
  5056. the same binding.)
  5057. Operationally, two identifiers are considered equivalent by
  5058. @func{free-identifier=?} if and only the topmost matching substitution
  5059. for each maps to the same binding or the identifiers have the same name
  5060. and no matching substitution.
  5061. The @func{syntax-case} and @func{syntax-rules} forms internally use
  5062. @func{free-identifier=?} to compare identifiers listed in the literals
  5063. list against input identifiers.
  5064. @example
  5065. (let ((fred 17))
  5066. (define-syntax a
  5067. (lambda (x)
  5068. (syntax-case x ()
  5069. ((_ id) #'(b id fred)))))
  5070. (define-syntax b
  5071. (lambda (x)
  5072. (syntax-case x ()
  5073. ((_ id1 id2)
  5074. #`(list
  5075. #,(free-identifier=? #'id1 #'id2)
  5076. #,(bound-identifier=? #'id1 #'id2))))))
  5077. (a fred))
  5078. @result{} (#t #f)
  5079. @end example
  5080. The following definition of unnamed @func{let} uses
  5081. @func{bound-identifier=?} to detect duplicate identifiers.
  5082. @example
  5083. (define-syntax let
  5084. (lambda (x)
  5085. (define unique-ids?
  5086. (lambda (ls)
  5087. (or (null? ls)
  5088. (and (let notmem? ((x (car ls)) (ls (cdr ls)))
  5089. (or (null? ls)
  5090. (and (not (bound-identifier=? x (car ls)))
  5091. (notmem? x (cdr ls)))))
  5092. (unique-ids? (cdr ls))))))
  5093. (syntax-case x ()
  5094. ((_ ((i v) ...) e1 e2 ...)
  5095. (unique-ids? #'(i ...))
  5096. #'((lambda (i ...) e1 e2 ...) v ...)))))
  5097. @end example
  5098. The argument @code{#'(i ...)} to @func{unique-ids?} is guaranteed to be
  5099. a list by the rules given in the description of @func{syntax} above.
  5100. With this definition of @func{let}:
  5101. @example
  5102. (let ((a 3) (a 4)) (+ a a)) @result{} @i{syntax error}
  5103. @end example
  5104. However,
  5105. @example
  5106. (let-syntax
  5107. ((dolet (lambda (x)
  5108. (syntax-case x ()
  5109. ((_ b)
  5110. #'(let ((a 3) (b 4)) (+ a b)))))))
  5111. (dolet a))
  5112. @result{} 7
  5113. @end example
  5114. @noindent
  5115. since the identifier @code{a} introduced by @func{dolet} and the
  5116. identifier @code{a} extracted from the input form are not
  5117. @func{bound-identifier=?}.
  5118. Rather than including @code{else} in the literals list as before, this
  5119. version of @func{case} explicitly tests for @code{else} using
  5120. @func{free-identifier=?}.
  5121. @example
  5122. (define-syntax case
  5123. (lambda (x)
  5124. (syntax-case x ()
  5125. ((_ e0 ((k ...) e1 e2 ...) ...
  5126. (else-key else-e1 else-e2 ...))
  5127. (and (identifier? #'else-key)
  5128. (free-identifier=? #'else-key #'else))
  5129. #'(let ((t e0))
  5130. (cond
  5131. ((memv t '(k ...)) e1 e2 ...)
  5132. ...
  5133. (else else-e1 else-e2 ...))))
  5134. ((_ e0 ((ka ...) e1a e2a ...)
  5135. ((kb ...) e1b e2b ...) ...)
  5136. #'(let ((t e0))
  5137. (cond
  5138. ((memv t '(ka ...)) e1a e2a ...)
  5139. ((memv t '(kb ...)) e1b e2b ...)
  5140. ...))))))
  5141. @end example
  5142. With either definition of @func{case}, @code{else} is not recognized as
  5143. an auxiliary keyword if an enclosing lexical binding for @code{else}
  5144. exists. For example,
  5145. @example
  5146. (let ((else @false{}))
  5147. (case 0 (else (write "oops")))) @result{} @i{syntax error}
  5148. @end example
  5149. @noindent
  5150. since @code{else} is bound lexically and is therefore not the same
  5151. @code{else} that appears in the definition of @func{case}.
  5152. @end deffn
  5153. @subsection Syntax-object and datum conversions
  5154. @deffn Procedure {syntax->datum} @var{syntax-object}
  5155. @deffnx {Deprecated procedure} {syntax-object->datum} @var{syntax-object}
  5156. Strip all syntactic information from a syntax object and returns the
  5157. corresponding Scheme datum.
  5158. Identifiers stripped in this manner are converted to their symbolic
  5159. names, which can then be compared with @func{eq?}. Thus, a predicate
  5160. @code{symbolic-identifier=?} might be defined as follows.
  5161. @example
  5162. (define symbolic-identifier=?
  5163. (lambda (x y)
  5164. (eq? (syntax->datum x)
  5165. (syntax->datum y))))
  5166. @end example
  5167. @end deffn
  5168. @deffn Procedure {datum->syntax} @var{template-id} @var{datum} [@var{srcloc}]
  5169. @deffnx {Deprecated procedure} {datum->syntax-object} @var{template-id} @var{datum}
  5170. @var{template-id} must be a template identifier and @var{datum} should
  5171. be a datum value.
  5172. The @func{datum->syntax} procedure returns a syntax-object
  5173. representation of @var{datum} that contains the same contextual
  5174. information as @var{template-id}, with the effect that the syntax object
  5175. behaves as if it were introduced into the code when @var{template-id}
  5176. was introduced.
  5177. If @var{srcloc} is specified (and neither @code{#f} or @code{#!null}),
  5178. it specifies the file position (including line number) for the result.
  5179. In that case it should be a syntax object representing
  5180. a list; otherwise it is currently ignored, though future extensions
  5181. may support other ways of specifying the position.
  5182. The @func{datum->syntax} procedure allows a transformer to ``bend''
  5183. lexical scoping rules by creating @emph{implicit identifiers} that
  5184. behave as if they were present in the input form, thus permitting the
  5185. definition of macros that introduce visible bindings for or references
  5186. to identifiers that do not appear explicitly in the input form. For
  5187. example, the following defines a @func{loop} expression that uses this
  5188. controlled form of identifier capture to bind the variable @code{break}
  5189. to an escape procedure within the loop body. (The derived
  5190. @func{with-syntax} form is like @func{let} but binds pattern variables.)
  5191. @example
  5192. (define-syntax loop
  5193. (lambda (x)
  5194. (syntax-case x ()
  5195. ((k e ...)
  5196. (with-syntax
  5197. ((break (datum->syntax #'k 'break)))
  5198. #'(call-with-current-continuation
  5199. (lambda (break)
  5200. (let f () e ... (f)))))))))
  5201. (let ((n 3) (ls '()))
  5202. (loop
  5203. (if (= n 0) (break ls))
  5204. (set! ls (cons 'a ls))
  5205. (set! n (- n 1))))
  5206. @result{} (a a a)
  5207. @end example
  5208. Were @code{loop} to be defined as:
  5209. @example
  5210. (define-syntax loop
  5211. (lambda (x)
  5212. (syntax-case x ()
  5213. ((_ e ...)
  5214. #'(call-with-current-continuation
  5215. (lambda (break)
  5216. (let f () e ... (f))))))))
  5217. @end example
  5218. @noindent
  5219. the variable @code{break} would not be visible in @code{e ...}.
  5220. The datum argument @var{datum} may also represent an arbitrary Scheme
  5221. form, as demonstrated by the following definition of @func{include}.
  5222. @example
  5223. (define-syntax include
  5224. (lambda (x)
  5225. (define read-file
  5226. (lambda (fn k)
  5227. (let ((p (open-file-input-port fn)))
  5228. (let f ((x (get-datum p)))
  5229. (if (eof-object? x)
  5230. (begin (close-port p) '())
  5231. (cons (datum->syntax k x)
  5232. (f (get-datum p))))))))
  5233. (syntax-case x ()
  5234. ((k filename)
  5235. (let ((fn (syntax->datum #'filename)))
  5236. (with-syntax (((exp ...)
  5237. (read-file fn #'k)))
  5238. #'(begin exp ...)))))))
  5239. @end example
  5240. @code{(include "filename")} expands into a @func{begin} expression
  5241. containing the forms found in the file named by @code{"filename"}. For
  5242. example, if the file @file{flib.ss} contains:
  5243. @example
  5244. (define f (lambda (x) (g (* x x))))
  5245. @end example
  5246. @noindent
  5247. and the file @file{glib.ss} contains:
  5248. @example
  5249. (define g (lambda (x) (+ x x)))
  5250. @end example
  5251. @noindent
  5252. the expression:
  5253. @example
  5254. (let ()
  5255. (include "flib.ss")
  5256. (include "glib.ss")
  5257. (f 5))
  5258. @end example
  5259. @noindent
  5260. evaluates to @code{50}.
  5261. The definition of @func{include} uses @func{datum->syntax} to convert
  5262. the objects read from the file into syntax objects in the proper lexical
  5263. context, so that identifier references and definitions within those
  5264. expressions are scoped where the @func{include} form appears.
  5265. Using @func{datum->syntax}, it is even possible to break hygiene
  5266. entirely and write macros in the style of old Lisp macros. The
  5267. @func{lisp-transformer} procedure defined below creates a transformer
  5268. that converts its input into a datum, calls the programmer's procedure
  5269. on this datum, and converts the result back into a syntax object scoped
  5270. where the original macro use appeared.
  5271. @example
  5272. (define lisp-transformer
  5273. (lambda (p)
  5274. (lambda (x)
  5275. (syntax-case x ()
  5276. ((kwd . rest)
  5277. (datum->syntax #'kwd
  5278. (p (syntax->datum x))))))))
  5279. @end example
  5280. @end deffn
  5281. @subsection Signaling errors in macro transformers
  5282. @deffn Syntax syntax-error message @arbno{args}
  5283. The @meta{message} and @meta{args} are treated similary as for
  5284. the @code{error} procedure. However, the error is reported
  5285. when the @code{syntax-error} is expanded.
  5286. This can be used as a @code{syntax-rules}
  5287. template for a pattern that is an invalid use of the
  5288. macro, which can provide more descriptive error messages.
  5289. The @meta{message} should be a string literal, and the @var{args}
  5290. arbitrary (non-evalualted) expressions providing additional information.
  5291. @example
  5292. (define-syntax simple-let
  5293. (syntax-rules ()
  5294. ((_ (head ... ((x . y) val) . tail)
  5295. body1 body2 ...)
  5296. (syntax-error "expected an identifier but got" (x . y)))
  5297. ((_ ((name val) ...) body1 body2 ...)
  5298. ((lambda (name ...) body1 body2 ...)
  5299. val ...))))
  5300. @end example
  5301. @end deffn
  5302. @deffn Procedure report-syntax-error location message
  5303. This is a procedure that can be called at macro-expansion time
  5304. by a syntax transformer function.
  5305. (In contrast @code{syntax-error} is a syntax form used in the
  5306. expansion result.)
  5307. The @var{message} is reported as a compile-time error message.
  5308. The @var{location} is used for the source location (file name and
  5309. line/column numbers): In general it can be a @code{SourceLocator} value;
  5310. most commonly it is a syntax object for a sub-list of the input form
  5311. that is erroneous.
  5312. The value returned by @code{report-syntax-error} is an
  5313. instance of @code{ErrorExp}, which supresses further compilation.
  5314. @example
  5315. (define-syntax if
  5316. (lambda (x)
  5317. (syntax-case x ()
  5318. ((_ test then)
  5319. (make-if-exp #'test #'then #!null))
  5320. ((_ test then else)
  5321. (make-if-exp #'test #'then #'else))
  5322. ((_ e1 e2 e3 . rest)
  5323. (report-syntax-error #'rest
  5324. "too many expressions for 'if'"))
  5325. ((_ . rest)
  5326. (report-syntax-error #'rest
  5327. "too few expressions for 'if'")))))
  5328. @end example
  5329. In the above example, one could use the source form @code{x} for the
  5330. location, but using @code{#'rest} is more accurate. Note that the following
  5331. is incorrect, because @code{e1} might not be a pair, in which case
  5332. we don't have location information for it (due to a Kawa limitation):
  5333. @example
  5334. (syntax-case x ()
  5335. ...
  5336. ((_ e1)
  5337. (report-syntax-error
  5338. #'e1 ;; @i{poor location specifier}
  5339. "too few expressions for 'if'")))))
  5340. @end example
  5341. @end deffn
  5342. @subsection Convenience forms
  5343. @deffn Syntax with-syntax ((@var{pattern} @stxref{expression}) @dots{}) @stxref{body}
  5344. The @func{with-syntax} form is used to bind pattern variables, just as
  5345. @func{let} is used to bind variables. This allows a transformer to
  5346. construct its output in separate pieces, then put the pieces together.
  5347. Each @var{pattern} is identical in form to a @func{syntax-case}
  5348. pattern. The value of each @var{expression} is computed and
  5349. destructured according to the corresponding @var{pattern}, and pattern
  5350. variables within the @var{pattern} are bound as with
  5351. @func{syntax-case} to the corresponding portions of the value within
  5352. @var{body}.
  5353. The @func{with-syntax} form may be defined in terms of
  5354. @func{syntax-case} as follows.
  5355. @example
  5356. (define-syntax with-syntax
  5357. (lambda (x)
  5358. (syntax-case x ()
  5359. ((_ ((p e0) ...) e1 e2 ...)
  5360. (syntax (syntax-case (list e0 ...) ()
  5361. ((p ...) (let () e1 e2 ...))))))))
  5362. @end example
  5363. The following definition of @func{cond} demonstrates the use of
  5364. @func{with-syntax} to support transformers that employ recursion
  5365. internally to construct their output. It handles all @func{cond} clause
  5366. variations and takes care to produce one-armed @func{if} expressions
  5367. where appropriate.
  5368. @example
  5369. (define-syntax cond
  5370. (lambda (x)
  5371. (syntax-case x ()
  5372. ((_ c1 c2 ...)
  5373. (let f ((c1 #'c1) (c2* #'(c2 ...)))
  5374. (syntax-case c2* ()
  5375. (()
  5376. (syntax-case c1 (else =>)
  5377. (((else e1 e2 ...) #'(begin e1 e2 ...))
  5378. ((e0) #'e0)
  5379. ((e0 => e1)
  5380. #'(let ((t e0)) (if t (e1 t))))
  5381. ((e0 e1 e2 ...)
  5382. #'(if e0 (begin e1 e2 ...)))))
  5383. ((c2 c3 ...)
  5384. (with-syntax ((rest (f #'c2 #'(c3 ...))))
  5385. (syntax-case c1 (=>)
  5386. ((e0) #'(let ((t e0)) (if t t rest)))
  5387. ((e0 => e1)
  5388. #'(let ((t e0)) (if t (e1 t) rest)))
  5389. ((e0 e1 e2 ...)
  5390. #'(if e0
  5391. (begin e1 e2 ...)
  5392. rest)))))))))))
  5393. @end example
  5394. @end deffn
  5395. @deffn Syntax quasisyntax @var{template}
  5396. @deffnx {Auxiliary Syntax} unsyntax
  5397. @deffnx {Auxiliary Syntax} unsyntax-splicing
  5398. The @func{quasisyntax} form is similar to @func{syntax}, but it allows
  5399. parts of the quoted text to be evaluated, in a manner similar to the
  5400. operation of @func{quasiquote}.
  5401. Within a @func{quasisyntax} @var{template}, subforms of @func{unsyntax}
  5402. and @func{unsyntax-splicing} forms are evaluated, and everything else is
  5403. treated as ordinary template material, as with @func{syntax}.
  5404. The value of each @func{unsyntax} subform is inserted into the output in
  5405. place of the @func{unsyntax} form, while the value of each
  5406. @func{unsyntax-splicing} subform is spliced into the surrounding list or
  5407. vector structure. Uses of @func{unsyntax} and @func{unsyntax-splicing}
  5408. are valid only within @func{quasisyntax} expressions.
  5409. A @func{quasisyntax} expression may be nested, with each
  5410. @func{quasisyntax} introducing a new level of syntax quotation and each
  5411. @func{unsyntax} or @func{unsyntax-splicing} taking away a level of
  5412. quotation. An expression nested within @emph{n} @func{quasisyntax}
  5413. expressions must be within @emph{n} @emph{unsyntax} or
  5414. @func{unsyntax-splicing} expressions to be evaluated.
  5415. As noted in @stxref{abbreviation}, @code{#`@var{template}} is equivalent to
  5416. @code{(quasisyntax @var{template})}, @code{#,@var{template}} is
  5417. equivalent to @code{(unsyntax @var{template})}, and
  5418. @code{#,@@@var{template}} is equivalent to @code{(unsyntax-splicing
  5419. @var{template})}. @emph{Note} that for backwards compatibility,
  5420. you should only use @code{#,@var{template}} inside a literal @code{#`@var{template}} form.
  5421. The @func{quasisyntax} keyword can be used in place of
  5422. @func{with-syntax} in many cases. For example, the definition of
  5423. @func{case} shown under the description of @func{with-syntax} above can
  5424. be rewritten using @func{quasisyntax} as follows.
  5425. @example
  5426. (define-syntax case
  5427. (lambda (x)
  5428. (syntax-case x ()
  5429. ((_ e c1 c2 ...)
  5430. #`(let ((t e))
  5431. #,(let f ((c1 #'c1) (cmore #'(c2 ...)))
  5432. (if (null? cmore)
  5433. (syntax-case c1 (else)
  5434. ((else e1 e2 ...)
  5435. #'(begin e1 e2 ...))
  5436. (((k ...) e1 e2 ...)
  5437. #'(if (memv t '(k ...))
  5438. (begin e1 e2 ...))])
  5439. (syntax-case c1 ()
  5440. (((k ...) e1 e2 ...)
  5441. #`(if (memv t '(k ...))
  5442. (begin e1 e2 ...)
  5443. #,(f (car cmore)
  5444. (cdr cmore))))))))))))
  5445. @end example
  5446. @c ((Unknown if this works))
  5447. @c Uses of @func{unsyntax} and @func{unsyntax-splicing} with zero or more
  5448. @c than one subform are valid only in splicing (list or vector) contexts.
  5449. @c @code{(unsyntax @var{template} @dots{})} is equivalent to
  5450. @c @code{(unsyntax @var{template}) ...}, and @code{(unsyntax-splicing
  5451. @c @var{template} ...)} is equivalent to @code{(unsyntax-splicing
  5452. @c @var{template}) ...}. These forms are primarily useful as intermediate
  5453. @c forms in the output of the @func{quasisyntax} expander.
  5454. @c
  5455. @c @quotation
  5456. @c @emph{Note:} Uses of @func{unsyntax} and @func{unsyntax-splicing} with
  5457. @c zero or more than one subform enable certain idioms, such as
  5458. @c @code{#,@@#,@@}, which has the effect of a doubly indirect splicing when
  5459. @c used within a doubly nested and doubly evaluated @func{quasisyntax}
  5460. @c expression.
  5461. @c @end quotation
  5462. @end deffn
  5463. @quotation
  5464. @emph{Note:} Any @func{syntax-rules} form can be expressed with
  5465. @func{syntax-case} by making the @func{lambda} expression and
  5466. @func{syntax} expressions explicit, and @func{syntax-rules} may be
  5467. defined in terms of @func{syntax-case} as follows.
  5468. @example
  5469. (define-syntax syntax-rules
  5470. (lambda (x)
  5471. (syntax-case x ()
  5472. ((_ (lit ...) ((k . p) t) ...)
  5473. (for-all identifier? #'(lit ... k ...))
  5474. #'(lambda (x)
  5475. (syntax-case x (lit ...)
  5476. ((_ . p) #'t) ...))))))
  5477. @end example
  5478. @end quotation
  5479. @node Named quasi-literals
  5480. @section Named quasi-literals
  5481. Traditional Scheme has only a few kinds of values,
  5482. and thus only a few builtin kinds of literals.
  5483. Modern Scheme allows defining new types,
  5484. so it is desirable to have a mechanism for defining literal values
  5485. for the new types.
  5486. Consider the @code{@ref{URI-type,,URI}} type.
  5487. You can create a new instance of a @code{URI} using a
  5488. constructor function:
  5489. @example
  5490. (URI "http://example.com/")
  5491. @end example
  5492. This isn't too bad, though the double-quote characters are an ugly distraction.
  5493. However, if you need to construct the string it gets messy:
  5494. @example
  5495. (URI (string-append base-uri "icon.png"))
  5496. @end example
  5497. Instead use can write:
  5498. @example
  5499. &URI@{http://example.com/@}
  5500. @end example
  5501. or:
  5502. @example
  5503. &URI@{&[base-uri]icon.png@}
  5504. @end example
  5505. This syntax is translated by the Scheme reader
  5506. to the more familiar but more verbose equivalent forms:
  5507. @example
  5508. ($construct$:URI "http://example.com/")
  5509. ($construct$:URI $<<$ base-uri $>>$ "icon.png")
  5510. @end example
  5511. So for this to work there just needs to be a definition
  5512. of @code{$construct$:URI}, usually a macro.
  5513. Normal scope rules apply; typically you'd define @code{$construct$:URI} in
  5514. a module.
  5515. The names @code{$<<$} and @code{$>>$} are bound to unique zero-length strings.
  5516. They are used to allow the implementation of @code{$construct$:URI}
  5517. to determine which arguments are literal and which come from
  5518. escaped expressions.
  5519. If you want to define your own @code{$construct$:@var{tag}},
  5520. or to read motivation and details, see the
  5521. @uref{http://srfi.schemers.org/srfi-108/srfi-108.html, SRFI 108} specification.
  5522. @display
  5523. @stxdef{extended-datum-literal}
  5524. @stxlit{&} @stxref{cname} @stxlit{@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
  5525. | @stxlit{&} @stxref{cname} @stxlit{[} @arbno{@stxref{expression}} @stxlit{]@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
  5526. @stxdef{cname} @stxref{identifier}
  5527. @stxdef{named-literal-part}
  5528. @i{any character except} @stxlit{&}@i{,} @stxlit{@lbracechar{}} @i{or} @stxlit{@rbracechar{}}
  5529. | @stxlit{@lbracechar{}} @atleastone{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
  5530. | @stxref{char-ref}
  5531. | @stxref{entity-ref}
  5532. | @stxref{special-escape}
  5533. | @stxref{enclosed-part}
  5534. | @stxref{extended-datum-literal}
  5535. @end display
  5536. @c FIXME May rename: Control structure
  5537. @node Program structure
  5538. @chapter Program structure
  5539. See @ref{program units} for some notes on
  5540. structure of an entire source file.
  5541. @menu
  5542. * Boolean values::
  5543. * Conditionals::
  5544. * Variables and Patterns::
  5545. * Definitions::
  5546. * Local binding constructs::
  5547. * Lazy evaluation::
  5548. * Repeat forms:: Repeat patterns and expressions
  5549. * Threads::
  5550. * Exceptions:: Exception handling
  5551. @end menu
  5552. @node Boolean values
  5553. @section Boolean values
  5554. The standard boolean objects for true and false are written as @code{#t} and @code{#f}.
  5555. Alternatively, they may be written @code{#true} and @code{#false},
  5556. respectively.
  5557. @display
  5558. @stxdef{boolean} @stxlit{#t} | @stxlit{#f} | @stxlit{#true} | @stxlit{#false}
  5559. @end display
  5560. @display
  5561. @stxdef{test-expression} @stxref{expression}
  5562. @end display
  5563. What really matters,
  5564. though, are the objects that the Scheme conditional expressions (@code{if},
  5565. @code{cond}, @code{and}, @code{or}, @code{when}, @code{unless}, @code{do})
  5566. treat as true or
  5567. false. The phrase ``a true value'' (or sometimes just ``true'')
  5568. means any object treated as true by the conditional expressions, and the phrase ``a false value'' (or ``false'') means any
  5569. object treated as false by the conditional expressions.
  5570. In this document, @var{test-expression} is an expression that is evaluated,
  5571. but we only care about whether the result is a true or a false value.
  5572. Of all the standard Scheme values, only @code{#f} counts as false in
  5573. conditional expressions. All other Scheme values, including @code{#t},
  5574. count as true. A @var{test-expression} is an expression evaluated
  5575. in this manner for whether it is true or false.
  5576. In addition the null value @code{#!null} (in Java written as @code{null})
  5577. is also considered false. Also, if you for some strange reason create a
  5578. fresh @code{java.lang.Boolean} object whose @code{booleanValue()}
  5579. returns @code{false}, that is also considered false.
  5580. @emph{Note:} Unlike some other dialects of Lisp, Scheme distinguishes
  5581. @code{#f} and the empty list from each other and from the symbol
  5582. @code{nil}.
  5583. Boolean constants evaluate to themselves, so they do not
  5584. need to be quoted in programs.
  5585. @example
  5586. #t @result{} #t
  5587. #true @result{} #t
  5588. #f @result{} #f
  5589. #false @result{} #f
  5590. '#f @result{} #f
  5591. @end example
  5592. @deffn Type boolean
  5593. The type of boolean values.
  5594. As a type conversion, a true value is converted to @code{#t},
  5595. while a false value is converted to @code{#f}.
  5596. Represented as a primitive Java @code{boolean}
  5597. or @code{kawa.lang.Boolean} when converted to an object.
  5598. @end deffn
  5599. @deffn Procedure boolean? obj
  5600. The @code{boolean?} predicate returns @code{#t} if @var{obj}
  5601. is either @code{#t} or @code{#f}, and returns @code{#f} otherwise.
  5602. @example
  5603. (boolean? #f) @result{} #t
  5604. (boolean? 0) @result{} #f
  5605. (boolean? '()) @result{} #f
  5606. @end example
  5607. @end deffn
  5608. @deffn Procedure boolean=? boolean1 boolean2 boolean3 ...
  5609. Returns @code{#t} if all the arguments are booleans and all are @code{#t}
  5610. or all are @code{#f}.
  5611. @end deffn
  5612. @node Conditionals
  5613. @section Conditionals
  5614. Kawa Scheme has the usual conditional expression forms,
  5615. such as @code{if}, @code{case}, @code{and}, and @code{or}:
  5616. @example
  5617. (if (> 3 2) 'yes 'no) @result{} yes
  5618. @end example
  5619. Kawa also allows you bind variables in the condition,
  5620. using the @samp{?} operator.
  5621. @example
  5622. (if (and (? x ::integer (get-value)) (> x 0))
  5623. (* x 10)
  5624. 'invalid)
  5625. @end example
  5626. In the above, if @code{(get-value)} evaluates to an integer, that
  5627. integer is bound to the variable @code{x}, which is visible
  5628. in both following sub-expression of @code{and},
  5629. as well case the true-part of the @code{if}.
  5630. Specifically, the first sub-expression of an @code{if}
  5631. is a @stxref{test-or-match}, which can be a @stxref{test-expression},
  5632. or a @samp{?} match expression, or a combination using @code{and}:
  5633. @display
  5634. @stxdef{test-or-match} @stxref{test-expression}
  5635. | @stxlit{(?} @stxref{pattern} @stxref{expression} @stxlit{)}
  5636. | @stxlit{(and} @arbno{@stxref{test-or-match}}@stxlit{)}
  5637. @end display
  5638. A @var{test-or-match} is true if every nested @var{test-expression}
  5639. is true, and every @samp{?} operation succeeds.
  5640. It produces a set of variable bindings which is the union
  5641. of the bindings produced by all the @var{pattern}s.
  5642. In an @code{and} form, bindings produced by a @var{pattern} are visible to
  5643. all subsequent @var{test-or-match} sub-expressions.
  5644. @deffn Syntax ? @stxref{pattern} @stxref{expression}
  5645. The form @code{(? @var{P} @var{V})} informally
  5646. is true if the value of @var{V} matches the pattern @var{P}.
  5647. Any variables bound in @var{P} are in scope in the ``true''
  5648. path of the containing conditional.
  5649. This has the form of an expression, but it can only be used
  5650. in places where a @stxref{test-or-match} is required.
  5651. For example it can be used as the first clause of an
  5652. @code{if} expression, in which case the scope of the variables bound in
  5653. the @code{pattern} includes the second (@stxref{consequent}) sub-expression.
  5654. On the other hand, a @samp{?} form may not be used
  5655. as an argument to a procedure application.
  5656. @end deffn
  5657. @deffn Syntax if @stxref{test-or-match} @stxref{consequent} @stxref{alternate}
  5658. @deffnx Syntax if @stxref{test-or-match} @stxref{consequent}
  5659. @display
  5660. @stxdef{consequent} @stxref{expression}
  5661. @stxdef{alternate} @stxref{expression}
  5662. @end display
  5663. An @func{if} expression is evaluated as follows:
  5664. first, the @stxref{test-or-match} is
  5665. evaluated. If it it true, then @meta{consequent} is
  5666. evaluated and its values are returned. Otherwise @meta{alternate} is
  5667. evaluated and its values are returned. If @meta{test} yields @false{}
  5668. and no @meta{alternate} is specified, then the result of the expression
  5669. is void.
  5670. @example
  5671. (if (> 2 3) 'yes 'no) @result{} no
  5672. (if (> 3 2)
  5673. (- 3 2)
  5674. (+ 3 2)) @result{} 1
  5675. (if #f #f) @result{} #!void
  5676. (if (? x::integer 3)
  5677. (+ x 1)
  5678. 'invalid) @result{} 4
  5679. (if (? x::integer 3.4)
  5680. (+ x 1)
  5681. 'invalid) @result{} 'invalid
  5682. @end example
  5683. The @meta{consequent} and @meta{alternate} expressions are in tail
  5684. context if the @func{if} expression itself is.
  5685. @end deffn
  5686. @deffn Syntax cond @atleastone{@stxref{cond-clause}}
  5687. @deffnx Syntax cond @arbno{@stxref{cond-clause}} @stxlit{(else} @meta{expression}@dots{}@stxlit{)}
  5688. @display
  5689. @stxdef{cond-clause} @stxlit{(}@stxref{test-or-match} @stxref{body}@stxlit{)}
  5690. | @stxlit{(}@meta{test} @stxlit{=>} @meta{expression}@stxlit{)}
  5691. @end display
  5692. A @func{cond} expression is evaluated by evaluating the @meta{test-or-match}s
  5693. of successive @meta{cond-clause}s in order until one of them
  5694. evaluates to a true value. When a @meta{test-or-match} is true
  5695. value, then the remaining @meta{expression}s in its @meta{cond-clause}
  5696. are evaluated in order, and the results of the last @meta{expression} in
  5697. the @meta{cond-clause} are returned as the results of the entire
  5698. @func{cond} expression. Variables bound by the @var{test-or-match}
  5699. are visible in @var{body}.
  5700. If the selected @meta{cond-clause} contains only the @meta{test-or-match} and no
  5701. @meta{expression}s, then the value of the last @meta{test-expression} is returned as the
  5702. result. If the selected @meta{cond-clause} uses the @code{=>} alternate
  5703. form, then the @meta{expression} is evaluated. Its value must be a
  5704. procedure. This procedure should accept one argument; it is called on
  5705. the value of the @meta{test-expression} and the values returned by this procedure
  5706. are returned by the @func{cond} expression.
  5707. If all @meta{test-or-match}s evaluate to @false{}, and there is no @code{else}
  5708. clause, then the conditional expression returns unspecified values; if
  5709. there is an @code{else} clause, then its @meta{expression}s are
  5710. evaluated, and the values of the last one are returned.
  5711. @example
  5712. (cond ((> 3 2) 'greater)
  5713. ((< 3 2) 'less)) @result{} greater
  5714. (cond ((> 3 3) 'greater)
  5715. ((< 3 3) 'less)
  5716. (else 'equal)) @result{} equal
  5717. (cond ('(1 2 3) => cadr)
  5718. (else #f)) @result{} 2
  5719. @end example
  5720. For a @meta{cond-clause} of one of the following forms:
  5721. @example
  5722. (@meta{test} @arbno{@stxref{expression}})
  5723. (else @stxref{expression} @arbno{@stxref{expression}})
  5724. @end example
  5725. @noindent
  5726. the last @meta{expression} is in tail context if the @func{cond} form
  5727. itself is. For a @meta{cond clause} of the form:
  5728. @example
  5729. (@meta{test} => @meta{expression})
  5730. @end example
  5731. @noindent
  5732. the (implied) call to the procedure that results from the evaluation of
  5733. @meta{expression} is in tail context if the @func{cond} form itself
  5734. is.
  5735. @end deffn
  5736. @deffn Syntax case @stxref{case-key} @atleastone{@stxref{case-clause}}
  5737. @deffnx Syntax case @stxref{case-key} @arbno{@stxref{case-clause}} @stxref{case-else-clause}
  5738. @display
  5739. @stxdef{case-key} @stxref{expression}
  5740. @stxdef{case-clause} @stxlit{((}@arbno{@stxref{datum}}@stxlit{)} @atleastone{@stxref{expression}}@stxlit{)}
  5741. | @stxlit{((}@arbno{@stxref{datum}}@stxlit{)} @stxlit{=>} @stxref{expression}@stxlit{)}
  5742. @stxdef{case-else-clause} @stxlit{(else} @atleastone{@stxref{expression}}@stxlit{)}
  5743. | @stxlit{(else =>} @stxref{expression}@stxlit{)}
  5744. @end display
  5745. Each @meta{datum} is an external representation of some object.
  5746. Each @meta{datum} in the entire @code{case} expression should be distinct.
  5747. A @func{case} expression is evaluated as follows.
  5748. @enumerate
  5749. @item
  5750. The @meta{case-key} is evaluated and its result is compared using
  5751. @func{eqv?} against the data represented by the @meta{datum}s of
  5752. each @meta{case-clause} in turn, proceeding in order from left to
  5753. right through the set of clauses.
  5754. @item
  5755. If the result of evaluating @meta{case-key} is equivalent to a datum of a
  5756. @meta{case-clause}, the corresponding @meta{expression}s are evaluated
  5757. from left to right and the results of the last expression in the
  5758. @meta{case-clause} are returned as the results of the @func{case}
  5759. expression. Otherwise, the comparison process continues.
  5760. @item
  5761. If the result of evaluating @meta{key} is different from every datum in
  5762. each set, then if there is an @meta{case-else-clause} its expressions are
  5763. evaluated and the results of the last are the results of the @func{case}
  5764. expression; otherwise the result of @func{case} expression is unspecified.
  5765. @end enumerate
  5766. If the selected @meta{case-clause} or @meta{case-else-clause}
  5767. uses the @code{=>} alternate
  5768. form, then the @meta{expression} is evaluated. It is an error if
  5769. its value is not a procedure accepting one argument. This
  5770. procedure is then called on the value of the @meta{key} and the
  5771. values returned by this procedure are returned by the @code{case}
  5772. expression.
  5773. @example
  5774. (case (* 2 3)
  5775. ((2 3 5 7) 'prime)
  5776. ((1 4 6 8 9) 'composite)) @result{} composite
  5777. (case (car '(c d))
  5778. ((a) 'a)
  5779. ((b) 'b)) @result{} unspecified
  5780. (case (car '(c d))
  5781. ((a e i o u) 'vowel)
  5782. ((w y) 'semivowel)
  5783. (else => (lambda (x) x))) @result{} c
  5784. @end example
  5785. The last @meta{expression} of a @meta{case clause} is in tail context if
  5786. the @func{case} expression itself is.
  5787. @end deffn
  5788. @anchor{def-match}
  5789. @deffn Syntax match @stxref{match-key} @atleastone{@stxref{match-clause}}
  5790. The @code{match} form is a generalization of @code{case} using @stxref{pattern}s,
  5791. @display
  5792. @stxdef{match-key} @stxref{expression}
  5793. @stxdef{match-clause}
  5794. @stxlit{(} @stxref{pattern} [@stxref{guard}] @stxref{body} @stxlit{)}
  5795. @end display
  5796. The @var{match-key} is evaluated,
  5797. Then the @var{match-clause}s are tried in order.
  5798. The first @var{match-clause} whose @var{pattern} matches (and
  5799. the @var{guard}, if any, is true), is selected,
  5800. and the corresponding @var{body} evaluated.
  5801. It is an error if no @var{match-clause} matches.
  5802. @example
  5803. (match value
  5804. (0 (found-zero))
  5805. (x #!if (> x 0) (found-positive x))
  5806. (x #!if (< x 0) (found-negative x))
  5807. (x::symbol (found-symbol x))
  5808. (_ (found-other)))
  5809. @end example
  5810. One @code{case} feature is not (yet) directly supported by @code{match}:
  5811. Matching against a list of values.
  5812. However, this is easy to simulate using a guard using @code{memq},
  5813. @code{memv}, or @code{member}:
  5814. @example
  5815. ;; compare similar example under case
  5816. (match (car '(c d))
  5817. (x #!if (memv x '(a e i o u)) ’vowel)
  5818. (x #!if (memv x '(w y)) ’semivowel)
  5819. (x x))
  5820. @end example
  5821. @end deffn
  5822. @deffn Syntax and @arbno{@stxref{test-or-match}}
  5823. If there are no @meta{test-or-match} forms, @true{} is returned.
  5824. If the @code{and} is not in @stxref{test-or-match} context,
  5825. then the last sub-expression (if any) must be a @stxref{test-expression},
  5826. and not a @samp{?} form. In this case the
  5827. @meta{test-or-match} expressions are evaluated from left to right until
  5828. either one of them is false
  5829. (a @meta{test-expression} is false or a @samp{?} match fails),
  5830. or the last @meta{test-expression} is reached. In the
  5831. former case, the @func{and} expression returns @false{} without
  5832. evaluating the remaining expressions. In the latter case, the last
  5833. expression is evaluated and its values are returned.
  5834. If the @code{and} is in @stxref{test-or-match} context,
  5835. then the last sub-form can be @samp{?} form.
  5836. They are evaluated in order: If one of them is false,
  5837. the entire @code{and} is false; otherwise the @code{and} is true.
  5838. Regardless, any bindings made by earlier @samp{?} forms
  5839. are visible in later @var{test-or-match} forms.
  5840. @example
  5841. (and (= 2 2) (> 2 1)) @result{} #t
  5842. (and (= 2 2) (< 2 1)) @result{} #f
  5843. (and 1 2 'c '(f g)) @result{} (f g)
  5844. (and) @result{} #t
  5845. (and (? x ::int 23) (> x 0)) @result{} #t
  5846. @end example
  5847. The @func{and} keyword could be defined in terms of @func{if} using
  5848. @func{syntax-rules} as follows:
  5849. @example
  5850. (define-syntax and
  5851. (syntax-rules ()
  5852. ((and) #t)
  5853. ((and test) test)
  5854. ((and test1 test2 ...)
  5855. (if test1 (and test2 ...) #t))))
  5856. @end example
  5857. The last @meta{test-expression} is in tail context if the @func{and}
  5858. expression itself is.
  5859. @end deffn
  5860. @deffn Syntax or @stxref{test-expression} @dots{}
  5861. If there are no @meta{test-expression}s, @false{} is returned. Otherwise, the
  5862. @meta{test-expression}s are evaluated from left to right until a
  5863. @meta{test-expression} returns a true value @var{val} or the last
  5864. @meta{test-expression} is
  5865. reached. In the former case, the @func{or} expression returns @var{val}
  5866. without evaluating the remaining expressions. In the latter case, the
  5867. last expression is evaluated and its values are returned.
  5868. @example
  5869. (or (= 2 2) (> 2 1)) @result{} #t
  5870. (or (= 2 2) (< 2 1)) @result{} #t
  5871. (or #f #f #f) @result{} #f
  5872. (or '(b c) (/ 3 0)) @result{} (b c)
  5873. @end example
  5874. The @func{or} keyword could be defined in terms of @func{if} using
  5875. @func{syntax-rules} as follows:
  5876. @example
  5877. (define-syntax or
  5878. (syntax-rules ()
  5879. ((or) #f)
  5880. ((or test) test)
  5881. ((or test1 test2 ...)
  5882. (let ((x test1))
  5883. (if x x (or test2 ...))))))
  5884. @end example
  5885. The last @meta{test-expression} is in tail context if the @func{or}
  5886. expression itself is.
  5887. @end deffn
  5888. @deffn Procedure not test-expression
  5889. The @code{not} procedure returns @code{#t} if @var{test-expression} is false,
  5890. and returns @code{#f} otherwise.
  5891. @example
  5892. (not #t) @result{} #f
  5893. (not 3) @result{} #f
  5894. (not (list 3)) @result{} #f
  5895. (not #f) @result{} #t
  5896. (not ’()) @result{} #f
  5897. (not (list)) @result{} #f
  5898. (not ’nil) @result{} #f
  5899. (not #!null) @result{} #t
  5900. @end example
  5901. @end deffn
  5902. @deffn Syntax when @stxref{test-expression} form...
  5903. If @var{test-expression} is true, evaluate each @var{form} in order,
  5904. returning the value of the last one.
  5905. @end deffn
  5906. @deffn Syntax unless @stxref{test-expression} form...
  5907. If @var{test-expression} is false, evaluate each @var{form} in order,
  5908. returning the value of the last one.
  5909. @end deffn
  5910. @node Variables and Patterns
  5911. @section Variables and Patterns
  5912. An identifier can name either a type of syntax or a location
  5913. where a value can be stored. An identifier that names a
  5914. type of syntax is called a @dfn{syntactic keyword}
  5915. (informally called a @dfn{macro}), and is said to be
  5916. @dfn{bound} to a transformer for that syntax. An identifier that
  5917. names a location is called a @dfn{variable} and is said to be @dfn{bound}
  5918. to that location. The set of all visible bindings in effect at
  5919. some point in a program is known as the @dfn{environment} in
  5920. effect at that point. The value stored in the location to
  5921. which a variable is bound is called the variable’s value.
  5922. By abuse of terminology, the variable is sometimes said
  5923. to name the value or to be bound to the value. This is
  5924. not quite accurate, but confusion rarely results from this
  5925. practice.
  5926. Certain expression types are used to create new kinds of
  5927. syntax and to bind syntactic keywords to those new syntaxes,
  5928. while other expression types create new locations
  5929. and bind variables to those locations. These expression
  5930. types are called @dfn{binding constructs}.
  5931. Those that bind syntactic keywords are discussed in @ref{Macros}.
  5932. The most fundamental of the variable binding constructs is the
  5933. @ref{meta-lambda-expression,@code{lambda} expression},
  5934. because all other variable binding constructs
  5935. can be explained in terms of @code{lambda} expressions.
  5936. Other binding constructs include the @ref{Definitions,@code{define} family},
  5937. and the @ref{Local binding constructs,@code{let} family}.
  5938. Scheme is a language with block structure. To each place
  5939. where an identifier is bound in a program there corresponds
  5940. a @dfn{region} of the program text within which the binding is visible.
  5941. The region is determined by the particular binding construct that
  5942. establishes the binding; if the binding is
  5943. established by a @code{lambda} expression, for example, then its
  5944. region is the entire @code{lambda} expression. Every mention of
  5945. an identifier refers to the binding of the identifier that established
  5946. the innermost of the regions containing the use.
  5947. If there is no binding of the identifier whose region contains the use,
  5948. then the use refers to the binding for the
  5949. variable in the global environment, if any;
  5950. if there is no binding for the identifier, it is said to be @dfn{unbound}.
  5951. @subsection Patterns
  5952. The usual way to bind variables is to match an incoming
  5953. value against a @dfn{pattern}. The pattern contains variables
  5954. that are bound to some value derived from the value.
  5955. @example
  5956. (! [x::double y::double] (some-expression))
  5957. @end example
  5958. In the above example, the pattern @code{[x::double y::double]}
  5959. is matched against the incoming value that results from
  5960. evaluating @code{(some-expression)}.
  5961. That value is required to be a two-element sequence.
  5962. Then the sub-pattern @code{x::double} is matched against
  5963. element 0 of the sequence, which means it is coerced to a @code{double}
  5964. and then the coerced value is matched against the sub-pattern @code{x}
  5965. (which trivially succeeds). Similarly, @code{y::double} is matched
  5966. against element 1.
  5967. The syntax of patterns is a work-in-progress. (The focus until now
  5968. has been in designing and implementing how patterns work in general,
  5969. rather than the details of the pattern syntax.)
  5970. @display
  5971. @stxdef{pattern} @stxref{identifier}
  5972. | @stxlit{_}
  5973. | @stxref{pattern-literal}
  5974. | @stxlit{'}@stxref{datum}
  5975. | @stxref{pattern} @stxlit{::} @stxref{type}
  5976. | @stxlit{[} @arbno{@stxref{lpattern}} @stxlit{]}
  5977. @stxdef{lpattern} @stxref{pattern}
  5978. | @stxlit{@@} @stxref{pattern}
  5979. | @stxref{pattern} @stxlit{...}
  5980. | @stxref{guard}
  5981. @stxdef{pattern-literal}
  5982. @stxref{boolean} | number | @stxref{character} | @stxref{string}
  5983. @stxdef{guard} @stxlit{#!if} @stxref{expression}
  5984. @end display
  5985. This is how the specific patterns work:
  5986. @table @asis
  5987. @item @stxref{identifier}
  5988. This is the simplest and most common form of pattern.
  5989. The @var{identifier} is bound to a new variable
  5990. that is initialized to the incoming value.
  5991. @item @stxlit{_}
  5992. This pattern just discards the incoming value.
  5993. It is equivalent to a unique otherwise-unused @var{identifier}.
  5994. @item @stxref{pattern-literal}
  5995. Matches if the value is @code{equal?} to the @var{pattern-literal}.
  5996. @item @stxlit{'}@stxref{datum}
  5997. Matches if the value is @code{equal?} to the quoted @var{datum}.
  5998. @item @stxref{pattern} @stxlit{::} @stxref{type}
  5999. The incoming value is coerced to a value of the specified @var{type},
  6000. and then the coerced value is matched against the sub-@var{pattern}.
  6001. Most commonly the sub-@var{pattern} is a plain @var{identifier},
  6002. so the latter match is trivial.
  6003. @item @stxlit{[} @arbno{@stxref{lpattern}} @stxlit{]}
  6004. The incoming value must be a sequence (a list, vector or similar).
  6005. In the case where each sub-pattern is a plain @var{pattern},
  6006. then the number of sub-patterns must match the size of the sequence, and
  6007. each sub-pattern is matched against the corresponding element of the sequence.
  6008. More generally, each sub-pattern may match zero or more consequtive
  6009. elements of the incoming sequence.
  6010. @item @stxlit{#!if} @stxref{expression}
  6011. No incoming value is used. Instead the @var{expression} is evaluated.
  6012. If the result is true, matching succeeds (so far);
  6013. otherwise the match fails.
  6014. This form is called a @uref{https://en.wikipedia.org/wiki/Guard_(computer_science),@dfn{guard}}.
  6015. @item @stxlit{@@} @stxref{pattern}
  6016. A @dfn{splice pattern} may match multiple (zero or more) elements of a sequence.
  6017. The @var{pattern} is matched against the resulting sub-sequence.
  6018. @example
  6019. (! [x @@r] [2 3 5 7 11])
  6020. @end example
  6021. This binds @code{x} to 2 and @code{r} to @code{[3 5 7 11]}.
  6022. @item @stxref{pattern} @stxlit{...}
  6023. Similar to @code{@@@var{pattern}} in that it matches
  6024. multiple elements of a sequence.
  6025. However, each individual element is matched
  6026. against the @var{pattern}, rather than the elements as a sequence.
  6027. This is a @ref{Repeat forms,repeat pattern}.
  6028. @end table
  6029. @node Definitions
  6030. @section Definitions
  6031. A variable definition binds one or more identifiers and specifies
  6032. an initial value for each of them. The simplest kind of
  6033. variable definition takes one of the following forms:
  6034. @anchor{exclam-syntax}
  6035. @deffn Syntax ! @stxref{pattern} @stxref{expression}
  6036. Evaluate @stxref{expression}, and match the result against @var{pattern}.
  6037. Defining variables in @stxref{pattern} becomes bound in the
  6038. current (surrounding) scope.
  6039. This is similar to @code{define-constant} except generalized to a @var{pattern}.
  6040. @example
  6041. (! [x y] (vector 3 4))
  6042. (format "x is ~w and y is ~w" x y) @result{} "x is 3 and y is 4"
  6043. @end example
  6044. @end deffn
  6045. @deffn Syntax define name [@stxlit{::} @stxref{type}] @stxref{expression}
  6046. Evaluate the @var{expression}, optionally converting it to @var{type},
  6047. and bind the @var{name} to the result.
  6048. @end deffn
  6049. @deffn Syntax define (name @stxref{formal-arguments}) @arbno{(@stxref{annotation} | @stxref{option-pair})} @stxref{opt-return-type} @stxref{body}
  6050. @deffnx Syntax define (name @stxlit{.} @stxref{rest-arg}) @arbno{(@stxref{annotation} | @stxref{option-pair})} @stxref{opt-return-type} @stxref{body}
  6051. Bind the @var{name} to a function definition. The form:
  6052. @example
  6053. (define (@var{name} @stxref{formal-arguments}) @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body})
  6054. @end example
  6055. is equivalent to:
  6056. @example
  6057. (define @var{name} (lambda @stxref{formal-arguments}) name: @var{name} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}))
  6058. @end example
  6059. while the form:
  6060. @example
  6061. (define (@var{name} . @stxref{rest-arg}) @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body})
  6062. @end example
  6063. is equivalent to:
  6064. @example
  6065. (define @var{name} (lambda @stxref{rest-arg}) name: @var{name} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}))
  6066. @end example
  6067. You can associate @ref{Annotations,annotations} with @var{name}.
  6068. A field annotation will be associated with the generated field;
  6069. a method annotation will be associated with the generated method(s).
  6070. @end deffn
  6071. In addition to @code{define} (which can take an optional type specifier),
  6072. Kawa has some extra definition forms.
  6073. @deffn Syntax define-private name [@stxlit{::} @stxref{type}] value
  6074. @deffnx Syntax define-private (name formals) body
  6075. Same as @code{define}, except that @code{name} is not exported.
  6076. @end deffn
  6077. @deffn Syntax define-constant name [@stxlit{::} @stxref{type}] value
  6078. @deffnx Syntax define-early-constant name [:: type] value
  6079. Defines @var{name} to have the given @var{value}.
  6080. The value is readonly, and you cannot assign to it.
  6081. (This is not fully enforced.)
  6082. If @code{define-early-constant} is used
  6083. @emph{or} the @var{value} is a compile-time constant,
  6084. then the compiler will create a @code{final} field with
  6085. the given name and type, and evaluate @var{value}
  6086. in the module's class initializer (if the definition
  6087. is static) or constructor (if the definition is non-static),
  6088. before other definitions and expressions.
  6089. Otherwise, the @var{value} is evaluated in the module body
  6090. where it appears.
  6091. If the @var{value} is a compile-time constant,
  6092. then the definition defaults to being static.
  6093. @end deffn
  6094. @deffn Syntax define-variable name [@stxlit{::} @stxref{type}] [init]
  6095. If @var{init} is specified and @var{name} does not have a global variable
  6096. binding, then @var{init} is evaluated, and @var{name} bound to the result.
  6097. Otherwise, the value bound to @var{name} does not change.
  6098. (Note that @var{init} is not evaluated
  6099. if @var{name} does have a global variable binding.)
  6100. Also, declares to the compiler that @var{name} will be looked up
  6101. in the per-thread dynamic environment. This can be useful for shutting up
  6102. warnings from @code{--warn-undefined-variable}.
  6103. This is similar to the Common Lisp @code{defvar} form.
  6104. However, the Kawa version is (currently) only allowed at module level.
  6105. @end deffn
  6106. For @code{define-namespace} and @code{define-private-namespace}
  6107. see @ref{Namespaces}.
  6108. @node Local binding constructs
  6109. @section Local binding constructs
  6110. The binding constructs @code{let}, @code{let*}, @code{letrec},
  6111. and @code{letrec*} give Scheme a block structure, like Algol 60.
  6112. The syntax of these four constructs
  6113. is identical, but they differ in the regions they establish
  6114. for their variable bindings. In a @code{let} expression, the initial
  6115. values are computed before any of the variables become
  6116. bound; in a @code{let*} expression, the bindings and evaluations
  6117. are performed sequentially; while in @code{letrec} and @code{letrec*}
  6118. expressions, all the bindings are in effect while their initial
  6119. values are being computed, thus allowing mutually recursive definitions.
  6120. @c The let-values and let*-values con-
  6121. @c structs are analogous to let and let* respectively, but
  6122. @c are designed to handle multiple-valued expressions, bind-
  6123. @c ing different identifiers to the returned values.
  6124. @deffn Syntax let @stxlit{((}@stxref{pattern} @var{init}@stxlit{)} ...@stxlit{)} @stxref{body}
  6125. Declare new local variables as found in the @meta{pattern}s.
  6126. Each @var{pattern} is matched against the corresponding @var{init}.
  6127. The @var{init}s are evaluated in the current environment (in left-to-right
  6128. onder), the @var{variable}s in the @var{patterns}s are bound to fresh
  6129. locations holding the matched results,
  6130. the @var{body} is evaluated in the extended environment, and the values of
  6131. the last expression of body are returned.
  6132. Each binding of a variable has @var{body} as its region.
  6133. @example
  6134. (let ((x 2) (y 3))
  6135. (* x y)) @result{} 6
  6136. @end example
  6137. @example
  6138. (let ((x 2) (y 3))
  6139. (let ((x 7)
  6140. (z (+ x y)))
  6141. (* z x))) @result{} 35
  6142. @end example
  6143. An example with a non-trivial pattern:
  6144. @example
  6145. (let (([a::double b::integer] (vector 4 5)))
  6146. (cons b a)) @result{} (5 . 4.0)
  6147. @end example
  6148. @end deffn
  6149. @deffn Syntax let* @stxlit{((}@stxref{pattern} init@stxlit{)} ...@stxlit{)} @stxref{body}
  6150. The @code{let*} binding construct is similar to @code{let},
  6151. but the bindings are performed sequentially from left to
  6152. right, and the region of a @var{variable}s in a @var{pattern}
  6153. is that part of the @code{let*} expression to the right of
  6154. the @var{pattern}. Thus the second pattern is matched in an environment
  6155. in which the bindings from the first pattern are visible, and so on.
  6156. @example
  6157. (let ((x 2) (y 3))
  6158. (let* ((x 7)
  6159. (z (+ x y)))
  6160. (* z x))) @result{} 70
  6161. @end example
  6162. @end deffn
  6163. @deffn Syntax letrec @stxlit{((}variable [@stxlit{::} @stxref{type}] init@stxlit{)} ...@stxlit{)} @stxref{body}
  6164. @deffnx Syntax letrec* @stxlit{((}variable [@stxlit{::} @stxref{type}] init@stxlit{)} ...@stxlit{)} @stxref{body}
  6165. The @var{variable}s are bound to fresh locations,
  6166. each @var{variable} is assigned in left-to-right order
  6167. to the result of the corresponding @var{init},
  6168. the @var{body} is evaluated in the resulting environment,
  6169. and the values of the last expression in body are returned.
  6170. Despite the left-to-right evaluation and assignment order, each binding of a
  6171. @var{variable} has the entire @code{letrec} or @code{letrec*}
  6172. expression as its region,
  6173. making it possible to define mutually recursive procedures.
  6174. In Kawa @code{letrec} is defined as the same as @code{letrec*}.
  6175. In standard Scheme the order of evaluation of the @var{init}s
  6176. is undefined, as is the order of assignments.
  6177. If the order matters, you should use @code{letrec*}.
  6178. If it is not possible to evaluate each @var{init} without assigning
  6179. or referring to the value of the corresponding @var{variable}
  6180. or the variables that follow it, it is an error.
  6181. @example
  6182. (letrec ((even?
  6183. (lambda (n)
  6184. (if (zero? n)
  6185. #t
  6186. (odd? (- n 1)))))
  6187. (odd?
  6188. (lambda (n)
  6189. (if (zero? n)
  6190. #f
  6191. (even? (- n 1))))))
  6192. (even? 88))
  6193. @result{} #t
  6194. @end example
  6195. @end deffn
  6196. @node Lazy evaluation
  6197. @section Lazy evaluation
  6198. @dfn{Lazy evaluation} (or call-by-need) delays evaluating an expression until it
  6199. is actually needed; when it is evaluated, the result is saved so
  6200. repeated evaluation is not needed.
  6201. @uref{http://en.wikipedia.org/wiki/Lazy_evaluation,Lazy evaluation}
  6202. is a technique that can make some algorithms easier to express compactly
  6203. or much more efficiently, or both. It is the normal evaluation mechanism
  6204. for strict functional (side-effect-free) languages such as
  6205. @uref{http://www.haskell.org,Haskell}.
  6206. However, automatic lazy evaluation is awkward to combine with side-effects
  6207. such as input-output. It can also be difficult to implement
  6208. lazy evaluation efficiently, as it requires more book-keeping.
  6209. Kawa, like other Schemes, uses ``eager evaluation'' - an expression
  6210. is normally evaluated immediately, unless it is wrapped in a special form.
  6211. Standard Scheme has some basic building blocks for ``manual''
  6212. lazy evaluation, using an explicit @code{delay} operator to
  6213. indicate that an expression is to be evaluated lazily,
  6214. yielding a @dfn{promise},
  6215. and a @code{force} function to force evaluation of a promise.
  6216. This functionality is enhanced in
  6217. @uref{http://srfi.schemers.org/srfi-45/srfi-45.html, SRFI 45},
  6218. in R7RS-draft (based on SRFI 45),
  6219. and @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41} (lazy lists aka streams).
  6220. Kawa makes lazy evaluation easier to use, by @dfn{implicit forcing}:
  6221. The promise is automatically evaluated (forced) when used in a
  6222. context that requires a normal value, such as arithmetic needing a number.
  6223. Kawa enhances lazy evaluation in other ways, including
  6224. support for safe multi-threaded programming.
  6225. @subsection Delayed evaluation
  6226. @deffn Syntax delay @stxref{expression}
  6227. The @code{delay} construct is used together with the procedure
  6228. @code{force} to implement @emph{lazy evaluation} or @emph{call by need}.
  6229. The result of @code{(delay @var{expression})} is a
  6230. @emph{promise} which at some point in the future may be asked (by the
  6231. @func{force} procedure) to evaluate @var{expression}, and deliver the
  6232. resulting value. The effect of @var{expression} returning multiple
  6233. values is unspecified.
  6234. @end deffn
  6235. @deffn Syntax delay-force @stxref{expression}
  6236. @deffnx Syntax lazy @stxref{expression}
  6237. The @code{delay-force} construct is similar to @code{delay}, but it is expected
  6238. that its argument evaluates to a promise.
  6239. (Kawa treats a non-promise value as if it were a forced promise.)
  6240. The returned
  6241. promise, when forced, will evaluate to whatever the original
  6242. promise would have evaluated to if it had been forced.
  6243. The expression @code{(delay-force @meta{expression})} is
  6244. conceptually similar to @code{(delay (force @meta{expression}))}, with
  6245. the difference that forcing the result of @code{delay-force} will
  6246. in effect result in a tail call to @code{(force @meta{expression})}, while
  6247. forcing the result of @code{(delay (force @meta{expression}))} might
  6248. not. Thus iterative lazy algorithms that might result in a
  6249. long series of chains of @code{delay} and @code{force} can be rewritten
  6250. using delay-force to prevent consuming unbounded space
  6251. during evaluation.
  6252. Using @code{delay-force} or @code{lazy} is equivalent.
  6253. The name @code{delay-force} is from R7RS; the name @code{lazy}
  6254. is from the older SRFI-45.
  6255. @end deffn
  6256. @deffn Procedure eager obj
  6257. Returns a promise that when forced will return @var{obj}.
  6258. It is similar to @code{delay}, but does not delay its argument;
  6259. it is a procedure rather than syntax.
  6260. The Kawa implementation just returns @var{obj} as-is.
  6261. This is because Kawa treats as equivalent
  6262. a value and forced promise evaluating to the value.
  6263. @end deffn
  6264. @deffn Procedure force promise
  6265. The @func{force} procedure forces the value of @var{promise}.
  6266. As a Kawa extension, if the @var{promise} is not a promise (a value that
  6267. does not implement @code{gnu.mapping.Lazy}) then the argument is returned unchanged.
  6268. If no value has been computed for the promise, then a value is computed and
  6269. returned. The value of the promise is cached (or ``memoized'') so that
  6270. if it is forced a second time, the previously computed value is
  6271. returned.
  6272. @example
  6273. (force (delay (+ 1 2))) @result{} 3
  6274. (let ((p (delay (+ 1 2))))
  6275. (list (force p) (force p))) @result{} (3 3)
  6276. (define integers
  6277. (letrec ((next
  6278. (lambda (n)
  6279. (cons n (delay (next (+ n 1)))))))
  6280. (next 0)))
  6281. (define head
  6282. (lambda (stream) (car (force stream))))
  6283. (define tail
  6284. (lambda (stream) (cdr (force stream))))
  6285. (head (tail (tail integers))) @result{} 2
  6286. @end example
  6287. The following example is a mechanical transformation of
  6288. a lazy stream-filtering algorithm into Scheme. Each call
  6289. to a constructor is wrapped in @code{delay}, and each argument
  6290. passed to a deconstructor is wrapped in @code{force}. The use
  6291. of @code{(lazy ...)} instead of @code{(delay (force ...))} around
  6292. the body of the procedure ensures that an ever-growing
  6293. sequence of pending promises does not exhaust the heap.
  6294. @example
  6295. (define (stream-filter p? s)
  6296. (lazy
  6297. (if (null? (force s))
  6298. (delay ’())
  6299. (let ((h (car (force s)))
  6300. (t (cdr (force s))))
  6301. (if (p? h)
  6302. (delay (cons h (stream-filter p? t)))
  6303. (stream-filter p? t))))))
  6304. (head (tail (tail (stream-filter odd? integers))))
  6305. @result{} 5
  6306. @end example
  6307. @end deffn
  6308. @deffn Procedure force* promise
  6309. Does @code{force} as many times as necessary to produce a non-promise.
  6310. (A non-promise is a value that does not implement @code{gnu.mapping.Lazy},
  6311. or if it does implement @code{gnu.mapping.Lazy} then forcing the value
  6312. using the @code{getValue} method yields the receiver.)
  6313. The @code{force*} function is a Kawa extension.
  6314. Kawa will add implicit calls to @code{force*}
  6315. in most contexts that need it, but you can also call it explicitly.
  6316. @end deffn
  6317. The following examples are not intended to illustrate good
  6318. programming style, as @code{delay}, @code{lazy}, and @code{force} are mainly
  6319. intended for programs written in the functional style.
  6320. However, they do illustrate the property that only one value is
  6321. computed for a promise, no matter how many times it is
  6322. forced.
  6323. @example
  6324. (define count 0)
  6325. (define p
  6326. (delay (begin (set! count (+ count 1))
  6327. (if (> count x)
  6328. count
  6329. (force p)))))
  6330. (define x 5)
  6331. p @result{} @emph{a promise}
  6332. (force p) @result{} 6
  6333. p @result{} @emph{a promise, still}
  6334. (begin (set! x 10)
  6335. (force p)) @result{} 6
  6336. @end example
  6337. @subsection Implicit forcing
  6338. If you pass a promise as an argument to a function like @code{sqrt}
  6339. if must first be forced to a number. In general, Kawa does this
  6340. automatically (implicitly) as needed, depending on the context.
  6341. For example:
  6342. @example
  6343. (+ (delay (* 3 7)) 13) @result{} 34
  6344. @end example
  6345. Other functions,
  6346. like @code{cons} have no problems with promises, and automatic forcing
  6347. would be undesirable.
  6348. Generally, implicit forcing happens for arguments that require a
  6349. specific type, and does not happen for arguments that work on
  6350. @emph{any} type (or @code{Object}).
  6351. Implicit forcing happens for:
  6352. @itemize
  6353. @item
  6354. arguments to arithmetic functions;
  6355. @item
  6356. the sequence and the index in indexing operations, like @code{string-ref};
  6357. @item
  6358. the operands to @code{eqv?} and @code{equal?} are forced,
  6359. though the operands to @code{eq?} are not;
  6360. @item
  6361. port operands to port functions;
  6362. @item
  6363. the value to be emitted by a @code{display} but @emph{not} the
  6364. value to be emitted by a @code{write};
  6365. @item
  6366. the function in an application.
  6367. @end itemize
  6368. Type membership tests, such as the @code{instance?} operation,
  6369. generally do not force their values.
  6370. The exact behavior for when implicit forcing happens is a work-in-progress:
  6371. There are certainly places where implicit forcing doesn't happen while
  6372. it should; there are also likely to be places where implicit forcing
  6373. happens while it is undesirable.
  6374. Most Scheme implementations are such that a forced promise behaves differently
  6375. from its forced value, but some Scheme implementions are such that there is no
  6376. means by which a promise can be operationally distinguished
  6377. from its forced value.
  6378. Kawa is a hybrid: Kawa tries to minimize the difference between
  6379. a forced promise and its forced value, and may freely optimize
  6380. and replace a forced promise with its value.
  6381. @subsection Blank promises
  6382. A @dfn{blank promise} is a promise that doesn't (yet) have
  6383. a value @emph{or} a rule for calculating the value.
  6384. Forcing a blank promise will wait forever, until some
  6385. other thread makes the promise non-blank.
  6386. Blank promises are useful as a synchronization mechanism -
  6387. you can use it to safely pass data from one thread (the producer)
  6388. to another thread (the consumer). Note that you can only
  6389. pass one value for a given promise: To pass multiple values, you
  6390. need multiple promises.
  6391. @example
  6392. (define p (promise))
  6393. (future ;; Consumer thread
  6394. (begin
  6395. (do-stuff)
  6396. (define v (force promise)) ; waits until promise-set-value!
  6397. (do-stuff-with v)))
  6398. ;; Producer thread
  6399. ... do stuff ...
  6400. (promise-set-value! p (calculate-value))
  6401. @end example
  6402. @deffn Constructor promise
  6403. Calling @code{promise} as a zero-argument constructor
  6404. creates a new blank promise.
  6405. This calls the constructor for @code{gnu.mapping.Promise}.
  6406. You can also create a non-blank promise, by setting one
  6407. of the @code{value}, @code{alias}, @code{thunk}, or @code{exception} properties.
  6408. Doing so is equivalent to calling @code{promise-set-value!},
  6409. @code{promise-set-alias!}, @code{promise-set-thunk!}, or
  6410. @code{promise-set-exception!} on the resulting promise.
  6411. For example: @code{(delay exp)} is equivalent to:
  6412. @example
  6413. (promise thunk: (lambda() exp))
  6414. @end example
  6415. @end deffn
  6416. The following four procedures require that their first arguments
  6417. be blank promises. When the procedure returns, the promise is
  6418. no longer blank, and cannot be changed. This is because a
  6419. promise is conceptually a placeholder for a single ``not-yet-known'' value;
  6420. it is not a location that can be assigned multiple times.
  6421. The former enables clean and safe (``declarative") use of multiple threads;
  6422. the latter is much trickier.
  6423. @deffn Procedure promise-set-value! promise value
  6424. Sets the value of the @var{promise} to @var{value},
  6425. which makes the @var{promise} forced.
  6426. @end deffn
  6427. @deffn Procedure promise-set-exception! promise exception
  6428. Associate @var{exception} with the @var{promise}.
  6429. When the @var{promise} is forced the @var{exception} gets thrown.
  6430. @end deffn
  6431. @deffn Procedure promise-set-alias! promise other
  6432. Bind the @var{promise} to be an alias of @var{other}.
  6433. Forcing @var{promise} will cause @var{other} to be forced.
  6434. @end deffn
  6435. @deffn Procedure promise-set-thunk! promise thunk
  6436. Associate @var{thunk} (a zero-argument procedure) with the @var{promise}.
  6437. The first time the @var{promise} is forced will causes the
  6438. @var{thunk} to be called, with the result (a value or an exception)
  6439. saved for future calls.
  6440. @end deffn
  6441. @deffn Procedure make-promise obj
  6442. The @code{make-promise} procedure returns a promise which,
  6443. when forced, will return @var{obj}. It is similar to @code{delay}, but
  6444. does not delay its argument: it is a procedure rather than
  6445. syntax. If @var{obj} is already a promise, it is returned.
  6446. Because of Kawa's implicit forcing, there is seldom a
  6447. need to use @code{make-promise}, except for portability.
  6448. @end deffn
  6449. @subsection Lazy and eager types
  6450. @deffn Type promise[T]
  6451. This parameterized type is the type of promises that evaluate to
  6452. an value of type @code{T}.
  6453. It is equivalent to the Java interface @code{gnu.mapping.Lazy<T>}.
  6454. The implementation class for promises is usually @code{gnu.mapping.Promise},
  6455. though there are other classes that implement @code{Lazy},
  6456. most notably @code{gnu.mapping.Future}, used for futures,
  6457. which are promises evaluated in a separate thread.
  6458. @end deffn
  6459. Note the distinction between the types @code{integer}
  6460. (the type of actual (eager) integer values), and @code{promise[integer]}
  6461. (the type of (lazy) promises that evaluate to integer).
  6462. The two are compatible: if a @code{promise[integer]} value is provided
  6463. in a context requiring an @code{integer} then it is automatically
  6464. evaluated (forced). If an @code{integer} value is provided
  6465. in context requiring a @code{promise[integer]}, that conversion is basically
  6466. a no-op (though the compiler may wrap the @code{integer}
  6467. in a pre-forced promise).
  6468. In a fully-lazy language there would be no distinction, or
  6469. at least the promise type would be the default. However, Kawa is
  6470. a mostly-eager language, so the eager type is the default.
  6471. This makes efficient code-generation easier: If an expression
  6472. has an eager type, then the compiler can generate code that
  6473. works on its values directly, without having to check for laziness.
  6474. @node Repeat forms
  6475. @section Repeat patterns and expressions
  6476. Many programming languages have some variant
  6477. of @uref{https://en.wikipedia.org/wiki/List_comprehension,list comprehension syntax}.
  6478. Kawa splits this into two separate forms,
  6479. that can be in separate parts of the program:
  6480. @itemize
  6481. @item
  6482. @cindex repeat pattern
  6483. A @dfn{repeat pattern} as you might guess
  6484. repeats a pattern by matching the pattern once for each element of a sequence.
  6485. For example, assume @code{A} is a some sequence-valued expression.
  6486. Then:
  6487. @example
  6488. #|kawa:3|# @kbd{(! [a::integer ...] A)}
  6489. @end example
  6490. Here @samp{a::integer ...} is a @var{repeat pattern} that
  6491. matches all the elements pf @code{A}.
  6492. We call @samp{a::integer} the @dfn{repeated pattern} - it matches an
  6493. individual element of @code{A}.
  6494. @cindex repeat variable
  6495. Any variable defined in a repeated pattern is a @dfn{repeat variable}.
  6496. In the example, that would be @code{a}.
  6497. @item
  6498. @cindex repeat expression
  6499. A @dfn{repeat expression} creates a sequence by repeating
  6500. an expression for each element of the result.
  6501. @example
  6502. #|kawa:4|# @kbd{[(* 2 a) ...]}
  6503. [4 6 10 14 22]
  6504. @end example
  6505. In this case @samp{(* 2 a) ...} is the repeat expression.
  6506. The @dfn{repeated expression} is @samp{(* 2 a)}.
  6507. The repeated expression is evaluated once for each element
  6508. of any contained repeat variable.
  6509. If there is more than one repeat variable, they are
  6510. repeated in parallel, as many times as the ``shortest'' repeat variable,
  6511. similar to the @code{map} procedure.
  6512. (If there is no repeat variable, the repeated expression is potentially
  6513. evaluated infinitely many times, which is not allowed.
  6514. A planned extension will allow it for lazy repeated expression.)
  6515. @end itemize
  6516. The use of @samp{...} for repeat patterns and expressions mirrors
  6517. exactly their use in @code{syntax-rules} patterns and templates.
  6518. It is an error to use a repeat variable outside of repeat context:
  6519. @example
  6520. #|kawa:5|# @kbd{a}
  6521. /dev/stdin:2:1: using repeat variable 'a' while not in repeat context
  6522. @end example
  6523. The repeat form feature is not yet complete.
  6524. It is missing functionality such as selecting only some elements
  6525. from a repeat sequence, lazy sequences, and it could be optimized more.
  6526. A repeat variable can be used multiple times in the
  6527. same repeat expressions, or different repeat expressions:
  6528. @example
  6529. #|kawa:7|# @kbd{[a ... a ...]}
  6530. [2 3 5 7 11 2 3 5 7 11]
  6531. #|kawa:8|# @kbd{[(* a a) ...]}
  6532. [4 9 25 49 121]
  6533. @end example
  6534. Repeat expressions are useful not just in sequence literals,
  6535. but in the argument list of a procedure call, where the resulting sequence
  6536. is spliced into the argument list. This is especially useful for functions
  6537. that take a variable number of arguments, because that enables a
  6538. convenient way to do @uref{https://en.wikipedia.org/wiki/Fold_(higher-order_function),fold/accumulate/reduce} operations. For example:
  6539. @example
  6540. #|kawa:9|# @kbd{(+ a ...)}
  6541. 28
  6542. @end example
  6543. because 28 is the result of @code{(+ 2 3 5 7 11)}.
  6544. An elegant way to implement @uref{https://en.wikipedia.org/wiki/Dot_product,dot product}:
  6545. @example
  6546. (define (dot-product [x ...] [y ...])
  6547. (+ (* x y) ...))
  6548. @end example
  6549. When an ellipse expression references two or more distinct repeat variables
  6550. then they are processed ``in parallel''.
  6551. That does not (necessarily) imply muliple threads, but that the first element
  6552. of the repeat result is evaluated using the first element of all the repeat sequences,
  6553. the second element of the result uses the second element of all the repeat sequences, and so on.
  6554. @subsubheading Sub-patterns in repeat patterns
  6555. While the repeated pattern before the @samp{...}
  6556. is commonly in identifier, it may be a more complex pattern.
  6557. We showed earlier the repeated pattern with a type specifier,
  6558. which applies to each element:
  6559. @example
  6560. #|kawa:11|# @kbd{(define (isum [x::integer ...]) (+ x ...))}
  6561. #|kawa:12|# @kbd{(isum [4 5 6])}
  6562. 15
  6563. #|kawa:12|# @kbd{(isum [4 5.1 6])}
  6564. Argument #1 (null) to 'isum' has wrong type
  6565. at gnu.mapping.CallContext.matchError(CallContext.java:189)
  6566. at atInteractiveLevel-6.isum$check(stdin:11)
  6567. ...
  6568. @end example
  6569. (The stack trace line number @code{stdin:11} is that of the @code{isum} definition.)
  6570. You can nest repeat patterns, allowing matching against sequences whose elements are sequences.
  6571. @example
  6572. #|kawa:31|# @kbd{(define (fun2 [[x ...] ...] [y ...])}
  6573. #|.....32|# @kbd{ [[(+ x y) ...] ...])}
  6574. #|kawa:33|# @kbd{(fun2 [[1 2 3] [10 11 12]] [100 200])}
  6575. [[101 102 103] [210 211 212]]
  6576. @end example
  6577. Note that @code{x} is double-nested, while @code{y} is singly-nested.
  6578. Here each element is constrained to be a pair (a -element sequence):
  6579. @example
  6580. #|kawa:1|# @kbd{(! [[x y] ...] [[11 12] [21 22] [31 32]])}
  6581. #|kawa:2|# @kbd{[(+ x y) ...]}
  6582. #(23 43 63)
  6583. #|kawa:3|# @kbd{[[x ...] [y ...]]}
  6584. #(#(11 21 31) #(12 22 32))
  6585. @end example
  6586. @node Threads
  6587. @section Threads
  6588. There is a very preliminary interface to create parallel threads.
  6589. The interface is similar to the standard @code{delay}/@code{force},
  6590. where a thread is basically the same as a promise, except that
  6591. evaluation may be in parallel.
  6592. @deffn Syntax future expression
  6593. Creates a new thread that evaluates @var{expression}.
  6594. (The result extends @code{java.lang.Thread} and
  6595. implements @code{gnu.mapping.Lazy}.)
  6596. @end deffn
  6597. @deffn Procedure force thread
  6598. The standard @code{force} function is generalized to also work
  6599. on threads. It waits for the thread's @var{expression} to finish
  6600. executing, and returns the result.
  6601. @end deffn
  6602. @deffn Procedure runnable function
  6603. Creates a new @code{Runnable} instance from a function.
  6604. Useful for passing to Java code that expects a @code{Runnable}.
  6605. You can get the result (a value or a thrown exception) using the
  6606. @code{getResult} method.
  6607. @end deffn
  6608. @deffn Syntax synchronized object form ...
  6609. Synchronize on the given @var{object}. (This means getting an
  6610. exclusive lock on the object, by acquiring its @dfn{monitor}.)
  6611. Then execute the @var{form}s while holding the lock.
  6612. When the @var{form}s finish (normally or abnormally by throwing
  6613. an exception), the lock is released.
  6614. Returns the result of the last @var{form}.
  6615. Equivalent to the Java @code{synchronized} statement,
  6616. except that it may return a result.
  6617. @end deffn
  6618. @node Exceptions
  6619. @section Exception handling
  6620. An @dfn{exception} is an object used to signal an error or
  6621. other exceptional situation. The program or run-time system
  6622. can @dfn{throw} the exception when an error is discovered.
  6623. An exception handler is a program construct that registers
  6624. an action to handle exceptions when the handler is active.
  6625. If an exception is thrown and not handled then the
  6626. read-eval-print-loop will print a stack trace, and bring
  6627. you back to the top level prompt.
  6628. When not running interactively, an unhandled exception
  6629. will normally cause Kawa to be exited.
  6630. In the Scheme exception model (as of R6RS and R7RS),
  6631. exception handlers are one-argument procedures that determine
  6632. the action the program takes when an exceptional situation is signaled.
  6633. The system implicitly maintains a
  6634. current exception handler in the dynamic environment.
  6635. The program raises an exception by invoking the current
  6636. exception handler, passing it an object encapsulating information
  6637. about the exception. Any procedure accepting
  6638. one argument can serve as an exception handler and any
  6639. object can be used to represent an exception.
  6640. The Scheme exception model is implemented on top of the Java VM's
  6641. native exception model where the only objects that
  6642. can be thrown are instances of @code{java.lang.Throwable}.
  6643. Kawa also provides direct access to this native model,
  6644. as well as older Scheme exception models.
  6645. @deffn Procedure with-exception-handler handler thunk
  6646. It is an error if @var{handler} does not accept one argument.
  6647. It is also an error if @var{thunk} does not accept zero arguments.
  6648. The @code{with-exception-handler} procedure returns the results
  6649. of invoking @var{thunk}. The @var{handler} is installed as the current
  6650. exception handler in the dynamic environment used for the
  6651. invocation of @var{thunk}.
  6652. @example
  6653. (call-with-current-continuation
  6654. (lambda (k)
  6655. (with-exception-handler
  6656. (lambda (x)
  6657. (display "condition: ")
  6658. (write x)
  6659. (newline)
  6660. (k 'exception))
  6661. (lambda ()
  6662. (+ 1 (raise ’an-error))))))
  6663. @result{} exception
  6664. @i{and prints} condition: an-error
  6665. @end example
  6666. @example
  6667. (with-exception-handler
  6668. (lambda (x)
  6669. (display "something went wrong\n"))
  6670. (lambda ()
  6671. (+ 1 (raise ’an-error))))
  6672. @i{prints} something went wrong
  6673. @end example
  6674. After printing, the second example then raises another exception.
  6675. @PerformanceNote{} The @var{thunk} is inlined if it is a
  6676. lambda expression. However, the @var{handler} cannot be inlined
  6677. even if it is a lambda expression, because it could be called by
  6678. @code{raise-continuable}. Using the @code{guard} form is
  6679. usually more efficient.
  6680. @end deffn
  6681. @deffn Procedure raise obj
  6682. Raises an exception by invoking the current exception handler on @var{obj}.
  6683. The handler is called with the same dynamic
  6684. environment as that of the call to raise, except that the
  6685. current exception handler is the one that was in place when
  6686. the handler being called was installed. If the handler returns,
  6687. then @var{obj} is re-raised in the same dynamic environment as the handler.
  6688. If @var{obj} is an instance of @code{java.lang.Throwable},
  6689. then @code{raise} has the same effect as @code{primitive-throw}.
  6690. @end deffn
  6691. @deffn Procedure raise-continuable obj
  6692. Raises an exception by invoking the current exception handler on @var{obj}.
  6693. The handler is called with the same dynamic
  6694. environment as the call to @code{raise-continuable}, except
  6695. that: (1) the current exception handler is the one that was
  6696. in place when the handler being called was installed, and
  6697. (2) if the handler being called returns, then it will again
  6698. become the current exception handler.
  6699. If the handler returns, the values it returns become the values
  6700. returned by the call to @code{raise-continuable}.
  6701. @example
  6702. (with-exception-handler
  6703. (lambda (con)
  6704. (cond
  6705. ((string? con)
  6706. (display con))
  6707. (else
  6708. (display "a warning has been issued")))
  6709. 42)
  6710. (lambda ()
  6711. (+ (raise-continuable "should be a number")
  6712. 23)))
  6713. @i{prints:} should be a number
  6714. @result{} 65
  6715. @end example
  6716. @end deffn
  6717. @deffn Syntax guard @var{variable} @atleastone{@stxref{cond-clause}} @stxref{body}
  6718. The @meta{body} is evaluated with an exception handler that binds
  6719. the raised object to @var{variable} and, within the scope of that binding,
  6720. evaluates the clauses as if they were the clauses of a @code{cond} expression.
  6721. That implicit @code{cond} expression is evaluated with
  6722. the continuation and dynamic environment of the @code{guard}
  6723. expression. If every cond-clause’s test evaluates to @code{#f}
  6724. and there is no @code{else} clause, then @code{raise-continuable} is
  6725. invoked on the raised object within the dynamic environment of the
  6726. original call to @code{raise} or @code{raise-continuable},
  6727. except that the current exception handler is that of the
  6728. @code{guard} expression.
  6729. @example
  6730. (guard (condition
  6731. ((assq 'a condition) => cdr)
  6732. ((assq 'b condition)))
  6733. (raise (list (cons 'a 42))))
  6734. @result{} 42
  6735. @end example
  6736. @example
  6737. (guard (condition
  6738. ((assq 'a condition) => cdr)
  6739. ((assq 'b condition)))
  6740. (raise (list (cons 'b 23))))
  6741. @result{} (b . 23)
  6742. @end example
  6743. @PerformanceNote{} Using @code{guard} is moderately efficient:
  6744. there is some overhead compared to using native exception handling,
  6745. but both the @var{body} and the handlers in the @var{cond-clause}
  6746. are inlined.
  6747. @end deffn
  6748. @deffn Procedure dynamic-wind in-guard thunk out-guard
  6749. All three arguments must be 0-argument procedures.
  6750. First calls @var{in-guard}, then @var{thunk}, then @var{out-guard}.
  6751. The result of the expression is that of @var{thunk}.
  6752. If @var{thunk} is exited abnormally (by throwing an exception or
  6753. invoking a continuation), @var{out-guard} is called.
  6754. If the continuation of the dynamic-wind is re-entered (which
  6755. is not yet possible in Kawa), the @var{in-guard} is called again.
  6756. This function was added in R5RS.
  6757. @end deffn
  6758. @deffn Procedure read-error? obj
  6759. Returns #t if @var{obj} is an object raised by the @code{read} procedure.
  6760. (That is if @var{obj} is a @code{gnu.text.SyntaxException}.)
  6761. @end deffn
  6762. @deffn Procedure file-error? obj
  6763. Returns #t if @var{obj} is an object raised by inability to open an input
  6764. or output port on a file.
  6765. (This includes @code{java.io.FileNotFoundException} as well
  6766. as certain other exceptions.)
  6767. @end deffn
  6768. @subsection Simple error objects
  6769. @deffn Procedure error message obj ...
  6770. Raises an exception as if by calling @code{raise}
  6771. on a newly allocated @dfn{simple error object},
  6772. which encapsulates the information provided by @var{message}
  6773. (which should a string), as well as any @var{obj} arguments,
  6774. known as the irritants.
  6775. The string representation of a simple error object is as if calling
  6776. @code{(format "#<ERROR ~a~@{ ~w~@}>" @var{message} @var{irritants})}.
  6777. (That is the @var{message} is formatted as if with @code{display}
  6778. while each irritant @var{obj} is formatted as if with @code{write}.)
  6779. This procedure is part of SRFI-23, and R7RS.
  6780. It differs from (and is incompatible with) R6RS's @code{error} procedure.
  6781. @end deffn
  6782. @deffn Procedure error-object? obj
  6783. Returns @code{#t} if @var{obj} is a simple error object.
  6784. Specifically, that @var{obj} is an instance of @code{kawa.lang.NamedException}.
  6785. Otherwise, it returns @code{#f}.
  6786. @end deffn
  6787. @deffn Procedure error-object-message error-object
  6788. Returns the message encapsulated by error-object,
  6789. which must be a simple error object.
  6790. @end deffn
  6791. @deffn Procedure error-object-irritants error-object
  6792. Returns a list of the irritants (other arguments)
  6793. encapsulated by error-object, which must be a simple error object.
  6794. @end deffn
  6795. @subsection Named exceptions
  6796. These functions associate a symbol with exceptions
  6797. and handlers: A handler catches an exception if the symbol matches.
  6798. @deffn Procedure catch key thunk handler
  6799. Invoke @var{thunk} in the dynamic context of @var{handler} for
  6800. exceptions matching @var{key}. If thunk throws to the symbol @var{key},
  6801. then @var{handler} is invoked this way:
  6802. @example
  6803. (handler key args ...)
  6804. @end example
  6805. @var{key} may be a symbol. The @var{thunk} takes no
  6806. arguments. If @var{thunk} returns normally, that is the return value of
  6807. @code{catch}.
  6808. Handler is invoked outside the scope of its own @code{catch}. If
  6809. @var{handler} again throws to the same key, a new handler from further
  6810. up the call chain is invoked.
  6811. If the key is @code{#t}, then a throw to @emph{any} symbol will match
  6812. this call to @code{catch}.
  6813. @end deffn
  6814. @deffn Procedure throw key arg ...
  6815. Invoke the catch form matching @var{key}, passing the @var{arg}s to the
  6816. current @var{handler}.
  6817. If the key is a symbol it will match catches of the same
  6818. symbol or of @code{#t}.
  6819. If there is no handler at all, an error is signaled.
  6820. @end deffn
  6821. @subsection Native exception handling
  6822. @deffn Procedure primitive-throw exception
  6823. Throws the @var{exception}, which must be an instance of a sub-class
  6824. of @code{java.lang.Throwable}.
  6825. @end deffn
  6826. @deffn Syntax try-finally body handler
  6827. Evaluate @var{body}, and return its result.
  6828. However, before it returns, evaluate @var{handler}.
  6829. Even if @var{body} returns abnormally (by throwing an exception),
  6830. @var{handler} is evaluated.
  6831. (This is implemented just like Java's @code{try}-@code{finally}.
  6832. However, the current implementation does not duplicate the @var{handler}.)
  6833. @end deffn
  6834. @deffn Syntax try-catch body handler ...
  6835. Evaluate @var{body}, in the context of the given @var{handler} specifications.
  6836. Each @var{handler} has the form:
  6837. @example
  6838. @var{var} @var{type} @var{exp} ...
  6839. @end example
  6840. If an exception is thrown in @var{body}, the first @var{handler}
  6841. is selected such that the thrown exception is an instance of
  6842. the @var{handler}'s @var{type}. If no @var{handler} is selected,
  6843. the exception is propagated through the dynamic execution context
  6844. until a matching @var{handler} is found. (If no matching @var{handler}
  6845. is found, then an error message is printed, and the computation terminated.)
  6846. Once a @var{handler} is selected,
  6847. the @var{var} is bound to the thrown exception, and the @var{exp} in
  6848. the @var{handler} are executed. The result of the @code{try-catch}
  6849. is the result of @var{body} if no exception is thrown, or the
  6850. value of the last @var{exp} in the selected @var{handler} if an
  6851. exception is thrown.
  6852. (This is implemented just like Java's @code{try}-@code{catch}.)
  6853. @end deffn
  6854. @node Control features
  6855. @chapter Control features
  6856. @menu
  6857. * Mapping functions::
  6858. * Multiple values::
  6859. @end menu
  6860. @node Mapping functions
  6861. @section Mapping functions
  6862. The procedures @code{string-for-each} and @code{string-map}
  6863. are documented under @ref{Strings}.
  6864. The procedure @code{string-cursor-for-each} is documented under @ref{String Cursor API}.
  6865. @deffn Procedure map @var{proc} sequence@sub{1} sequence@sub{2} ...
  6866. @deffnx Procedure for-each @var{proc} sequence@sub{1} sequence@sub{2} ...
  6867. The @code{map} procedure applies @var{proc} element-wise to the elements
  6868. of the @var{sequence}s and returns a list of the results, in order.
  6869. The dynamic order in which @var{proc} is applied to
  6870. the elements of the @var{sequence}s is unspecified.
  6871. The @code{for-each} procedure does the same,
  6872. but is executed for the side-effects of @var{proc}, whose result (if any)
  6873. is discarded.
  6874. Unlike @code{map}, @code{for-each} is guaranteed to call @var{proc}
  6875. on the elements of the @var{sequences}s in order from the first element(s)
  6876. to the last.
  6877. The value returned by @code{for-each} is the void value.
  6878. Each @var{sequence} must be a generalized sequence.
  6879. (Traditionally, these arguments were restricted to lists,
  6880. but Kawa allows sequences, including vectors, Java arrays, and strings.)
  6881. If more than one @var{sequence} is given and not all
  6882. @var{sequence}s have the same length, the procedure terminates when the
  6883. shortest @var{sequence} runs out.
  6884. The @var{sequence}s can be infinite (for example circular lists),
  6885. but it is an error if all of them are infinite.
  6886. The @var{proc} must be a procedure that accepts as many arguments
  6887. as there are @var{sequence} arguments.
  6888. It is an error for @var{proc} to mutate any of the @var{sequence}s.
  6889. In the case of @code{map}, @var{proc} must return a single value.
  6890. @example
  6891. (map cadr '((a b) (d e) (g h)))
  6892. @result{} (b e h)
  6893. (map (lambda (n) (expt n n))
  6894. '(1 2 3 4 5))
  6895. @result{} (1 4 27 256 3125)
  6896. (map + ’(1 2 3) ’(4 5 6 7)) @result{} (5 7 9)
  6897. (let ((count 0))
  6898. (map (lambda (ignored)
  6899. (set! count (+ count 1))
  6900. count)
  6901. '(a b)))
  6902. @result{} (1 2) @i{or} (2 1)
  6903. @end example
  6904. The result of @code{map} is a list, even if the arguments are non-lists:
  6905. @example
  6906. (map +
  6907. #(3 4 5)
  6908. (float[] 0.5 1.5))
  6909. @result{} (3.5 5.5)
  6910. @end example
  6911. To get a vector result, use @code{vector-map}.
  6912. @example
  6913. (let ((v (make-vector 5)))
  6914. (for-each (lambda (i)
  6915. (vector-set! v i (* i i)))
  6916. '(0 1 2 3 4))
  6917. v)
  6918. @result{} #(0 1 4 9 16)
  6919. @end example
  6920. A string is considered a sequence of @code{character} values
  6921. (not 16-bit @code{char} values):
  6922. @example
  6923. (let ((v (make-vector 10 #\-)))
  6924. (for-each (lambda (i ch)
  6925. (vector-set! v i ch))
  6926. [0 <: ]
  6927. "Smile 😃!")
  6928. v)
  6929. @result{} #(#\S #\m #\i #\l #\e #\space #\x1f603 #\! #\- #\-)
  6930. @end example
  6931. @PerformanceNote{} These procedures are pretty well optimized.
  6932. For each @var{sequence} the compiler will by default create an
  6933. iterator.
  6934. @c FUTURE (This can be done without object allocation XXXX)
  6935. However, if the type of the @var{sequence} is known, the compiler will
  6936. inline the iteration code.
  6937. @end deffn
  6938. @deffn Procedure vector-map @var{proc} @vari{sequence} @varii{sequence} @dots{}
  6939. Same as the @code{map} procedure, except the result is a vector.
  6940. (Traditionally, these arguments were restricted to vectors,
  6941. but Kawa allows sequences, including lists, Java arrays, and strings.)
  6942. @example
  6943. (vector-map cadr '#((a b) (d e) (g h)))
  6944. @result{} #(b e h)
  6945. (vector-map (lambda (n) (expt n n))
  6946. '#(1 2 3 4 5))
  6947. @result{} #(1 4 27 256 3125)
  6948. (vector-map + '#(1 2 3) ’#(4 5 6 7))
  6949. @result{} #(5 7 9)
  6950. (let ((count 0))
  6951. (vector-map
  6952. (lambda (ignored)
  6953. (set! count (+ count 1))
  6954. count)
  6955. '#(a b)))
  6956. @result{} #(1 2) @i{or} #(2 1)
  6957. @end example
  6958. @end deffn
  6959. @deffn Procedure vector-for-each @var{proc} @vari{vector} @varii{vector} @dots{}
  6960. Mostly the same as @code{for-each},
  6961. however the arguments should be generalized vectors.
  6962. Specifically, they should implement @code{java.util.List}
  6963. (which both regular vectors and uniform vectors do).
  6964. The @var{vectors} should also be efficiently indexable.
  6965. (Traditionally, these arguments were restricted to vectors,
  6966. but Kawa allows sequences, including lists, Java arrays, and strings.)
  6967. @example
  6968. (let ((v (make-list 5)))
  6969. (vector-for-each
  6970. (lambda (i) (list-set! v i (* i i)))
  6971. '#(0 1 2 3 4))
  6972. v)
  6973. @result{} (0 1 4 9 16)
  6974. @end example
  6975. @end deffn
  6976. @node Multiple values
  6977. @section Multiple values
  6978. The multiple-value feature was added in R5RS.
  6979. @deffn Procedure values object ...
  6980. Delivers all of its arguments to its continuation.
  6981. @end deffn
  6982. @deffn Procedure call-with-values producer consumer
  6983. Calls its @var{producer} argument with no arguments and a
  6984. continuation that, when passed some values, calls the
  6985. @var{consumer} procedure with those values as arguments.
  6986. @example
  6987. (call-with-values (lambda () (values 4 5))
  6988. (lambda (a b) b))
  6989. @result{} 5
  6990. (call-with-values * -) @result{} -1
  6991. @end example
  6992. @PerformanceNote{} If either the @var{producer} or @var{consumer} is a
  6993. fixed-arity lambda expression, it is inlined.
  6994. @end deffn
  6995. @deffn Syntax define-values @stxref{formals} @stxref{expression}
  6996. It is an error if a variable appears more than once in the
  6997. set of @meta{formals}.
  6998. The @meta{expression} is evaluated, and the @meta{formals}
  6999. are bound to the return values in the same way that the @meta{formals} in
  7000. a @code{lambda} expression are matched to the arguments in a procedure call.
  7001. @example
  7002. (define-values (x y) (integer-sqrt 17))
  7003. (list x y) @result{} (4 1)
  7004. (let ()
  7005. (define-values (x y) (values 1 2))
  7006. (+ x y))
  7007. @result{} 3
  7008. @end example
  7009. @end deffn
  7010. @deffn Syntax let-values @stxlit{((}@stxref{formals} @stxref{expression}@stxlit{)} ...@stxlit{)} @stxref{body}
  7011. Each @var{formals} should be a formal arguments list, as for a @code{lambda}.
  7012. The @var{expression}s are evaluated in the current environment, the
  7013. variables of the @var{formals} are bound to fresh locations, the return
  7014. values of the @var{expression}s are stored in the variables, the
  7015. @var{body} is evaluated in the extended environment, and the values of
  7016. the last expression of @var{body} are returned. The @var{body} is a
  7017. "tail body", cf section 3.5 of the R5RS.
  7018. The matching of each @var{formals} to values is as for the matching of
  7019. @var{formals} to arguments in a @code{lambda} expression, and it is an
  7020. error for an @var{expression} to return a number of values that does not
  7021. match its corresponding @var{formals}.
  7022. @example
  7023. (let-values (((a b . c) (values 1 2 3 4)))
  7024. (list a b c)) @result{} (1 2 (3 4))
  7025. (let ((a 'a) (b 'b) (x 'x) (y 'y))
  7026. (let-values (((a b) (values x y))
  7027. ((x y) (values a b)))
  7028. (list a b x y))) @result{} (x y a b)
  7029. @end example
  7030. @end deffn
  7031. @deffn Syntax let*-values @stxlit{((}@stxref{formals} @stxref{expression}@stxlit{)} ...@stxlit{)} @stxref{body}
  7032. Each @var{formals} should be a formal arguments list as for a
  7033. @code{lambda} expression.
  7034. @code{let*-values} is similar to @code{let-values}, but the bindings are
  7035. performed sequentially from left to right, and the region of a binding
  7036. indicated by (@var{formals} @var{expression}) is that part of the
  7037. @code{let*-values} expression to the right of the binding. Thus the
  7038. second binding is done in an environment in which the first binding is
  7039. visible, and so on.
  7040. @example
  7041. (let ((a 'a) (b 'b) (x 'x) (y 'y))
  7042. (let*-values (((a b) (values x y))
  7043. ((x y) (values a b)))
  7044. (list a b x y))) @result{} (x y x y)
  7045. @end example
  7046. @end deffn
  7047. @deffn Syntax receive @stxref{formals} @stxref{expression} @stxref{body}
  7048. This convenience
  7049. form (from @uref{http://srfi.schemers.org/srfi-8/srfi-8.html, SRFI-8})
  7050. is equivalent to:
  7051. @example
  7052. (let-values ((@var{formals} @var{expression})) @var{body})
  7053. @end example
  7054. For example:
  7055. @example
  7056. (receive a (values 1 2 3 4)
  7057. (reverse a)) @result{} (4 3 2 1)
  7058. (receive (a b . c) (values 1 2 3 4)
  7059. (list a b c)) @result{} (1 2 (3 4))
  7060. (let ((a 'a) (b 'b) (x 'x) (y 'y))
  7061. (receive (a b) (values x y)
  7062. (receive (x y) (values a b)
  7063. (list a b x y)))) @result{} (x y x y)
  7064. @end example
  7065. @end deffn
  7066. @deffn Procedure values-append arg1 ...
  7067. The values resulting from evaluating each argument are appended
  7068. together.
  7069. @end deffn
  7070. @node Symbols and namespaces
  7071. @chapter Symbols and namespaces
  7072. An identifier is a name that appears in a program.
  7073. A symbol is an object representing a string that cannot be
  7074. modified. This string is called the symbol's name. Unlike strings, two
  7075. symbols whose names are spelled the same way are indistinguishable.
  7076. A symbol is immutable (unmodifiable) and normally viewed as atomic.
  7077. Symbols are useful for many applications; for instance, they may be
  7078. used the way enumerated values are used in other languages.
  7079. In addition to the simple symbols of standard Scheme, Kawa
  7080. also has compound (two-part) symbols.
  7081. @menu
  7082. * Simple symbols::
  7083. * Namespaces::
  7084. * Keywords::
  7085. * Special named constants::
  7086. @end menu
  7087. @node Simple symbols, Namespaces, , Symbols and namespaces
  7088. @section Simple symbols
  7089. Simple symbols have no properties other than their name, an immutable string.
  7090. They have the useful property that two simple symbols
  7091. are identical (in the sense of @func{eq?}, @func{eqv?} and
  7092. @func{equal?}) if and only if their names are spelled the same way. A
  7093. symbol literal is formed using @func{quote}.
  7094. @deffn Procedure {symbol?} @var{obj}
  7095. Return @true{} if @var{obj} is a symbol, @false{} otherwise.
  7096. @example
  7097. (symbol? 'foo) @result{} #t
  7098. (symbol? (car '(a b))) @result{} #t
  7099. (symbol? "bar") @result{} #f
  7100. (symbol? 'nil) @result{} #t
  7101. (symbol? '()) @result{} #f
  7102. (symbol? #f) @result{} #f
  7103. @end example
  7104. @end deffn
  7105. @deffn Procedure {symbol->string} @var{symbol}
  7106. Return the name of @var{symbol} as an immutable string.
  7107. @example
  7108. (symbol->string 'flying-fish) @result{} "flying-fish"
  7109. (symbol->string 'Martin) @result{} "Martin"
  7110. (symbol->string (string->symbol "Malvina")) @result{} "Malvina"
  7111. @end example
  7112. @end deffn
  7113. @deffn Procedure {string->symbol} @var{string}
  7114. Return the symbol whose name is @var{string}.
  7115. @example
  7116. (eq? 'mISSISSIppi 'mississippi)
  7117. @result{} #f
  7118. (string->symbol "mISSISSIppi")
  7119. @result{} the symbol with name "mISSISSIppi"
  7120. (eq? 'bitBlt (string->symbol "bitBlt"))
  7121. @result{} #t
  7122. (eq? 'JollyWog (string->symbol (symbol->string 'JollyWog)))
  7123. @result{} #t
  7124. (string=? "K. Harper, M.D."
  7125. (symbol->string (string->symbol "K. Harper, M.D.")))
  7126. @result{} #t
  7127. @end example
  7128. @end deffn
  7129. @node Namespaces, Keywords, Simple symbols, Symbols and namespaces
  7130. @section Namespaces and compound symbols
  7131. Different applications may want to use the same symbol
  7132. to mean different things. To avoid such @dfn{name clashes}
  7133. we can use @dfn{compound symbols}, which have two string parts:
  7134. a @dfn{local name} and a @dfn{namespace URI}.
  7135. The namespace-uri can be any string, but it is
  7136. recommended that it have the form of an absolute
  7137. @uref{http://en.wikipedia.org/wiki/Uniform_Resource_Identifier,URI}.
  7138. It would be too verbose to write the full URI all the
  7139. time, so one usually uses a @dfn{namespace prefix}
  7140. (namespace alias) as a short local alias to refer to a
  7141. namespace URI.
  7142. Compound symbols are usually written using the infix colon operator:
  7143. @example
  7144. @var{prefix}@stxlit{:}@var{local-name}
  7145. @end example
  7146. where @var{prefix} is a namespace alias bound
  7147. to some (lexically-known) namespace URI.
  7148. Compound symbols are used for namespace-aware XML processing.
  7149. @subsection Namespace objects
  7150. A @dfn{namespace} is a mapping from strings to symbols.
  7151. The string is the local-name of the resulting symbol.
  7152. A namespace is similar to a Common Lisp @dfn{package}.
  7153. A namespace has a namespace-uri, which a string;
  7154. it is recommended that it have the form of an absolute URI.
  7155. A namespace may optionally have a prefix, which is a string used
  7156. when printing out symbols belonging to the namespace.
  7157. (If you want ``equivalent symbols'' (i.e. those that have the same
  7158. local-name and same uri) to be the identical symbol object, then
  7159. you should use namespaces whose prefix is the empty string.)
  7160. @deffn Constructor namespace name [prefix]
  7161. Return a namespace with the given @var{name} and @var{prefix}.
  7162. If no such namespace exists, create it.
  7163. The @var{namespace-name} is commonly a URI, especially when working with XML,
  7164. in which case it is called a @var{namespace-uri}. However, any non-empty
  7165. string is allowed.
  7166. The prefix can be a string or a simple symbol.
  7167. (If a symbol is used, then the symbol's local-name is used.)
  7168. The default for @var{prefix} is the empty string.
  7169. Multiple calls with the same arguments will yield the same namespace object.
  7170. @end deffn
  7171. The reader macro @code{#,namespace} is equivalent to the
  7172. @code{namespace} function, but it is invoked at read-time:
  7173. @example
  7174. #,(namespace "http://www.w3.org/1999/XSL/Transform" xsl)
  7175. (eq? #,(namespace "foo") (namespace "foo")) @result{} #t
  7176. @end example
  7177. The form @code{(,#namespace "" "")} returns the default @dfn{empty namespace},
  7178. which is used for simple symbols.
  7179. @deffn Procedure namespace-uri namespace
  7180. Return the namespace-uri of the argument @var{namespace}, as a string.
  7181. @end deffn
  7182. @deffn Procedure namespace-prefix namespace
  7183. Return the namespace prefix of the argument @var{namespace}, as a string.
  7184. @end deffn
  7185. @subsection Compound symbols
  7186. A compound symbol is one that belongs to a namespace other than the
  7187. default empty namespace, and (normally) has a non-empty namespace uri.
  7188. (It is possible for a symbol to belong to a non-default namespace
  7189. and have an empty namespace uri, but that is not recommended.)
  7190. @deffn Constructor symbol local-name namespace-spec
  7191. @deffnx Constructor symbol local-name [uri [prefix]]
  7192. Construct a symbol with the given @var{local-name} and namespace.
  7193. If @var{namespace-spec} is a namespace object, then find (or, if needed,
  7194. construct) a symbol with the given @var{local-name} belonging to the
  7195. namespace. Multiple calls to @code{symbol} with the same namespace
  7196. and @var{local-name} will yield the same symbol object.
  7197. If uri is a string (optionally followed by a prefix),
  7198. then:
  7199. @example
  7200. (symbol lname uri [prefix])
  7201. @end example
  7202. is equivalent to:
  7203. @example
  7204. (symbol lname (namespace uri [prefix]))
  7205. @end example
  7206. Using @code{#t} for the @var{namespace-spec} is equivalent to
  7207. using the empty namespace @code{#,(namespace "")}.
  7208. Using @code{#!null} or @code{#f} for the @var{namespace-spec}
  7209. creates an @var{uninterned} symbol, which does not belong to
  7210. any namespace.
  7211. @end deffn
  7212. @deffn Procedure symbol-local-name symbol
  7213. Return the local name of the argument symbol, as an immutable string.
  7214. (The string is interned, except in the case of an uninterned symbol.)
  7215. @end deffn
  7216. @deffn Procedure symbol-prefix symbol
  7217. Return the prefix of the argument symbol, as an immutable
  7218. (and interned) string.
  7219. @end deffn
  7220. @deffn Procedure symbol-namespace-uri symbol
  7221. Return the namespace uri of the argument symbol, as an immutable
  7222. (and interned) string.
  7223. @end deffn
  7224. @deffn Procedure symbol-namespace symbol
  7225. Return the namespace object (if any) of the argument symbol.
  7226. Returns @code{#!null} if the symbol is uninterned.
  7227. @end deffn
  7228. @deffn Procedure {symbol=?} @vari{symbol} @varii{symbol} @variii{symbol} @dots{}
  7229. Return @true{} if the symbols are equivalent as symbols,
  7230. i.e., if their local-names and namespace-uris are the same.
  7231. They may have different values of @code{symbol-prefix} and @code{symbol-namespace}.
  7232. If a symbol is uninterned (or is @code{#!null}) then @code{symbol=?}
  7233. returns the same result as @code{eq?}.
  7234. @end deffn
  7235. Two symbols are @code{equal?} or @code{eqv?} if they're @code{symbol=?}.
  7236. @subsection Namespace aliases
  7237. A namespace is usually referenced using a shorter @dfn{namespace alias},
  7238. which is is a lexical definition that binds a namespace prefix
  7239. to a namespace object (and thus a namespace uri).
  7240. This allows using compound symbols as identifiers in Scheme programs.
  7241. @deffn Syntax define-namespace name namespace-name
  7242. Defines @var{name} as a @dfn{namespace prefix} - a lexically scoped
  7243. "nickname" for the namespace
  7244. whose full name is @var{namespace-name}, which should be a non-empty
  7245. string literal.
  7246. It is customary for the string have syntactic form of
  7247. an absolute @uref{http://en.wikipedia.org/wiki/Uniform_Resource_Identifier,URI},
  7248. but any non-empty string is acceptable and is used without
  7249. further interpretation.
  7250. Any symbols in the scope of this definitions that contain a colon, and
  7251. where the part before the colon matches the @var{name} will be
  7252. treated as being in the package/namespace whose global unique name
  7253. is the @var{namespace-name}.
  7254. Has mostly the same effect as:
  7255. @example
  7256. (define-constant @var{name} #,(namespace @var{namespace-name})
  7257. @end example
  7258. However, using @code{define-namespace} (rather than @code{define-constant})
  7259. is recommended if you want to use compound symbols as names of
  7260. variables, especially local variables, or if you want to quote
  7261. compound symbols.
  7262. Note that the prefix is only visible lexically: it is not
  7263. part of the namespace, or thus indirectly the symbols, and
  7264. so is not available when printing the symbol.
  7265. You might consider using @code{define-xml-namespace} as an alternative.
  7266. A namespace is similar to a Common Lisp package,
  7267. and the @var{namespace-name} is like the name of the package.
  7268. However, a namespace alias belongs to the lexical scope,
  7269. while a Common Lisp package nickname is global
  7270. and belongs to the package itself.
  7271. If the namespace-name starts with the string @code{"class:"}, then the
  7272. @var{name} can be used for invoking Java methods
  7273. (@pxref{Method operations}) and accessing fields (@pxref{Field operations}).
  7274. You can use a namespace as an abbreviation or renaming of a
  7275. class name, but as a matter of style @code{define-alias} is preferred.
  7276. @end deffn
  7277. @deffn Syntax define-private-namespace name namespace-name
  7278. Same as @code{define-namespace}, but the prefix @var{name}
  7279. is local to the current module.
  7280. @end deffn
  7281. For example, you might have a set of a geometry definitions
  7282. defined under the namespace-uri @code{"http://foo.org/lib/geometry"}:
  7283. @example
  7284. (define-namespace geom "http://foo.org/lib/geometry")
  7285. (define (geom:translate x y)
  7286. (java.awt.geom.AffineTransform:getTranslateInstance x y))
  7287. (define geom:zero (geom:translate 0 0))
  7288. geom:zero
  7289. @result{} AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
  7290. @end example
  7291. You could have some other definitions for complex math:
  7292. @example
  7293. (define-namespace complex "http://foo.org/lib/math/complex")
  7294. (define complex:zero +0+0i)
  7295. @end example
  7296. You can use a namespace-value directly in a compound name:
  7297. @example
  7298. (namespace "http://foo.org/lib/geometry"):zero
  7299. @result{} AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
  7300. @end example
  7301. The variation @code{define-xml-namespace} is used for @ref{Creating XML nodes}.
  7302. @deffn Syntax define-xml-namespace prefix "namespace-uri"
  7303. Defines a namespace with prefix @var{prefix} and URI @var{namespace-uri}.
  7304. This is similar to @code{define-namespace} but with two important differences:
  7305. @itemize
  7306. @item
  7307. Every symbol in the namespace automatically maps to
  7308. an element-constructor-type, as with the @code{html} namespace.
  7309. @item
  7310. The @var{prefix} is a component of the namespace object, and
  7311. hence indirectly of any symbols belongining to the namespace.
  7312. @end itemize
  7313. Thus the definition is roughly equivalent to:
  7314. @example
  7315. (define-constant @var{name} #,(namespace @var{namespace-name name})
  7316. @end example
  7317. along with an infinite set of definitions, for every possible @var{tag}:
  7318. @example
  7319. (define (name:@var{tag} . rest) (apply make-element 'name:@var{tag} rest))
  7320. @end example
  7321. @end deffn
  7322. @example
  7323. $ kawa --output-format xml
  7324. #|kawa:1|# @kbd{(define-xml-namespace na "Namespace1")}
  7325. #|kawa:2|# @kbd{(define-xml-namespace nb "Namespace1")}
  7326. #|kawa:3|# @kbd{(define xa (na:em "Info"))}
  7327. #|kawa:4|# @kbd{xa}
  7328. <na:em xmlns:na="Namespace1">Info</na:em>
  7329. #|kawa:5|# @kbd{(define xb (nb:em "Info"))}
  7330. #|kawa:6|# @kbd{xa}
  7331. <nb:em xmlns:nb="Namespace1">Info</nb:em>
  7332. @end example
  7333. Note that the prefix is part of the qualified name
  7334. (it is actually part of the namespace object),
  7335. and it is used when printing the tag.
  7336. Two qualified names (symbols) that have the same
  7337. local-name and the same namespace-name are considered
  7338. equal, even if they have different prefix. You can think of
  7339. the prefix as annotation used when printing, but not
  7340. otherwise part of the ``meaning'' of a compound symbol.
  7341. They are the same object if they also have the same prefix.
  7342. This is an important difference from traditional Lisp/Scheme symbols,
  7343. but it is how XML QNames work.
  7344. @example
  7345. #|kawa:7|# (instance? xb na:em)
  7346. true
  7347. #|kawa:8|# (eq? 'na:em 'nb:em)
  7348. false
  7349. #|kawa:9|# (equal? 'na:em 'nb:em)
  7350. true
  7351. #|kawa:10|# (eqv? 'na:em 'nb:em)
  7352. true
  7353. @end example
  7354. (Note that @code{#t} is printed as @code{true} when using XML formatting.)
  7355. The predefined @code{html} prefix could be defined thus:
  7356. @example
  7357. (define-xml-namespace html "http://www.w3.org/1999/xhtml")
  7358. @end example
  7359. @node Keywords, Special named constants, Namespaces, Symbols and namespaces
  7360. @section Keywords
  7361. Keywords are similar to symbols.
  7362. They are used mainly for specifying keyword arguments.
  7363. Historically keywords have been self-evaluating (you did not need to
  7364. quote them). This has changed: you must quote a keyword if you
  7365. want a literal keyword value, and not quote it if it is used
  7366. as a keyword argument.
  7367. @display
  7368. @stxdef{keyword} @stxref{identifier}@stxlit{:}
  7369. | @stxlit{#:}@stxref{identifier}
  7370. @end display
  7371. The two syntaxes have the same meaning: The former is nicer-looking;
  7372. the latter is more portable (and required if you use the
  7373. @code{--r7rs} command-line flag).
  7374. @quotation
  7375. @emph{Details:}
  7376. In r7rs and other Scheme standards the colon character
  7377. does not have any special meaning, so @code{foo:} or @code{foo:bar}
  7378. are just regular identifiers. Therefore some other Scheme variants
  7379. that have keywords (including Guile and Racket) use the @code{#:} syntax.
  7380. Kawa has some hacks so that @emph{most}
  7381. standard Scheme programs that have colons in identifiers will work.
  7382. However, for best compatibility, use the @code{--r7rs} command-line flag
  7383. (which turns colon into a regular character in a symbol), and the
  7384. @code{#:} syntax.
  7385. @end quotation
  7386. A keyword is a single token; therefore no whitespace is allowed between
  7387. the @var{identifier} and the colon or after the @code{#:};
  7388. these characters are not considered part of the name of the keyword.
  7389. @deffn Procedure keyword? obj
  7390. Return @code{#t} if @var{obj} is a keyword, and otherwise returns @code{#f}.
  7391. @end deffn
  7392. @deffn Procedure keyword->string keyword
  7393. Returns the name of @var{keyword} as a string.
  7394. The name does not include the final @code{#\:}.
  7395. @end deffn
  7396. @deffn Procedure string->keyword string
  7397. Returns the keyword whose name is @var{string}.
  7398. (The @var{string} does not include a final @code{#\:}.)
  7399. @end deffn
  7400. @node Special named constants, , Keywords, Symbols and namespaces
  7401. @section Special named constants
  7402. @defvr Constant #!optional
  7403. Special self-evaluating literal used in lambda parameter lists
  7404. before optional parameters.
  7405. @end defvr
  7406. @defvr Constant #!rest
  7407. Special self-evaluating literal used in lambda parameter lists
  7408. before the rest parameter.
  7409. @end defvr
  7410. @defvr Constant #!key
  7411. Special self-evaluating literal used in lambda parameter lists
  7412. before keyword parameters.
  7413. @end defvr
  7414. @defvr Constant #!eof
  7415. The end-of-file object.
  7416. Note that if the Scheme reader sees this literal at top-level,
  7417. it is returned literally. This is indistinguishable from
  7418. coming to the end of the input file. If you do not want to end reading,
  7419. but want the actual value of @code{#!eof}, you should quote it.
  7420. @end defvr
  7421. @defvr Constant #!void
  7422. The void value. Same as @code{(values)}.
  7423. If this is the value of an expression in a read-eval-print loop,
  7424. nothing is printed.
  7425. @end defvr
  7426. @defvr Constant #!null
  7427. The Java @code{null} value. This is not really a Scheme value,
  7428. but is useful when interfacing to low-level Java code.
  7429. @end defvr
  7430. @node Procedures, Numbers, Symbols and namespaces, Top
  7431. @chapter Procedures
  7432. @menu
  7433. * Application and Arguments Lists::
  7434. * Extended formals::
  7435. * Procedure properties::
  7436. * Generic procedures::
  7437. * Partial application::
  7438. @end menu
  7439. @node Application and Arguments Lists
  7440. @section Application and Arguments Lists
  7441. When a procedure is called, the actual argument expressions are evaluated,
  7442. and the resulting values becomes the actual argument list.
  7443. This is then matched against the formal parameter list
  7444. in the procedure definition, and (assuming they match)
  7445. the procedure body is called.
  7446. @anchor{argument list}
  7447. @subsection Arguments lists
  7448. An argument list has three parts:
  7449. @itemize @bullet
  7450. @item
  7451. Zero or more @dfn{prefix arguments}, each of which is a value.
  7452. These typically get bound to named required or optional formal parameters,
  7453. but can also get bound to patterns.
  7454. @item
  7455. Zero or more @dfn{keyword arguments}, each of which is a keyword
  7456. (an identifier specified with keyword syntax) combined with a value.
  7457. These are bound to either named keyword formal parameters, or
  7458. bundled in with a rest parameter.
  7459. @item
  7460. Zero or more @dfn{postfix arguments}, each of which is a value.
  7461. These are usually bound to a ``rest'' formal parameter, which
  7462. receives any remaining arguments.
  7463. If there are no keyword arguments, then it ambiguous where
  7464. prefix arguments end and where postfix arguments start.
  7465. This is normally not a problem: the called procedure can
  7466. split them up however it wishes.
  7467. @end itemize
  7468. Note that all keyword arguments have to be grouped together:
  7469. It is not allowed to have a keyword argument followed by a plain
  7470. argument followed by a keyword argument.
  7471. The argument list is constructed by evaluating each @stxref{operand}
  7472. of the @stxref{procedure-call} in order:
  7473. @table @asis
  7474. @item @var{expression}
  7475. The @var{expression} is evaluated, yielding a single value
  7476. that becomes a prefix or postfix argument.
  7477. @item @var{keyword} @var{expression}
  7478. The @var{expression} is evaluated. The resulting value combined
  7479. with the @var{keyword} becomes a keyword argument.
  7480. @item @stxlit{@@}@var{expression}
  7481. The @var{expression} is evaluated.
  7482. The result must be a sequence - a list, vector, or primitive array.
  7483. The values of the sequence are appended to the resulting argument list.
  7484. Keyword arguments are not allowed.
  7485. @item @stxlit{@@:}@var{expression}
  7486. The @var{expression} is evaluted.
  7487. The result can be a sequence;
  7488. a hash table (viewed as a collection of (keyword,value) pairs);
  7489. or an @dfn{explicit argument list} object, which is a sequence of values
  7490. @emph{or} keyword arguments.
  7491. The values and keyword arguments
  7492. are appended to the resulting argument list, though subject to the restriction
  7493. that keyword arguments must be adjacent in the resulting argument list.
  7494. @end table
  7495. @anchor{Explicit argument list objects}
  7496. @subsection Explicit argument list objects
  7497. Sometimes it is useful to create an argument list out of
  7498. pieces, take argument lists apart, iterate over them,
  7499. and generally treat an argument list as an actual first-class value.
  7500. Explicit argument list objects can take multiple forms.
  7501. The simplest is a sequence: a list, vector, or primitive array.
  7502. Each element of the list becomes a value in the resulting argument list.
  7503. @example
  7504. (define v1 '(a b c))
  7505. (define v2 (int[] 10 11 12 13))
  7506. (list "X" @@v1 "Y" @@v2 "Z")
  7507. @result{} ("X" a b c "Y" 10 11 12 13 "Z")
  7508. @end example
  7509. Things get more complicated once keywords are involved.
  7510. An explicit argument list with keywords is only allowed
  7511. when using the @code{@@:} splicing form,
  7512. not the @code{@@} form. It can be either
  7513. a hash table, or the types @code{arglist} or @code{argvector}.
  7514. @quotation
  7515. @emph{Design note:} An argument list with keywords is straightforward
  7516. in Common Lisp and some Scheme implementations (including order versions of
  7517. Kawa): It's just a list some of whose @code{car} cells are keyword objects.
  7518. The problem with this model is neither a human or the compiler can
  7519. reliably tell when an argument is a keyword, since any variable
  7520. might have been assigned a keyword. This limits performance and
  7521. error checking.
  7522. @end quotation
  7523. A hash table (anything the implements @code{java.util.Map})
  7524. whose keys are strings or keyword objects is
  7525. interpreted as a sequence of keyword arguments,
  7526. using the hash-table keys and values.
  7527. @deffn Type argvector
  7528. @deffnx Constructor argvector @arbno{@stxref{operand}}
  7529. List of arguments represented as an immutable vector.
  7530. A keyword argument takes two elements in this vector:
  7531. A keyword object, followed by the value.
  7532. @example
  7533. (define v1 (argvector 1 2 k1: 10 k2: 11 98 99))
  7534. (v1 4) @result{} 'k2
  7535. (v1 5) @result{} 11
  7536. @end example
  7537. When @code{v1} is viewed as a vector it
  7538. is equivalent to @code{(vector 1 2 'k1: 10 'k2: 11 98 99)}.
  7539. (Note in this case the keywords need to be quoted, since
  7540. the @code{vector} constructor does not take keyword arguments.)
  7541. However, the @code{argvector} ``knows'' which arguments
  7542. are actually keyword arguments, and can be examined using the
  7543. @code{(kawa arglist)} library discussed below:
  7544. @example
  7545. (arglist-key-count (argvector 1 x: 2 3)) @result{} 1
  7546. (arglist-key-count (argvector 1 'x: 2 3)) @result{} 0
  7547. (arglist-key-count (vector 1 'x: 2 3)) @result{} 0
  7548. @end example
  7549. In this case:
  7550. @example
  7551. (fun 'a @@:v1)
  7552. @end example
  7553. is equivalent to:
  7554. @example
  7555. (fun 'a 1 2 k1: 10 k2: 11 98 99)
  7556. @end example
  7557. @end deffn
  7558. @deffn Type arglist
  7559. @deffnx Constructor arglist @arbno{@stxref{operand}}
  7560. Similar to @code{argvector}, but compatible with @code{list}.
  7561. If there are no keyword arguments, returns a plain list.
  7562. If there is at least one keyword argument creates a special
  7563. @code{gnu.mapping.ArgListPair} object that implements the
  7564. usual @code{list} properties but internally wraps a @code{argvector}.
  7565. @end deffn
  7566. @anchor{Argument list library}
  7567. @subsection Argument list library
  7568. @example
  7569. (import (kawa arglist))
  7570. @end example
  7571. In the following, @var{args} is an @code{arglist} or @code{argvector}
  7572. (or in general any object that implement @code{gnu.mapping.ArgList}).
  7573. Also, @var{args} can be any sequence, in which case it
  7574. behaves like an @code{argvector} that has no keyword arguments.
  7575. @deffn Procedure arglist-walk args proc
  7576. Call @var{proc} once, in order, for each argument in @var{args}.
  7577. The @var{proc} is called with two arguments,
  7578. corresponding to @code{(arglist-key-ref @var{args} @var{i})}
  7579. and @code{(arglist-arg-ref @var{args} @var{i})} for each @var{i} from 0
  7580. up to @code{(arglist-arg-count @var{args})} (exclusive).
  7581. I.e. the first argument is either @code{#!null} or the keyword (as a string);
  7582. the second argument is the corresponding argument value.
  7583. @example
  7584. (define (print-arguments args #!optional (out (current-output-port)))
  7585. (arglist-walk args
  7586. (lambda (key value)
  7587. (if key (format out "key: ~a value: ~w~%" key value)
  7588. (format out "value: ~w~%" value)))))
  7589. @end example
  7590. @end deffn
  7591. @deffn Procedure arglist-key-count args
  7592. Return the number of keyword arguments.
  7593. @end deffn
  7594. @deffn Procedure arglist-key-start args
  7595. Number of prefix arguments, which is the number of arguments before
  7596. the first keyword argument.
  7597. @end deffn
  7598. @deffn Procedure arglist-arg-count args
  7599. Return the number of arguments.
  7600. The count includes the number of keyword arguments, but not the actual keywords.
  7601. @example
  7602. (arglist-arg-count (arglist 10 11 k1: -1 19)) @result{} 4
  7603. @end example
  7604. @end deffn
  7605. @deffn Procedure arglist-arg-ref args index
  7606. Get the @var{index}'th argument value.
  7607. The @var{index} counts keyword argument values, but not the keywords themselves.
  7608. @example
  7609. (arglist-arg-ref (arglist 10 11 k1: -1 19) 2) @result{} -1
  7610. (arglist-arg-ref (arglist 10 11 k1: -1 19) 3) @result{} 19
  7611. @end example
  7612. @end deffn
  7613. @deffn Procedure arglist-key-ref args index
  7614. The @var{index} counts arguments like @code{arglist-arg-ref} does.
  7615. If this is a keyword argument, return the corresponding keyword
  7616. (as a string); otherwise, return @code{#!null} (which counts as false).
  7617. @example
  7618. (arglist-key-ref (argvector 10 11 k1: -1 k2: -2 19) 3) @result{} "k2"
  7619. (arglist-key-ref (argvector 10 11 k1: -1 k2: -2 19) 4) @result{} #!null
  7620. @end example
  7621. @end deffn
  7622. @deffn Procedure arglist-key-index args key
  7623. Search for a keyword matching @var{key} (which must be an interned string).
  7624. If there is no such keyword, return -1.
  7625. Otherwise return the keyword's index as an argument to @code{arglist-key-ref}.
  7626. @end deffn
  7627. @deffn Procedure arglist-key-value args key default
  7628. Search for a keyword matching @var{key} (which must be an interned string).
  7629. If there is no such keyword, return the @var{default}.
  7630. Otherwise return the corresponding keyword argument's value.
  7631. @end deffn
  7632. @subsection Apply procedures
  7633. @deffn Procedure apply proc @arbno{argi} argrest
  7634. @var{Argrest} must be a sequence (list, vector, or string) or a
  7635. primitive Java array.
  7636. (This is an extension over standard Scheme, which requires that
  7637. @var{args} be a list.)
  7638. Calls the @var{proc} (which must be a procedure), using as arguments
  7639. the @var{argi}... values plus all the elements of @var{argrest}.
  7640. Equivalent to: @code{(}@var{proc} @arbno{@var{argi}} @code{@@}@var{argrest}@code{)}.
  7641. @end deffn
  7642. @deffn Syntax constant-fold proc arg1 ...
  7643. Same as @code{(@var{proc} @var{arg1} ...)}, unless @var{proc} and
  7644. all the following arguments are compile-time constants.
  7645. (That is: They are either constant, or symbols that have a global
  7646. binding and no lexical binding.) In that case, @var{proc}
  7647. is applied to the arguments at compile-time, and the result replaces
  7648. the @code{constant-fold} form. If the application raises an exception,
  7649. a compile-time error is reported.
  7650. For example:
  7651. @example
  7652. (constant-fold vector 'a 'b 'c)
  7653. @end example
  7654. is equivalent to @code{(quote #(a b c))}, assuming @code{vector}
  7655. has not been re-bound.
  7656. @end deffn
  7657. @c The node name 'Extended formals' is klunky, but kept for compatibility
  7658. @node Extended formals
  7659. @section Lambda Expressions and Formal Parameters
  7660. A @code{lambda} expression evaluates to a procedure.
  7661. The environment in effect when the @code{lambda} expression was
  7662. evaluated is remembered as part of the procedure. When
  7663. the procedure is later called with some actual arguments,
  7664. the environment in which the @code{lambda} expression was evaluated
  7665. will be extended by binding the variables in the formal
  7666. argument list to fresh locations, and the corresponding actual
  7667. argument values will be stored in those locations.
  7668. (A @dfn{fresh location} is one that is distinct from every previously
  7669. existing location.) Next, the expressions in the body of the
  7670. lambda expression will be evaluated
  7671. sequentially in the extended environment. The results of
  7672. the last expression in the body will be returned as the results
  7673. of the procedure call.
  7674. @example
  7675. (lambda (x) (+ x x)) @result{} @emph{a procedure}
  7676. ((lambda (x) (+ x x)) 4) @result{} 8
  7677. (define reverse-subtract
  7678. (lambda (x y) (- y x)))
  7679. (reverse-subtract 7 10) @result{} 3
  7680. (define add4
  7681. (let ((x 4))
  7682. (lambda (y) (+ x y))))
  7683. (add4 6) @result{} 10
  7684. @end example
  7685. The formal arguments list of a lambda expression has some
  7686. extensions over standard Scheme:
  7687. Kawa borrows the extended formal argument list of DSSSL,
  7688. and allows you to declare the type of the parameter.
  7689. More generally, you can use @ref{Variables and Patterns,patterns}.
  7690. @display
  7691. @stxdef{lambda-expression} @stxlit{(lambda} @stxref{formals} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}@stxlit{)}
  7692. @stxdef{opt-return-type} [@stxlit{::} @stxref{type}]
  7693. @stxdef{formals} @stxlit{(}@stxref{formal-arguments}@stxlit{)} | @stxref{rest-arg}
  7694. @end display
  7695. An @var{opt-return-type} specifies the return type of the procedure:
  7696. The result of evaluating the @var{body} is coerced to the specified @var{type}.
  7697. @emph{Deprecated}: If the first form of the function body is an unbound
  7698. identifier of the form @code{<TYPE>} (that is the first character
  7699. is @samp{<} and the last is @samp{>}), then that is another way to specify the
  7700. function's return type.
  7701. See @ref{Procedure properties,properties} for
  7702. how to set and use an @var{option-pair}.
  7703. The @ref{Definitions,@code{define}} form has a short-hand that combines
  7704. a lambda definition with binding the lambda to a variable:
  7705. @example
  7706. @b{(define (}@var{name} @stxref{formal-arguments}@b{)} @stxref{opt-return-type} @stxref{body}@b{)}
  7707. @end example
  7708. @display
  7709. @stxdef{formal-arguments} @arbno{@stxref{required-or-guard}} [@stxlit{#!optional} @stxref{optional-arg} ...] @stxref{rest-key-args}
  7710. @stxdef{rest-key-args} [@stxlit{#!rest} @stxref{rest-arg}] [@stxlit{#!key} @stxref{key-arg} ...] [@stxref{guard}]
  7711. | [@stxlit{#!key} @stxref{key-arg} ...] [@stxref{rest-parameter}] [@stxref{guard}]
  7712. | @stxlit{.} @stxref{rest-arg}
  7713. @end display
  7714. When the procedure is applied to an
  7715. @ref{argument list}, the latter is matched against formal parameters.
  7716. This may involve some complex rules and pattern matching.
  7717. @subsubheading Required parameters
  7718. @display
  7719. @stxdef{required-or-guard} @stxref{required-arg} | @stxref{guard}
  7720. @stxdef{required-arg} @stxref{pattern}
  7721. | @stxlit{(} @stxref{pattern} @stxlit{::} @stxref{type}@stxlit{)}
  7722. @end display
  7723. The @var{required-arg}s are matched against the
  7724. actual (pre-keyword) arguments in order,
  7725. starting with the first actual argument.
  7726. It is an error if there are fewer pre-keyword
  7727. arguments then there are @var{required-arg}s.
  7728. While a @var{pattern} is most commonly an identifier,
  7729. more complicated patterns are possible, thus more (or fewer)
  7730. variables may be bound than there are arguments.
  7731. Note a @stxref{pattern} may include an @stxref{opt-type-specifier}.
  7732. For example:
  7733. @example
  7734. (define (isquare x::integer)
  7735. (* x x))
  7736. @end example
  7737. In this case the actual argument is coerced to an @code{integer}
  7738. and then the result matched against the pattern @code{x}.
  7739. This is how parameter types are specified.
  7740. The @var{pattern} may be enclosed in parentheses for clarify
  7741. (just like for optional parameters), but in that case the
  7742. type specifier is required to avoid ambiguity.
  7743. @subsubheading Optional parameters
  7744. @display
  7745. @stxdef{optional-arg} @var{variable} @stxref{opt-type-specifier}
  7746. | @stxlit{(} @stxref{pattern} @stxref{opt-type-specifier} [@var{initializer} [@stxref{supplied-var}]]@stxlit{)}
  7747. @stxdef{supplied-var} @var{variable}
  7748. @end display
  7749. Next the @var{optional-arg}s are bound to remaining pre-keyword arguments.
  7750. If there are fewer remaining pre-keyword arguments than there are
  7751. @var{optional-arg}s, then the remaining @var{variable}s are bound
  7752. to the corresponding @var{initializer}.
  7753. If no @var{initializer} was specified, it defaults to @code{#f}.
  7754. (TODO: If a @var{type} is specified the default for @var{initializer}
  7755. is the default value of the @var{type}.)
  7756. The @var{initializer} is evaluated in an
  7757. environment in which all the previous formal parameters have been bound.
  7758. If a @var{supplied-var} is specified, it has type boolean,
  7759. and is set to true if there was an actual corresponding argument,
  7760. and false if the initializer was evaluated.
  7761. @subsubheading Keyword parameters
  7762. @display
  7763. @stxdef{key-arg} @var{variable} @stxref{opt-type-specifier}
  7764. | @stxlit{(} @var{variable} @stxref{opt-type-specifier} [@var{initializer} [@stxref{supplied-var}]] @stxlit{)}
  7765. @end display
  7766. Keyword parameters follow @code{#!key}.
  7767. For each @var{variable}
  7768. if there is an actual keyword parameter whose keyword matches @var{variable},
  7769. then @var{variable} is bound to the corresponding value.
  7770. If there is no matching artual argument, then the @var{initializer} is
  7771. evaluated and bound to the argument.
  7772. If @var{initializer} is not specified, it defaults to @code{#f}.
  7773. The @var{initializer} is evaluated in an
  7774. environment in which all the previous formal parameters have been bound.
  7775. @example
  7776. (define (fun x #!key (foo 1) (bar 2) (baz 3))
  7777. (list x foo bar baz))
  7778. (fun 9 baz: 10 foo: 11) @result{} (9 11 2 10)
  7779. @end example
  7780. The following cause a match failure, @emph{unless} there is a rest parameter:
  7781. @itemize
  7782. @item
  7783. There may not be extra non-keyword arguments (prefix or postfix)
  7784. beyond those matched by required and optional parameters.
  7785. @item
  7786. There may not be any duplicated keyword arguments.
  7787. @item
  7788. All keyowrds in the actual argument list must
  7789. match one of the keyword formal parameters.
  7790. @end itemize
  7791. It is not recommended to use both keyword parameters
  7792. and a rest parameter that can match keyword arguments.
  7793. Currently, the rest parameter will include any arguments
  7794. that match the explicit keyword parameters, as well any that don't,
  7795. though this may change.
  7796. On the other hand, it is fine to have both keyword parameters
  7797. and a rest parameter does not accept keywords. In that case
  7798. the rest parameter will match any ``postfix'' arguments:
  7799. @example
  7800. #|kawa:8|# (define (fun x #!key k1 k2 #!rest r)
  7801. (format "x:~w k1:~w k2:~w r:~w" x k1 k2 r))
  7802. (fun 3 k2: 12 100 101) @result{} x:3 k1:#f k2:12 r:(100 101)
  7803. @end example
  7804. The @var{supplied-var} argument is as for optional arguments.
  7805. @PerformanceNote{} Keyword parameters are implemented very
  7806. efficiently and compactly when explicit in the code.
  7807. The parameters are sorted by the compiler, and the
  7808. actual keyword arguemnts at the call state are also sorted at compile-time.
  7809. So keyword matching just requires a fast linear scan comparing
  7810. the two sorted lists. This implementation is also very compact,
  7811. compared to say a hash table.
  7812. If a @var{type} is specified, the corresponding actual argument (or
  7813. the @var{initializer} default value) is coerced to the specified @var{type}.
  7814. In the function body, the parameter has the specified type.
  7815. @subsubheading Rest parameters
  7816. A ``rest parameter'' matches any arguments not matched by other parameters.
  7817. You can write it using any of the following ways:
  7818. @display
  7819. @stxdef{rest-parameter}
  7820. @stxlit{#!rest} @stxref{rest-arg} [@stxlit{::} @stxref{type}]
  7821. | @stxlit{@@}@stxref{rest-arg}
  7822. | @stxlit{@@:}@stxref{rest-arg}
  7823. @stxdef{rest-arg} @var{variable}
  7824. @end display
  7825. In addition, if @var{formals} is just a @var{rest-arg} identifier,
  7826. or a @var{formal-arguments} ends with @code{. @var{rest-arg}}
  7827. (i.e. is a dotted list) that is equivalent to using @code{#!rest}.
  7828. These forms are similar but differ in the type of the @var{rest-arg}
  7829. and whether keywords are allowed (as part of the @var{rest-arg}):
  7830. @itemize
  7831. @item
  7832. If @stxlit{#!rest} @var{rest-arg} is used with no @var{type} specifier
  7833. (or a @var{type} specifier of @code{list})
  7834. then @var{rest-arg} is a list.
  7835. Keywords are not allowed if @code{#!key} has been seen.
  7836. (For backward compatibility, it is allowed to have extra keywords
  7837. if @code{#!rest} is followed by @code{!key}.)
  7838. If there are any keywords, then @var{rest-arg} is more specifically
  7839. an @code{arglist}.
  7840. @item
  7841. If @stxlit{#!rest} @var{rest-arg} is used with @var{type} specifier
  7842. that is a Java array (for example @code{#!rest r::string[]}
  7843. then @var{rest-arg} has that type. Each argument must be compatible
  7844. with the element type of the array.
  7845. Keywords are not allowed (even if @var{type} is @code{object[]}).
  7846. The generated method will be compiled like a Java varargs
  7847. methods if possible (i.e. no non-trivial patterns or keyword paremeters).
  7848. @item
  7849. Using @stxlit{@@}@var{rest-arg} is equivalent to
  7850. @code{#!rest @var{rest-arg}::object[]}:
  7851. Keywords are not allowed; the type of @var{rest-arg} is a Java array;
  7852. the method is compiled like a Java varargs method.
  7853. @item
  7854. For @stxlit{@@:}@var{rest-arg} then @var{rest-arg} is a vector,
  7855. specifically an @code{argvector}. Keywords are allowed.
  7856. @end itemize
  7857. @subsubheading Guards (conditional expressions)
  7858. A @stxref{guard} is evaluated when it appears in the formal
  7859. parameter list.
  7860. If it evaluates to false, then matching fails.
  7861. Guards can appears before or after required arguments,
  7862. or at the very end, after all other formal parameters.
  7863. @node Procedure properties
  7864. @section Procedure properties
  7865. You can associate arbitrary @dfn{properties} with any procedure.
  7866. Each property is a (@var{key}, @var{value})-pair. Usually the
  7867. @var{key} is a symbol, but it can be any object.
  7868. The preferred way to set a property is using an @stxref{option-pair}
  7869. in a @stxref{lambda-expression}.
  7870. For example,
  7871. to set the @code{setter} property of a procedure
  7872. to @code{my-set-car} do the following:
  7873. @example
  7874. (define my-car
  7875. (lambda (arg) setter: my-set-car (primitive-car arg)))
  7876. @end example
  7877. The system uses certain internal properties:
  7878. @code{'name} refers to the name used when a procedure is printed;
  7879. @code{'emacs-interactive} is used to implement Emacs @code{interactive}
  7880. specification;
  7881. @code{'setter} is used to associate a @code{setter} procedure.
  7882. @deffn Procedure procedure-property proc key [default]
  7883. Get the property value corresponding to the given @var{key}.
  7884. If @var{proc} has no property with the given @var{key},
  7885. return @var{default} (which defaults to @code{#f}) instead.
  7886. @end deffn
  7887. @deffn Procedure set-procedure-property! proc key value
  7888. Associate the given @var{value} with the @var{key} property of @var{proc}.
  7889. @end deffn
  7890. To change the print name of the standard @code{+} procedure (probably
  7891. not a good idea!), you could do:
  7892. @example
  7893. (set-procedure-property! + 'name 'PLUS)
  7894. @end example
  7895. Note this @emph{only} changes the name property used for printing:
  7896. @example
  7897. + @result{} #<procedure PLUS>
  7898. (+ 2 3) @result{} 5
  7899. (PLUS 3 4) @result{} ERROR
  7900. @end example
  7901. As a matter of style, it is cleaner to use the @code{define-procedure}
  7902. form, as it is a more declarative interface.
  7903. @deffn Syntax define-procedure name [propname: propvalue] ... method ...
  7904. Defines @var{name} as a compound procedure consisting of the
  7905. specified @var{method}s, with the associated properties.
  7906. Applying @var{name} select the "best" @var{method}, and applies that.
  7907. See the following section on generic procedures.
  7908. For example, the standard @code{vector-ref} procedure specifies
  7909. one method, as well as the @code{setter} property:
  7910. @example
  7911. (define-procedure vector-ref
  7912. setter: vector-set!
  7913. (lambda (vector::vector k ::int)
  7914. (invoke vector 'get k)))
  7915. @end example
  7916. @end deffn
  7917. You can also specify properties in the lambda body:
  7918. @example
  7919. (define (vector-ref vector::vector k ::int)
  7920. setter: vector-set!
  7921. (invoke vector 'get k))
  7922. @end example
  7923. @subsection Standard properties
  7924. @table @code
  7925. @item name
  7926. The name of a procedure (as a symbol), which is used
  7927. when the procedure is printed.
  7928. @item setter
  7929. Set the setter procedure associated with the procedure.
  7930. @item validate-apply
  7931. @itemx validate-xapply
  7932. Used during the validation phase of the compiler.
  7933. @item compile-apply
  7934. Used during the bytecode-generation phase of the compiler:
  7935. If we see a call to a known function with this property,
  7936. we can emit custom bytecode for the call.
  7937. @end table
  7938. @node Generic procedures
  7939. @section Generic (dynamically overloaded) procedures
  7940. A @dfn{generic procedure} is a collection of @dfn{method procedures}.
  7941. (A "method procedure" is not the same as a Java method, but
  7942. the terms are related.)
  7943. You can call a generic procedure, which selects the "closest
  7944. match" among the component method procedures: I.e. the most specific
  7945. method procedure that is applicable given the actual arguments.
  7946. @quotation
  7947. @strong{Warning:} The current implementation of selecting the "best" method
  7948. is not reliable if there is more than one method.
  7949. It can select depending on argument count, and it can select between
  7950. primitive Java methods. However, selecting between different Scheme
  7951. procedures based on parameter types should be considered experimental.
  7952. The main problem is we can't determine the most specific
  7953. method, so Kawa just tries the methods in order.
  7954. @end quotation
  7955. @deffn Procedure make-procedure [keyword: value]... method...
  7956. Create a generic procedure given the specific methods.
  7957. You can also specify property values for the result.
  7958. The @var{keyword}s specify how the arguments are used.
  7959. A @code{method:} keyword is optional and specifies that the following
  7960. argument is a method.
  7961. A @code{name:} keyword specifies the name of the resulting procedure,
  7962. when used for printing.
  7963. Unrecognized keywords are used to set the procedure properties of the result.
  7964. @example
  7965. (define plus10 (make-procedure foo: 33 name: 'Plus10
  7966. method: (lambda (x y) (+ x y 10))
  7967. method: (lambda () 10)))
  7968. @end example
  7969. @end deffn
  7970. @node Partial application
  7971. @section Partial application
  7972. @deffn Syntax cut slot-or-expr slot-or-expr* [@code{<...>}]
  7973. where each @var{slot-or-expr} is either an @var{expression} or
  7974. the literal symbol @code{<>}.
  7975. It is frequently necessary to specialize some of the parameters of a
  7976. multi-parameter procedure. For example, from the binary operation @code{cons}
  7977. one might want to obtain the unary operation
  7978. @code{(lambda (x) (cons 1 x))}.
  7979. This specialization of parameters is also known
  7980. as @dfn{partial application}, @dfn{operator section}, or @dfn{projection}.
  7981. The macro @code{cut} specializes some of the parameters of its first
  7982. argument. The parameters that are to show up as formal variables of the
  7983. result are indicated by the symbol @code{<>}, pronouced as "slot".
  7984. In addition, the symbol @code{<...>}, pronounced as "rest-slot", matches all
  7985. residual arguments of a variable argument procedure.
  7986. A @code{cut}-expression is transformed into
  7987. a @var{lambda expression} with as many formal variables as there are
  7988. slots in the list @var{slot-or-expr}*.
  7989. The body of the resulting @var{lambda expression} calls
  7990. the first @var{slot-or-expr} with arguments from the @var{slot-or-expr}* list
  7991. in the order they appear. In case there is a rest-slot symbol, the resulting
  7992. procedure is also of variable arity, and the body calls the first
  7993. @var{slot-or-expr} with remaining arguments provided to the actual call of the
  7994. specialized procedure.
  7995. Here are some examples:
  7996. @code{(cut cons (+ a 1) <>)} is the same as @w{@code{(lambda (x2) (cons (+ a 1) x2))}}
  7997. @code{(cut list 1 <> 3 <> 5)} is the same as @w{@code{(lambda (x2 x4) (list 1 x2 3 x4 5))}}
  7998. @code{(cut list)} is the same as @w{@code{(lambda () (list))}}
  7999. @code{(cut list 1 <> 3 <...>)} is the same as @w{@code{(lambda (x2 . xs) (apply list 1 x2 3 xs))}}
  8000. The first argument can also be a slot, as one should expect in Scheme:
  8001. @code{(cut <> a b)} is the same as @w{@code{(lambda (f) (f a b))}}
  8002. @end deffn
  8003. @deffn Syntax cute slot-or-expr slot-or-expr* [@code{<...>}]
  8004. The macro @code{cute} (a mnemonic for "cut with evaluated non-slots") is
  8005. similar to @code{cut}, but it evaluates the non-slot expressions at the
  8006. time the procedure is specialized, not at the time the specialized
  8007. procedure is called.
  8008. For example
  8009. @code{(cute cons (+ a 1) <>)} is the same as
  8010. @w{@code{(let ((a1 (+ a 1))) (lambda (x2) (cons a1 x2)))}}
  8011. As you see from comparing this example with the first example above, the
  8012. @code{cute}-variant will evaluate @code{(+ a 1)} once,
  8013. while the @code{cut}-variant will
  8014. evaluate it during every invocation of the resulting procedure.
  8015. @end deffn
  8016. @node Numbers, Characters and text, Procedures, Top
  8017. @chapter Quantities and Numbers
  8018. Kawa supports the full Scheme set of number operations with some extensions.
  8019. Kawa converts between Scheme number types
  8020. and Java number types as appropriate.
  8021. @menu
  8022. * Numerical types::
  8023. * Arithmetic operations::
  8024. * Numerical input and output::
  8025. * Quaternions::
  8026. * Quantities::
  8027. * Logical Number Operations::
  8028. * Performance of numeric operations::
  8029. @end menu
  8030. @node Numerical types
  8031. @section Numerical types
  8032. Mathematically, numbers are arranged into a tower of subtypes
  8033. in which each level is a subset of the level before it:
  8034. number; complex number; real number; rational number; integer.
  8035. For example, @code{3} is an integer. Therefore @code{3} is also a rational,
  8036. a real, and a complex number. The same is true of the
  8037. Scheme numbers that model 3. For Scheme numbers, these
  8038. types are defined by the predicates @code{number?}, @code{complex?},
  8039. @code{real?}, @code{rational?}, and @code{integer?}.
  8040. There is no simple relationship between a number’s type
  8041. and its representation inside a computer. Although most
  8042. implementations of Scheme will offer at least two different
  8043. representations of 3, these different representations denote
  8044. the same integer.
  8045. Scheme’s numerical operations treat numbers as abstract
  8046. data, as independent of their representation as possible.
  8047. Although an implementation of Scheme may use multiple
  8048. internal representations of numbers, this ought not to be
  8049. apparent to a casual programmer writing simple programs.
  8050. @deffn Type number
  8051. The type of Scheme numbers.
  8052. @end deffn
  8053. @deffn Type quantity
  8054. The type of quantities optionally with units.
  8055. This is a sub-type of @code{number}.
  8056. @end deffn
  8057. @deffn Type complex
  8058. The type of complex numbers.
  8059. This is a sub-type of @code{quantity}.
  8060. @end deffn
  8061. @deffn Type real
  8062. The type of real numbers.
  8063. This is a sub-type of @code{complex}.
  8064. @end deffn
  8065. @deffn Type rational
  8066. The type of exact rational numbers.
  8067. This is a sub-type of @code{real}.
  8068. @end deffn
  8069. @deffn Type integer
  8070. The type of exact Scheme integers.
  8071. This is a sub-type of @code{rational}.
  8072. @end deffn
  8073. Kawa allows working with expressions of ``primitive'' types,
  8074. which are supported by the JVM without object allocation,
  8075. and using builtin arithmetic. Using these types may be much
  8076. faster, assuming the compiler is able to infer
  8077. that the variable or expression has primitive type.
  8078. @deffn Type long
  8079. @deffnx Type int
  8080. @deffnx Type short
  8081. @deffnx Type byte
  8082. These are fixed-sized primitive signed exact integer types,
  8083. of respectively 64, 32, 18, and 8 bits.
  8084. If a value of one of these types needs to be converted to an
  8085. object, the standard classes @code{java.lang.Long}, @code{java.lang.Integer},
  8086. @code{java.lang.Short}, or @code{java.lang.Byte}, respectively, are used.
  8087. @end deffn
  8088. @deffn Type ulong
  8089. @deffnx Type uint
  8090. @deffnx Type ushort
  8091. @deffnx Type ubyte
  8092. These are fixed-sized primitive unsigned exact integer types,
  8093. of respectively 64, 32, 18, and 8 bits.
  8094. These are presented at runtime using the corresponding
  8095. signed types (@code{long}, @code{int}, @code{short}, or @code{byte}).
  8096. However, for arithmetic the Kawa compiler generates code to perform the
  8097. ``mathematically correct'' result, truncated to an unsigned result
  8098. rather than signed.
  8099. If a value of one of these types needs to be converted to an
  8100. object, the classes @code{gnu.math.ULong}, @code{gnu.math.UInt},
  8101. @code{gnu.math.UShort}, or @code{gnu.math.UByte} is used.
  8102. @end deffn
  8103. @deffn Type double
  8104. @deffnx Type float
  8105. These are fixed-size primitive inexact floating-point real types,
  8106. using the standard 64-bit or 32-bit IEEE representation.
  8107. If a value of one of these types needs to be converted to an
  8108. object, the standard classes @code{java.lang.Double},
  8109. or @code{java.lang.Float} is used.
  8110. @end deffn
  8111. @subsection Exactness
  8112. @cindex exactness
  8113. It is useful to distinguish between numbers that are represented
  8114. exactly and those that might not be. For example,
  8115. indexes into data structures must be known exactly, as
  8116. must some polynomial coefficients in a symbolic algebra
  8117. system. On the other hand, the results of measurements
  8118. are inherently inexact, and irrational numbers may be approximated
  8119. by rational and therefore inexact approximations.
  8120. In order to catch uses of inexact numbers where exact numbers
  8121. are required, Scheme explicitly distinguishes
  8122. exact from inexact numbers. This distinction is orthogonal
  8123. to the dimension of type.
  8124. @cindex exact complex number
  8125. @cindex inexact complex number
  8126. A Scheme number is @dfn{exact} if it was written as an exact
  8127. constant or was derived from exact numbers using only exact operations.
  8128. A number is @dfn{inexact} if it was written as
  8129. an inexact constant, if it was derived using inexact ingredients,
  8130. or if it was derived using inexact operations. Thus
  8131. inexactness is a contagious property of a number.
  8132. In particular, an @dfn{exact complex number} has an exact real part
  8133. and an exact imaginary part; all other complex numbers
  8134. are @dfn{inexact complex numbers}.
  8135. If two implementations produce exact results for a computation
  8136. that did not involve inexact intermediate results, the
  8137. two ultimate results will be mathematically equal. This
  8138. is generally not true of computations involving inexact
  8139. numbers since approximate methods such as floating-point
  8140. arithmetic may be used, but it is the duty of the implementation
  8141. to make the result as close as practical to the
  8142. mathematically ideal result.
  8143. Rational operations such as @code{+} should always produce exact
  8144. results when given exact arguments. If the operation
  8145. is unable to produce an exact result, then it may either
  8146. report the violation of an implementation restriction or it
  8147. may silently coerce its result to an inexact value.
  8148. Except for @code{exact}, the operations described in this section
  8149. must generally return inexact results when given any inexact arguments.
  8150. An operation may, however, return an
  8151. exact result if it can prove that the value of the result is
  8152. unaffected by the inexactness of its arguments. For example,
  8153. multiplication of any number by an exact zero may
  8154. produce an exact zero result, even if the other argument is inexact.
  8155. Specifically, the expression @code{(* 0 +inf.0)} may return @code{0},
  8156. or @code{+nan.0}, or report that inexact numbers are not supported,
  8157. or report that non-rational real numbers are not supported,
  8158. or fail silently or noisily in other implementation-specific ways.
  8159. The procedures listed below will always return exact integer
  8160. results provided all their arguments are exact integers
  8161. and the mathematically expected results are representable
  8162. as exact integers within the implementation:
  8163. @code{-},
  8164. @code{*},
  8165. @code{+},
  8166. @code{abs},
  8167. @code{ceiling},
  8168. @code{denominator},
  8169. @code{exact-integer-sqrt},
  8170. @code{expt},
  8171. @code{floor},
  8172. @code{floor/},
  8173. @code{floor-quotient},
  8174. @code{floor-remainder},
  8175. @code{gcd},
  8176. @code{lcm},
  8177. @code{max},
  8178. @code{min},
  8179. @code{modulo},
  8180. @code{numerator},
  8181. @code{quotient},
  8182. @code{rationalize},
  8183. @code{remainder},
  8184. @code{square},
  8185. @code{truncate},
  8186. @code{truncate/},
  8187. @code{truncate-quotient},
  8188. @code{truncate-remainder}.
  8189. @subsection Numerical promotion and conversion
  8190. When combining two values of different numeric types,
  8191. the values are converted to the first line in the following
  8192. that subsumes (follows) both types. The computation is done using
  8193. values of that type, and so is the result.
  8194. For example adding a @code{long} and a @code{float} converts the former
  8195. to the latter, yielding a @code{float}.
  8196. Note that @code{short}, @code{byte}, @code{ushort}, @code{ubyte}
  8197. are converted to @code{int} regardless, even in the case of
  8198. a single-operand operation, such as unary negation.
  8199. Another exception is trancendental functions (such as @code{cos}),
  8200. where integer operands are converted to @code{double}.
  8201. @itemize
  8202. @item
  8203. @code{int} subsumes @code{short}, @code{byte}, @code{ushort}, @code{ubyte}.
  8204. @item
  8205. @code{uint}
  8206. @item
  8207. @code{long}
  8208. @item
  8209. @code{ulong}
  8210. @item
  8211. @code{java.lang.BigInteger}
  8212. @item
  8213. @code{integer} (i.e. @code{gnu.math.IntNum})
  8214. @item
  8215. @code{rational} (i.e. @code{gnu.math.RatNum})
  8216. @item
  8217. @code{float}
  8218. @item
  8219. @code{double}
  8220. @item
  8221. @code{gnu.math.FloNum}
  8222. @item
  8223. @code{real} (i.e. @code{gnu.math.RealNum})
  8224. @item
  8225. @code{number}
  8226. @item
  8227. @code{complex}
  8228. @item
  8229. @code{quantity}
  8230. @end itemize
  8231. When comparing a primitive signed integer value with a primitive unsigned
  8232. integer (for example @code{<} applied to a @code{int} and a @code{ulong})
  8233. the mathemically correct result is computed, as it converting both
  8234. operands to @code{integer}.
  8235. @node Arithmetic operations
  8236. @section Arithmetic operations
  8237. @deffn Procedure {real-valued?} @var{obj}
  8238. @deffnx Procedure {rational-valued?} @var{obj}
  8239. @deffnx Procedure {integer-valued?} @var{obj}
  8240. These numerical type predicates can be applied to any kind of argument.
  8241. The @func{real-valued?} procedure returns @true{} if the object is a
  8242. number object and is equal in the sense of @code{=} to some real number
  8243. object, or if the object is a NaN, or a complex number object whose real
  8244. part is a NaN and whose imaginary part is zero in the sense of
  8245. @func{zero?}. The @func{rational-valued?} and @func{integer-valued?}
  8246. procedures return @true{} if the object is a number object and is equal
  8247. in the sense of @code{=} to some object of the named type, and otherwise
  8248. they return @false{}.
  8249. @example
  8250. (real-valued? +nan.0) @result{} #t
  8251. (real-valued? +nan.0+0i) @result{} #t
  8252. (real-valued? -inf.0) @result{} #t
  8253. (real-valued? 3) @result{} #t
  8254. (real-valued? -2.5+0.0i) @result{} #t
  8255. (real-valued? -2.5+0i) @result{} #t
  8256. (real-valued? -2.5) @result{} #t
  8257. (real-valued? #e1e10) @result{} #t
  8258. (rational-valued? +nan.0) @result{} #f
  8259. (rational-valued? -inf.0) @result{} #f
  8260. (rational-valued? 6/10) @result{} #t
  8261. (rational-valued? 6/10+0.0i) @result{} #t
  8262. (rational-valued? 6/10+0i) @result{} #t
  8263. (rational-valued? 6/3) @result{} #t
  8264. (integer-valued? 3+0i) @result{} #t
  8265. (integer-valued? 3+0.0i) @result{} #t
  8266. (integer-valued? 3.0) @result{} #t
  8267. (integer-valued? 3.0+0.0i) @result{} #t
  8268. (integer-valued? 8/4) @result{} #t
  8269. @end example
  8270. @quotation
  8271. @emph{Note:} These procedures test whether a given number object can be
  8272. coerced to the specified type without loss of numerical accuracy.
  8273. Specifically, the behavior of these predicates differs from the behavior
  8274. of @func{real?}, @func{rational?}, and @func{integer?} on complex number
  8275. objects whose imaginary part is inexact zero.
  8276. @end quotation
  8277. @quotation
  8278. @emph{Note:} The behavior of these type predicates on inexact number
  8279. objects is unreliable, because any inaccuracy may affect the result.
  8280. @end quotation
  8281. @end deffn
  8282. @deffn Procedure exact-integer? z
  8283. Returns @code{#t} if @var{z} is both exact and an integer; otherwise
  8284. returns @code{#f}.
  8285. @example
  8286. (exact-integer? 32) @result{} #t
  8287. (exact-integer? 32.0) @result{} #t
  8288. (exact-integer? 32/5) @result{} #f
  8289. @end example
  8290. @end deffn
  8291. @deffn Procedure {finite?} @var{z}
  8292. Returns @code{#t} if @var{z} is finite real number
  8293. (i.e. an infinity and not a NaN),
  8294. or if @var{z} is a complex number
  8295. whose real and imaginary parts are both finite.
  8296. @example
  8297. (finite? 3) @result{} #t
  8298. (finite? +inf.0) @result{} #f
  8299. (finite? 3.0+inf.0i) @result{} #f
  8300. @end example
  8301. @end deffn
  8302. @deffn Procedure {infinite?} @var{z}
  8303. Return @code{#t} if @var{z} is
  8304. an infinite real number (@code{+int.0} or @code{-inf.0}),
  8305. or if @var{z} is a complex number where either
  8306. real or imaginary parts or both are infinite.
  8307. @example
  8308. (infinite? 5.0) @result{} #f
  8309. (infinite? +inf.0) @result{} #t
  8310. (infinite? +nan.0) @result{} #f
  8311. (infinite? 3.0+inf.0i) @result{} #t
  8312. @end example
  8313. @end deffn
  8314. @deffn Procedure {nan?} @var{z}
  8315. For a real numer returns whether its is a NaN;
  8316. for a complex number if the real or imaginary parts or both is a NaN.
  8317. @example
  8318. (nan? +nan.0) @result{} #t
  8319. (nan? 32) @result{} #f
  8320. (nan? +nan.0+5.0i) @result{} #t
  8321. (nan? 1+2i) @result{} #f
  8322. @end example
  8323. @end deffn
  8324. @deffn Procedure + @var{z} @dots{}
  8325. @deffnx Procedure * @var{z} @dots{}
  8326. These procedures return the sum or product of their arguments.
  8327. @example
  8328. (+ 3 4) @result{} 7
  8329. (+ 3) @result{} 3
  8330. (+) @result{} 0
  8331. (+ +inf.0 +inf.0) @result{} +inf.0
  8332. (+ +inf.0 -inf.0) @result{} +nan.0
  8333. (* 4) @result{} 4
  8334. (*) @result{} 1
  8335. (* 5 +inf.0) @result{} +inf.0
  8336. (* -5 +inf.0) @result{} -inf.0
  8337. (* +inf.0 +inf.0) @result{} +inf.0
  8338. (* +inf.0 -inf.0) @result{} -inf.0
  8339. (* 0 +inf.0) @result{} +nan.0
  8340. (* 0 +nan.0) @result{} +nan.0
  8341. (* 1.0 0) @result{} 0.0
  8342. @end example
  8343. For any real number object @var{x} that is neither infinite nor NaN:
  8344. @example
  8345. (+ +inf.0 @var{x}) @result{} +inf.0
  8346. (+ -inf.0 @var{x}) @result{} -inf.0
  8347. @end example
  8348. For any real number object @var{x}:
  8349. @example
  8350. (+ +nan.0 @var{x}) @result{} +nan.0
  8351. @end example
  8352. For any real number object @var{x} that is not an exact 0:
  8353. @example
  8354. (* +nan.0 @var{x}) @result{} +nan.0
  8355. @end example
  8356. @c If any of these procedures are applied to mixed non--rational real and
  8357. @c non--real complex arguments, they either raise an exception with
  8358. @c condition type @code{&implementation-restriction} or return an
  8359. @c unspecified number object.
  8360. The behavior of @code{-0.0} is illustrated by the following examples:
  8361. @example
  8362. (+ 0.0 -0.0) @result{} 0.0
  8363. (+ -0.0 0.0) @result{} 0.0
  8364. (+ 0.0 0.0) @result{} 0.0
  8365. (+ -0.0 -0.0) @result{} -0.0
  8366. @end example
  8367. @end deffn
  8368. @deffn Procedure - @var{z}
  8369. @deffnx Procedure - @vari{z} @varii{z} @variii{z} @dots{}
  8370. With two or more arguments, this procedures returns the difference of
  8371. its arguments, associating to the left. With one argument, however, it
  8372. returns the negation (additive inverse) of its argument.
  8373. @example
  8374. (- 3 4) @result{} -1
  8375. (- 3 4 5) @result{} -6
  8376. (- 3) @result{} -3
  8377. (- +inf.0 +inf.0) @result{} +nan.0
  8378. @end example
  8379. @c If this procedure is applied to mixed non--rational real and non--real
  8380. @c complex arguments, it either raises an exception with condition type
  8381. @c @code{&implementation-restriction} or returns an unspecified number
  8382. @c object.
  8383. The behavior of @code{-0.0} is illustrated by the following examples:
  8384. @example
  8385. (- 0.0) @result{} -0.0
  8386. (- -0.0) @result{} 0.0
  8387. (- 0.0 -0.0) @result{} 0.0
  8388. (- -0.0 0.0) @result{} -0.0
  8389. (- 0.0 0.0) @result{} 0.0
  8390. (- -0.0 -0.0) @result{} 0.0
  8391. @end example
  8392. @end deffn
  8393. @deffn Procedure / @var{z}
  8394. @deffnx Procedure / @vari{z} @varii{z} @variii{z} @dots{}
  8395. If all of the arguments are exact, then the divisors must all be
  8396. nonzero. With two or more arguments, this procedure returns the
  8397. quotient of its arguments, associating to the left. With one argument,
  8398. however, it returns the multiplicative inverse of its argument.
  8399. @example
  8400. (/ 3 4 5) @result{} 3/20
  8401. (/ 3) @result{} 1/3
  8402. (/ 0.0) @result{} +inf.0
  8403. (/ 1.0 0) @result{} +inf.0
  8404. (/ -1 0.0) @result{} -inf.0
  8405. (/ +inf.0) @result{} 0.0
  8406. (/ 0 0) @result{} exception &assertion
  8407. (/ 3 0) @result{} exception &assertion
  8408. (/ 0 3.5) @result{} 0.0
  8409. (/ 0 0.0) @result{} +nan.0
  8410. (/ 0.0 0) @result{} +nan.0
  8411. (/ 0.0 0.0) @result{} +nan.0
  8412. @end example
  8413. If this procedure is applied to mixed non--rational real and non--real
  8414. complex arguments, it either raises an exception with condition type
  8415. @code{&implementation-restriction} or returns an unspecified number
  8416. object.
  8417. @end deffn
  8418. @deffn Procedure floor/ x y
  8419. @deffnx Procedure truncate/ x y
  8420. @deffnx Procedure div-and-mod x y
  8421. @deffnx Procedure div0-and-mod0 x y
  8422. These procedures implement number--theoretic integer division.
  8423. They accept two real numbers @var{x} and @var{y} as operands,
  8424. where @var{y} must be nonzero.
  8425. In all cases the result is two values @var{q} (an integer) and @var{r} (a real)
  8426. that satisfy the equations:
  8427. @example
  8428. @var{x} = @var{q} * @var{y} + @var{r}
  8429. @var{q} = @var{rounding-op}(@var{x}/@var{y})
  8430. @end example
  8431. The result is inexact if either argument is inexact.
  8432. For @code{floor/} the @var{rounding-op} is the @code{floor} function (below).
  8433. @example
  8434. (floor/ 123 10) @result{} 12 3
  8435. (floor/ 123 -10) @result{} -13 -7
  8436. (floor/ -123 10) @result{} -13 7
  8437. (floor/ -123 -10) @result{} 12 -3
  8438. @end example
  8439. For @code{truncate/} the @var{rounding-op} is the @code{truncate} function.
  8440. @example
  8441. (truncate/ 123 10) @result{} 12 3
  8442. (truncate/ 123 -10) @result{} -12 3
  8443. (truncate/ -123 10) @result{} -12 -3
  8444. (truncate/ -123 -10) @result{} 12 -3
  8445. @end example
  8446. For @code{div-and-mod} the @var{rounding-op} is either @code{floor}
  8447. (if @var{y} is positive) or @code{ceiling} (if @var{y} is negative).
  8448. We have:
  8449. @example
  8450. 0 <= @var{r} < |@var{y}|
  8451. @end example
  8452. @example
  8453. (div-and-mod 123 10) @result{} 12 3
  8454. (div-and-mod 123 -10) @result{} -12 3
  8455. (div-and-mod -123 10) @result{} -13 7
  8456. (div-and-mod -123 -10) @result{} 13 7
  8457. @end example
  8458. For @code{div0-and-mod0} the @var{rounding-op} is the @code{round} function,
  8459. and @code{r} lies within a half--open interval centered on zero.
  8460. @example
  8461. -|@var{y}/2| <= @var{r} < |@var{y}/2|
  8462. @end example
  8463. @example
  8464. (div0-and-mod0 123 10) @result{} 12 3
  8465. (div0-and-mod0 123 -10) @result{} -12 3
  8466. (div0-and-mod0 -123 10) @result{} -12 -3
  8467. (div0-and-mod0 -123 -10) @result{} 12 -3
  8468. (div0-and-mod0 127 10) @result{} 13 -3
  8469. (div0-and-mod0 127 -10) @result{} -13 -3
  8470. (div0-and-mod0 -127 10) @result{} -13 3
  8471. (div0-and-mod0 -127 -10) @result{} 13 3
  8472. @end example
  8473. The inconsistent naming is for historical reasons: @code{div-and-mod}
  8474. and @code{div0-and-mod0} are from R6RS, while @code{floor/} and
  8475. @code{truncate/} are from R7RS.
  8476. @end deffn
  8477. @deffn Procedure floor-quotient x y
  8478. @deffnx Procedure truncate-quotient x y
  8479. @deffnx Procedure div x y
  8480. @deffnx Procedure div0 x y
  8481. These procedures return the quotient part (first value)
  8482. of respectively @code{floor/}, @code{truncate/},
  8483. @code{div-and-mod}, and @code{div0-and-mod0}.
  8484. @end deffn
  8485. @deffn Procedure floor-remainder x y
  8486. @deffnx Procedure truncate-remainder x y
  8487. @deffnx Procedure mod x y
  8488. @deffnx Procedure mod0 x y
  8489. These procedures return the remainder part (second value)
  8490. of respectively @code{floor/}, @code{truncate/},
  8491. @code{div-and-mod}, and @code{div0-and-mod0}.
  8492. As a Kawa extension @var{y} may be zero, in which case the result is @var{x}:
  8493. @example
  8494. (mod 123 0) @result{} 123 ;; Kawa extension
  8495. @end example
  8496. @end deffn
  8497. @deffn Procedure quotient x y
  8498. @deffnx Procedure remainder x y
  8499. @deffnx Procedure modulo x y
  8500. These are equivalent to @code{truncate-quotient},
  8501. @code{truncate-remainder}, and @code{floor-remainder}, respectively.
  8502. These are provided for backward compatibility.
  8503. @example
  8504. (remainder 13 4) @result{} 1
  8505. (remainder -13 4) @result{} -1
  8506. (remainder 13 -4) @result{} 1
  8507. (remainder -13 -4) @result{} -1
  8508. (remainder -13 -4.0) @result{} -1.0
  8509. (modulo 13 4) @result{} 1
  8510. (modulo -13 4) @result{} 3
  8511. (modulo 13 -4) @result{} -4
  8512. (modulo -13 -4) @result{} -1
  8513. @end example
  8514. @end deffn
  8515. @deffn Procedure abs @var{x}
  8516. Returns the absolute value of its argument.
  8517. @example
  8518. (abs -7) @result{} 7
  8519. (abs -inf.0) @result{} +inf.0
  8520. @end example
  8521. @end deffn
  8522. @deffn Procedure gcd @vari{n} @dots{}
  8523. @deffnx Procedure lcm @vari{n} @dots{}
  8524. These procedures return the greatest common divisor or least common
  8525. multiple of their arguments. The result is always non--negative.
  8526. The arguments must be integers; if an argument is inexact, so is the result.
  8527. @example
  8528. (gcd 32 -36) @result{} 4
  8529. (gcd) @result{} 0
  8530. (lcm 32 -36) @result{} 288
  8531. (lcm 32.0 -36) @result{} 288.0 ; inexact
  8532. (lcm) @result{} 1
  8533. @end example
  8534. @end deffn
  8535. @deffn Procedure numerator @var{q}
  8536. @deffnx Procedure denominator @var{q}
  8537. These procedures return the numerator or denominator of their argument;
  8538. the result is computed as if the argument was represented as a fraction
  8539. in lowest terms. The denominator is always positive. The denominator
  8540. of @code{0} is defined to be @code{1}.
  8541. The arguments must be integers; if an argument is inexact, so is the result.
  8542. @example
  8543. (numerator (/ 6 4)) @result{} 3
  8544. (denominator (/ 6 4)) @result{} 2
  8545. (denominator (inexact (/ 6 4))) @result{} 2.0
  8546. @end example
  8547. @end deffn
  8548. @deffn Procedure floor @var{x}
  8549. @deffnx Procedure ceiling @var{x}
  8550. @deffnx Procedure truncate @var{x}
  8551. @deffnx Procedure round @var{x}
  8552. These procedures return inexact integer objects for inexact arguments
  8553. that are not infinities or NaNs, and exact integer objects for exact
  8554. rational arguments.
  8555. @table @code
  8556. @item floor
  8557. Returns the largest integer object not larger than @var{x}.
  8558. @item ceiling
  8559. Returns the smallest integer object not smaller than @var{x}.
  8560. @item truncate
  8561. Returns the integer object closest to @var{x} whose absolute value is
  8562. not larger than the absolute value of @var{x}.
  8563. @item round
  8564. Returns the closest integer object to @var{x}, rounding to even when
  8565. @var{x} represents a number halfway between two integers.
  8566. @end table
  8567. If the argument to one of these procedures is inexact, then the result
  8568. is also inexact. If an exact value is needed, the result should be
  8569. passed to the @func{exact} procedure.
  8570. Although infinities and NaNs are not integer objects, these procedures
  8571. return an infinity when given an infinity as an argument, and a NaN when
  8572. given a NaN.
  8573. @example
  8574. (floor -4.3) @result{} -5.0
  8575. (ceiling -4.3) @result{} -4.0
  8576. (truncate -4.3) @result{} -4.0
  8577. (round -4.3) @result{} -4.0
  8578. (floor 3.5) @result{} 3.0
  8579. (ceiling 3.5) @result{} 4.0
  8580. (truncate 3.5) @result{} 3.0
  8581. (round 3.5) @result{} 4.0
  8582. (round 7/2) @result{} 4
  8583. (round 7) @result{} 7
  8584. (floor +inf.0) @result{} +inf.0
  8585. (ceiling -inf.0) @result{} -inf.0
  8586. (round +nan.0) @result{} +nan.0
  8587. @end example
  8588. @end deffn
  8589. @deffn Procedure rationalize @vari{x} @varii{x}
  8590. The @func{rationalize} procedure returns a number object representing
  8591. the @emph{simplest} rational number differing from @vari{x} by no more
  8592. than @varii{x}.
  8593. A rational number @emph{r_1} is @emph{simpler} than another rational
  8594. number @emph{r_2} if @code{r_1 = p_1/q_1} and @code{r_2 = p_2/q_2} (in
  8595. lowest terms) and @code{|p_1| <= |p_2|} and @code{|q_1| <= |q_2|}. Thus
  8596. @code{3/5} is simpler than @code{4/7}.
  8597. Although not all rationals are comparable in this ordering (consider
  8598. @code{2/7} and @code{3/5}) any interval contains a rational number that
  8599. is simpler than every other rational number in that interval (the
  8600. simpler @code{2/5} lies between @code{2/7} and @code{3/5}).
  8601. Note that @code{0 = 0/1} is the simplest rational of all.
  8602. @example
  8603. (rationalize (exact .3) 1/10) @result{} 1/3
  8604. (rationalize .3 1/10) @result{} #i1/3 ; approximately
  8605. (rationalize +inf.0 3) @result{} +inf.0
  8606. (rationalize +inf.0 +inf.0) @result{} +nan.0
  8607. @c (rationalize 3 +inf.0) @result{} 0.0
  8608. @end example
  8609. The first two examples hold only in implementations whose inexact real
  8610. number objects have sufficient precision.
  8611. @end deffn
  8612. @deffn Procedure exp @var{z}
  8613. @deffnx Procedure log @var{z}
  8614. @deffnx Procedure log @vari{z} @varii{z}
  8615. @deffnx Procedure sin @var{z}
  8616. @deffnx Procedure cos @var{z}
  8617. @deffnx Procedure tan @var{z}
  8618. @deffnx Procedure asin @var{z}
  8619. @deffnx Procedure acos @var{z}
  8620. @deffnx Procedure atan @var{z}
  8621. @deffnx Procedure atan @vari{x} @varii{x}
  8622. These procedures compute the usual transcendental functions.
  8623. The @func{exp} procedure computes the base--@var{e} exponential of
  8624. @var{z}.
  8625. The @func{log} procedure with a single argument computes the natural
  8626. logarithm of @var{z} (@strong{not} the base--10 logarithm); @code{(log
  8627. @vari{z} @varii{z})} computes the base--@varii{z} logarithm of @vari{z}.
  8628. The @func{asin}, @func{acos}, and @func{atan} procedures compute
  8629. arcsine, arccosine, and arctangent, respectively. The two--argument
  8630. variant of @func{atan} computes:
  8631. @example
  8632. (angle (make-rectangular @varii{x} @vari{x}))
  8633. @end example
  8634. These procedures may return inexact results even when given exact
  8635. arguments.
  8636. @example
  8637. (exp +inf.0) @result{} +inf.0
  8638. (exp -inf.0) @result{} 0.0
  8639. (log +inf.0) @result{} +inf.0
  8640. (log 0.0) @result{} -inf.0
  8641. (log 0) @result{} exception &assertion
  8642. (log -inf.0) @result{} +inf.0+3.141592653589793i ; approximately
  8643. (atan -inf.0) @result{} -1.5707963267948965 ; approximately
  8644. (atan +inf.0) @result{} 1.5707963267948965 ; approximately
  8645. (log -1.0+0.0i) @result{} 0.0+3.141592653589793i ; approximately
  8646. (log -1.0-0.0i) @result{} 0.0-3.141592653589793i ; approximately
  8647. ; if -0.0 is distinguished
  8648. @end example
  8649. @end deffn
  8650. @deffn Procedure sinh z
  8651. @deffnx Procedure cosh z
  8652. @deffnx Procedure tanh z
  8653. @deffnx Procedure asinh z
  8654. @deffnx Procedure acosh z
  8655. @deffnx Procedure atanh z
  8656. The hyperbolic functions.
  8657. @end deffn
  8658. @deffn Procedure square z
  8659. Returns the square of @var{z}.
  8660. This is equivalent to @code{(* @var{z} @var{z})}.
  8661. @example
  8662. (square 42) @result{} 1764
  8663. (square 2.0) @result{} 4.0
  8664. @end example
  8665. @end deffn
  8666. @deffn Procedure sqrt @var{z}
  8667. Returns the principal square root of @var{z}. For rational @var{z}, the
  8668. result has either positive real part, or zero real part and
  8669. non--negative imaginary part. The value of @code{(sqrt @var{z})} could be
  8670. expressed as:
  8671. @example
  8672. e^((log z)/2)
  8673. @end example
  8674. The @func{sqrt} procedure may return an inexact result even when given
  8675. an exact argument.
  8676. @example
  8677. (sqrt -5) @result{} 0.0+2.23606797749979i ; approximately
  8678. (sqrt +inf.0) @result{} +inf.0
  8679. (sqrt -inf.0) @result{} +inf.0i
  8680. @end example
  8681. Note that if the argument is a primitive number (such as @code{double}) or an
  8682. instance of the corresponding boxed class (such as @code{java.lang.Double})
  8683. then we use the real-number version of @code{sqrt}:
  8684. @example
  8685. (sqrt (->double -5)) @result{} NaN
  8686. @end example
  8687. That is, we get different a result for @code{java.lang.Double}
  8688. and @code{gnu.math.DFloNum}, even for arguments that are numerically equal
  8689. in the sense of @code{=}.
  8690. This is so that the compiler can use the @code{java.lang.Math.sqrt}
  8691. method without object allocation when the argument is a @code{double}
  8692. (and because we want @code{double} and @code{java.lang.Double} to behave
  8693. consistently).
  8694. @end deffn
  8695. @deffn Procedure exact-integer-sqrt @var{k}
  8696. The @func{exact-integer-sqrt} procedure returns two non--negative exact
  8697. integer objects @emph{s} and @emph{r} where @code{@var{k} = s^2 + r} and
  8698. @code{@var{k} < (s+1)^2}.
  8699. @example
  8700. (exact-integer-sqrt 4) @result{} 2 0 ; two return values
  8701. (exact-integer-sqrt 5) @result{} 2 1 ; two return values
  8702. @end example
  8703. @end deffn
  8704. @deffn Procedure expt @vari{z} @varii{z}
  8705. Returns @vari{z} raised to the power @varii{z}.
  8706. For nonzero @vari{z}, this is
  8707. @vari{z}@sup{@varii{z}} = @var{e}@sup{@varii{z} log @vari{z}}.
  8708. The value of 0@sup{@var{z}} is 1 if @code{(zero? @var{z})},
  8709. 0 if @code{(real-part @var{z})} is positive, and an error otherwise.
  8710. Similarly for 0.0@sup{z}, with inexact results.
  8711. @end deffn
  8712. @node Numerical input and output
  8713. @section Numerical input and output
  8714. @deffn Procedure number->string z [radix]
  8715. The procedure @code{number->string} takes a number and a
  8716. radix and returns as a string an external representation
  8717. of the given number in the given radix such that
  8718. @example
  8719. (let ((number number)
  8720. (radix radix))
  8721. (eqv? number
  8722. (string->number (number->string number radix)
  8723. radix)))
  8724. @end example
  8725. is true. It is an error if no possible result makes this expression true.
  8726. If present, @var{radix} must be an exact integer
  8727. in the range 2 to 36, inclusive.
  8728. If omitted, @var{radix} defaults to 10.
  8729. If @var{z} is inexact, the @var{radix} is 10, and the above expression
  8730. can be satisfied by a result that contains a decimal point,
  8731. then the result contains a decimal point and is expressed
  8732. using the minimum number of digits (exclusive of exponent
  8733. and trailing zeroes) needed to make the above expression;
  8734. otherwise the format of the result is unspecified.
  8735. The result returned by @code{number->string} never contains an
  8736. explicit radix prefix.
  8737. @emph{Note:}
  8738. The error case can occur only when @var{z} is not a complex
  8739. number or is a complex number with a non-rational real or
  8740. imaginary part.
  8741. @emph{Rationale:} If @var{z} is an inexact number and the @var{radix} is 10,
  8742. then the above expression is normally satisfied by a result containing
  8743. a decimal point. The unspecified case allows for infinities, NaNs,
  8744. and unusual representations.
  8745. @end deffn
  8746. @deffn Procedure string->number string [radix]
  8747. Returns a number of the maximally precise representation
  8748. expressed by the given @var{string}. It is an error if @var{radix} is not
  8749. an exact integer in the range 2 to 26, inclusive.
  8750. If supplied, @var{radix} is a default radix that will be overridden
  8751. if an explicit radix prefix is present in the string (e.g.
  8752. @code{"#o177"}). If @var{radix} is not supplied, then the default @var{radix}
  8753. is 10. If @var{string} is not a syntactically valid notation for a
  8754. number, or would result in a number that the implementation cannot represent,
  8755. then @code{string->number} returns @code{#f}.
  8756. An error is never signaled due to the content of @var{string}.
  8757. @example
  8758. (string->number "100") @result{} 100
  8759. (string->number "100" 16) @result{} 256
  8760. (string->number "1e2") @result{} 100.0
  8761. (string->number "#x100" 10) @result{} 256
  8762. @end example
  8763. @end deffn
  8764. @node Quaternions
  8765. @section Quaternions
  8766. Kawa extends the Scheme numeric tower to include
  8767. @uref{http://en.wikipedia.org/wiki/Quaternion,quaternions} as a proper
  8768. superset of the complex numbers. Quaternions provide a convenient
  8769. notation to represent
  8770. @uref{http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation,rotations in three-dimensional space},
  8771. and are therefore commonly found in applications such as computer
  8772. graphics, robotics, and spacecraft engineering. The Kawa quaternion API
  8773. is modeled after
  8774. @uref{http://www.ccs.neu.edu/home/dorai/squat/squat.html,this} with some
  8775. additions.
  8776. A quaternion is a number that can be expressed in the form
  8777. @samp{w+xi+yj+zk}, where @code{w}, @code{x}, @code{y}, and @code{z} are
  8778. real, and @code{i}, @code{j}, and @code{k} are imaginary units
  8779. satisfying @math{i@sup{2} = j@sup{2} = k@sup{2} = ijk = -1}. The magnitude of a
  8780. quaternion is defined to be its Euclidean norm when viewed as a point in
  8781. @math{R@sup{4}}.
  8782. The real--part of a quaternion is also called its @samp{scalar}, while
  8783. the i--part, j--part, and k--part taken together are also called its
  8784. @samp{vector}. A quaternion with zero j--part and k--part is an
  8785. ordinary complex number. (If the i--part is also zero, then it is a
  8786. real). A quaternion with zero real--part is called a
  8787. @samp{vector quaternion}.
  8788. The reader syntax for number literals has been extended to support both
  8789. rectangular and polar (hyperspherical) notation for quaternions. The
  8790. rectangular notation is as above, i.e. @code{w+xi+yj+zk}. The polar
  8791. notation takes the form @code{r@@t%u&v}, where @code{r} is the
  8792. magnitude, @code{t} is the first angle, and @code{u} and @code{v} are
  8793. two other angles called the ``colatitude'' and ``longitude''.
  8794. The rectangular coordinates and polar coordinates are related by the
  8795. equations:
  8796. @example
  8797. @var{w} = @var{r} * cos @var{t}
  8798. @var{x} = @var{r} * sin @var{t} * cos @var{u}
  8799. @var{y} = @var{r} * sin @var{t} * sin @var{u} * cos @var{v}
  8800. @var{z} = @var{r} * sin @var{t} * sin @var{u} * sin @var{v}
  8801. @end example
  8802. With either notation, zero elements may be omitted.
  8803. @deffn Procedure make-rectangular @var{w} @var{x}
  8804. @deffnx Procedure make-rectangular @var{w} @var{x} @var{y} @var{z}
  8805. These procedures construct quaternions from Cartesian coordinates.
  8806. @end deffn
  8807. @deffn Procedure make-polar @var{r} @var{t}
  8808. @deffnx Procedure make-polar @var{r} @var{t} @var{u} @var{v}
  8809. These procedures construct quaternions from polar coordinates.
  8810. @end deffn
  8811. @deffn Procedure + @var{q} @dots{}
  8812. @deffnx Procedure - @var{q} @dots{}
  8813. @deffnx Procedure * @var{q} @dots{}
  8814. @deffnx Procedure / @var{q}
  8815. @deffnx Procedure / @vari{q} @varii{q} @variii{q} @dots{}
  8816. @deffnx Procedure expt @vari{q} @varii{q}
  8817. @deffnx Procedure exp @var{q}
  8818. @deffnx Procedure log @var{q}
  8819. @deffnx Procedure sqrt @var{q}
  8820. @deffnx Procedure sin @var{q}
  8821. @deffnx Procedure cos @var{q}
  8822. @deffnx Procedure tan @var{q}
  8823. @deffnx Procedure asin @var{q}
  8824. @deffnx Procedure acos @var{q}
  8825. @deffnx Procedure atan @var{q}
  8826. All of the arithmetic and transcendental functions defined for complex
  8827. arguments have been extended to support quaternions.
  8828. Quaternion multiplication is not commutative, so there are two possible
  8829. interpretations of @code{(/ q1 q2)} which would yield different results:
  8830. either @code{(* q1 (/ q2))}, or @code{(* (/ q2) q1)}. Division in this
  8831. implementation has been defined such that @code{(/ q1 q2 ...)} is
  8832. equivalent to @code{(* q1 (/ q2) ...)}, but it is recommended to
  8833. use reciprocals (unary @code{/}) and multiplication.
  8834. @end deffn
  8835. @deffn Procedure real-part @var{q}
  8836. Return the real--part of @var{q}.
  8837. @example
  8838. (real-part 0) @result{} 0
  8839. (real-part -i) @result{} 0
  8840. (real-part 1+2i-3j+4k) @result{} 1
  8841. @end example
  8842. @end deffn
  8843. @deffn Procedure imag-part @var{q}
  8844. Return the i--part of @var{q}.
  8845. @example
  8846. (imag-part 0) @result{} 0
  8847. (imag-part -i) @result{} -1
  8848. (imag-part 1+2i-3j+4k) @result{} 2
  8849. @end example
  8850. @end deffn
  8851. @deffn Procedure magnitude @var{q}
  8852. Return the Euclidean norm of @var{q}. If @var{q} is @code{a+bi+cj+dk},
  8853. then @code{(magnitude q)} is
  8854. @code{(sqrt (apply + (map square (list a b c d))))}
  8855. @end deffn
  8856. @deffn Procedure angle @var{q}
  8857. Return the angle of @var{q}.
  8858. @end deffn
  8859. @subsection The @code{(kawa quaternions)} module
  8860. The following additional functionality is made available by doing one
  8861. of:
  8862. @example
  8863. (require 'quaternions) ;; or
  8864. (import (kawa quaternions))
  8865. @end example
  8866. @deffn Alias quaternion
  8867. An alias for @code{gnu.math.Quaternion}, useful for type declarations.
  8868. @end deffn
  8869. @deffn Procedure {quaternion?} @var{x}
  8870. Return @true{} if @var{x} is a quaternion, i.e. an ordinary number, and
  8871. @false{} otherwise.
  8872. @example
  8873. (quaternion? 0) @result{} #t
  8874. (quaternion? -i) @result{} #t
  8875. (quaternion? 1+2i-3j+4k) @result{} #t
  8876. (quaternion? 10.0m) @result{} #f
  8877. (quaternion? "x") @result{} #f
  8878. @end example
  8879. @end deffn
  8880. @deffn Procedure jmag-part @var{q}
  8881. Return the j--part of @var{q}.
  8882. @example
  8883. (jmag-part 0) @result{} 0
  8884. (jmag-part -i) @result{} 0
  8885. (jmag-part 1+2i-3j+4k) @result{} -3
  8886. @end example
  8887. @end deffn
  8888. @deffn Procedure kmag-part @var{q}
  8889. @example
  8890. (kmag-part 0) @result{} 0
  8891. (kmag-part -i) @result{} 0
  8892. (kmag-part 1+2i-3j+4k) @result{} 4
  8893. @end example
  8894. @end deffn
  8895. @deffn Procedure complex-part @var{q}
  8896. Return the projection of @var{q} into the complex plane:
  8897. @code{(+ (real-part q) (* +i (imag-part q)))}
  8898. @example
  8899. (complex-part 0) @result{} 0
  8900. (complex-part -i) @result{} -1i
  8901. (complex-part 1+2i-3j+4k) @result{} 1+2i
  8902. @end example
  8903. @end deffn
  8904. @deffn Procedure vector-part @var{q}
  8905. Return the vector--part of @var{q}.
  8906. @example
  8907. (vector-part 0) @result{} 0
  8908. (vector-part -i) @result{} -1i
  8909. (vector-part 1+2i-3j+4k) @result{} +2i-3j+4k
  8910. @end example
  8911. @end deffn
  8912. @deffn Procedure unit-quaternion @var{q}
  8913. Return a quaternion of unit magnitude with the same direction as
  8914. @var{q}. If @var{q} is zero, return zero. This is like a 4D version of
  8915. a signum function.
  8916. @example
  8917. (unit-quaternion 0) @result{} 0
  8918. (unit-quaternion -i) @result{} -1i
  8919. (unit-quaternion 1+2i-3j+4k) @result{} 0.18257418583505536+0.3651483716701107i-0.5477225575051661j+0.7302967433402214k
  8920. @end example
  8921. @end deffn
  8922. @deffn Procedure unit-vector @var{q}
  8923. Return the vector--part of @var{q}, scaled to have magnitude 1. If the
  8924. vector--part is zero, then return zero.
  8925. @example
  8926. (unit-vector 0) @result{} 0
  8927. (unit-vector -i) @result{} -1i
  8928. (unit-vector 1+2i-3j+4k) @result{} +0.3713906763541037i-0.5570860145311556j+0.7427813527082074k
  8929. @end example
  8930. @end deffn
  8931. @deffn Procedure colatitude @var{q}
  8932. Return the colatitude of @var{q}.
  8933. @end deffn
  8934. @deffn Procedure longitude @var{q}
  8935. Return the longitude of @var{q}.
  8936. @end deffn
  8937. @deffn Procedure {vector-quaternion?} @var{obj}
  8938. Return @true{} if @var{obj} is a vector quaternion, i.e. a quaternion
  8939. with zero real--part.
  8940. @end deffn
  8941. @deffn Procedure make-vector-quaternion @var{x} @var{y} @var{z}
  8942. Construct vector quaternion @code{xi+yj+zk}. This is equivalent to
  8943. @code{(make-rectangular 0 x y z)}.
  8944. @end deffn
  8945. @deffn Procedure {vector-quaternion->list} @var{vq}
  8946. Return a newly allocated list of the x, y, and z components of
  8947. @var{vq}. This is equivalent to
  8948. @code{(list (imag-part vq) (jmag-part vq) (kmag-part vq))}.
  8949. @end deffn
  8950. @deffn Procedure dot-product @vari{q} @varii{q}
  8951. For two vector quaternions @vari{q} = @code{ai+bj+ck} and @varii{q} =
  8952. @code{di+ej+fk}, return @code{ad + be + cf}. This is equal to the
  8953. @math{R^3} dot product for vectors @math{(a,b,c)} and @math{(d,e,f)},
  8954. and is also equal to @code{(- (real-part (* q1 q2)))}. It is an error
  8955. if either @vari{q} or @varii{q} has a non-zero real--part.
  8956. @end deffn
  8957. @deffn Procedure cross-product @vari{q} @varii{q}
  8958. For two vector quaternions @vari{q} = @code{ai+bj+ck} and @varii{q} =
  8959. @code{di+ej+fk}, return the @math{R^3} cross product for vectors
  8960. @math{(a,b,c)} and @math{(d,e,f)}, which is equal to
  8961. @code{(vector-part (* q1 q2))}. It is an error
  8962. if either @vari{q} or @varii{q} has a non-zero real--part.
  8963. @end deffn
  8964. @deffn Procedure conjugate @var{q}
  8965. Return @code{(+ (real-part q) (* -1 (vector-part q)))}.
  8966. @example
  8967. (conjugate 0) @result{} 0
  8968. (conjugate -i) @result{} +1i
  8969. (conjugate 1+2i-3j+4k) @result{} 1-2i+3j-4k
  8970. @end example
  8971. @end deffn
  8972. @subsection The @code{(kawa rotations)} module
  8973. The @code{(kawa rotations)} library provides a set of functions which
  8974. use unit quaternions to represent 3D spatial rotations. To use these
  8975. functions, the library must be imported:
  8976. @example
  8977. (import (kawa rotations))
  8978. @end example
  8979. These functions normalize their quaternion inputs as needed to be of
  8980. length 1.
  8981. @subsubsection Rotation Representation Conversions
  8982. Conversions to and from several alternate representations of rotations
  8983. are supported.
  8984. The set of unit quaternions provides a double covering of all
  8985. possible 3D rotations: @code{q} and @code{-q} represent the same
  8986. rotation. Most other representations also have multiple numerical
  8987. values which map to the same rotation (for example, the rotation about
  8988. @code{axis-vec} by @code{angle} is the same as the rotation about
  8989. @code{-axis-vec} by @code{-angle+2pi}). Therefore, these functions do
  8990. not necessarily act as inverses in the sense of @func{equal?}.
  8991. Furthermore, rotations involve trigonometric functions, so there will
  8992. typically be some floating point error: @code{(acos (cos 0.1))} returns
  8993. 0.09999999999999945, which is very close to 0.1 but not exact.
  8994. @subsubheading Rotation Matrices
  8995. @deffn Procedure {quaternion->rotation-matrix} @var{q}
  8996. @deffnx Procedure {rotation-matrix->quaternion} @var{m}
  8997. The @func{quaternion->rotation-matrix} procedure returns a 3x3 rotation
  8998. matrix representing the same rotation as @var{q}. The rotation matrix
  8999. is instantiated as a @ref{Arrays,SRFI-25 multi-dimensional array} backed
  9000. by an @ref{Uniform vectors,f64vector}.
  9001. The @func{rotation-matrix->quaternion} procedure performs the reverse
  9002. operation, producing an equivalent unit quaternion for the rotation
  9003. matrix (multi-dimensional array) @var{m}.
  9004. @example
  9005. (rotation-matrix->quaternion (quaternion->rotation-matrix -1)) @result{} 1.0
  9006. @end example
  9007. @end deffn
  9008. @subsubheading Axis-Angle Representation
  9009. @deffn Procedure rotation-axis @var{q}
  9010. @deffnx Procedure rotation-angle @var{q}
  9011. @deffnx Procedure rotation-axis/angle @var{q}
  9012. The @func{rotation-axis} procedure returns the axis of rotation of the
  9013. quaternion @var{q} as a unit-length vector quaternion. If the axis of
  9014. rotation is not well-defined (the angle of rotation is 0), then
  9015. @code{+i} is arbitrarily chosen as the axis.
  9016. The @func{rotation-angle} procedure returns the corresponding angle of
  9017. rotation. Note that this is not the same as the result of the
  9018. @func{angle} procedure.
  9019. The @func{rotation-axis/angle} procedure returns the rotation axis and
  9020. angle as multiple values.
  9021. @example
  9022. (let* ((q 1/2+1/2i+1/2j+1/2k)
  9023. (ar (rotation-angle q))
  9024. (ad (java.lang.Math:toDegrees ar))
  9025. (exact-ad (exact ad)))
  9026. (rationalize exact-ad 1/10)) @result{} 120
  9027. @end example
  9028. @end deffn
  9029. @deffn Procedure {make-axis/angle} @var{axis-vec} @var{angle}
  9030. @deffnx Procedure {make-axis/angle} @var{axis-x} @var{axis-y} @var{axis-z} @var{angle}
  9031. The @func{make-axis/angle} procedure returns a quaternion representing
  9032. the given axis/angle rotation. The axis is specified as either a single
  9033. vector quaternion argument @var{axis-vec}, or as three reals
  9034. @var{axis-x}, @var{axis-y}, and @var{axis-z}.
  9035. @end deffn
  9036. @deffn Procedure rotx @var{angle}
  9037. @deffnx Procedure roty @var{angle}
  9038. @deffnx Procedure rotz @var{angle}
  9039. The procedures @func{rotx}, @func{roty}, and @func{rotz} return
  9040. quaternions representing rotations about the X-, Y-, and Z-axes.
  9041. @end deffn
  9042. @subsubheading Intrinsic Angle Sets
  9043. The intrinsic angle sets represent arbitrary rotations as a sequence of
  9044. three rotations about coordinate frame axes attached to the rotating
  9045. body (i.e. the axes rotate with the body).
  9046. There are twelve possible angle sets which neatly divide into two groups
  9047. of six. The six with same first and third axes are also known as
  9048. ``Euler angles''. The six with different first and third axes are also
  9049. known as ``Tait-Bryan angles''.
  9050. @deffn Procedure intrinsic-xyx @var{q}
  9051. @deffnx Procedure intrinsic-xzx @var{q}
  9052. @deffnx Procedure intrinsic-yxy @var{q}
  9053. @deffnx Procedure intrinsic-yzy @var{q}
  9054. @deffnx Procedure intrinsic-zxz @var{q}
  9055. @deffnx Procedure intrinsic-zyz @var{q}
  9056. These functions decompose the rotation represented by @var{q} into Euler
  9057. angles of the given set (XYX, XZX, YXY, YZY, ZXZ, or ZYZ) and returns
  9058. the three angles as multiple values. The middle angle will be in the
  9059. range [0,pi]. If it is on the edges of that range (within 1.0E-12 of 0
  9060. or pi), such that the first and third axes are colinear, then the first
  9061. angle will be set to 0.
  9062. @example
  9063. (intrinsic-zyz (* (rotz 0.3) (roty 0.8) (rotz -0.6))) @result{} 0.3000000000000001 0.7999999999999999 -0.5999999999999999
  9064. @end example
  9065. @end deffn
  9066. @deffn Alias euler-xyx
  9067. @deffnx Alias euler-xzx
  9068. @deffnx Alias euler-yxy
  9069. @deffnx Alias euler-yzy
  9070. @deffnx Alias euler-zxz
  9071. @deffnx Alias euler-zyz
  9072. Aliases for the corresponding @code{intrinsic-} procedures.
  9073. @end deffn
  9074. @deffn Procedure intrinsic-xyz @var{q}
  9075. @deffnx Procedure intrinsic-xzy @var{q}
  9076. @deffnx Procedure intrinsic-yxz @var{q}
  9077. @deffnx Procedure intrinsic-yzx @var{q}
  9078. @deffnx Procedure intrinsic-zxy @var{q}
  9079. @deffnx Procedure intrinsic-zyx @var{q}
  9080. These functions decompose the rotation represented by @var{q} into
  9081. Tait-Bryan angles of the given set (XYZ, XZY, YXZ, YZX, ZXY, or ZYX) and
  9082. returns the three angles as multiple values. The middle angle will be
  9083. in the range [-pi/2,pi/2]. If it is on the edges of that range, such
  9084. that the first and third axes are colinear, then the first angle will be
  9085. set to 0.
  9086. @end deffn
  9087. @deffn Alias tait-bryan-xyz
  9088. @deffnx Alias tait-bryan-xzy
  9089. @deffnx Alias tait-bryan-yxz
  9090. @deffnx Alias tait-bryan-yzx
  9091. @deffnx Alias tait-bryan-zxy
  9092. @deffnx Alias tait-bryan-zyx
  9093. Aliases for the corresponding @code{intrinsic-} procedures.
  9094. @end deffn
  9095. @deffn Procedure make-intrinsic-xyx @var{alpha} @var{beta} @var{gamma}
  9096. @deffnx Procedure make-intrinsic-xzx @var{alpha} @var{beta} @var{gamma}
  9097. @deffnx Procedure make-intrinsic-yxy @var{alpha} @var{beta} @var{gamma}
  9098. @deffnx Procedure make-intrinsic-yzy @var{alpha} @var{beta} @var{gamma}
  9099. @deffnx Procedure make-intrinsic-zxz @var{alpha} @var{beta} @var{gamma}
  9100. @deffnx Procedure make-intrinsic-zyz @var{alpha} @var{beta} @var{gamma}
  9101. These functions return quaternions representing the given Euler angle
  9102. rotations.
  9103. @end deffn
  9104. @deffn Alias make-euler-xyx
  9105. @deffnx Alias make-euler-xzx
  9106. @deffnx Alias make-euler-yxy
  9107. @deffnx Alias make-euler-yzy
  9108. @deffnx Alias make-euler-zxz
  9109. @deffnx Alias make-euler-zyz
  9110. Aliases for the corresponding @code{make-intrinsic-} procedures.
  9111. @example
  9112. (let-values (((a b c) (euler-xyx (make-euler-xyx 1.0 0.0 2.0))))
  9113. (list a b c)) @result{} (0.0 0.0 3.0)
  9114. @end example
  9115. @end deffn
  9116. @deffn Procedure make-intrinsic-xyz @var{alpha} @var{beta} @var{gamma}
  9117. @deffnx Procedure make-intrinsic-xzy @var{alpha} @var{beta} @var{gamma}
  9118. @deffnx Procedure make-intrinsic-yxz @var{alpha} @var{beta} @var{gamma}
  9119. @deffnx Procedure make-intrinsic-yzx @var{alpha} @var{beta} @var{gamma}
  9120. @deffnx Procedure make-intrinsic-zxy @var{alpha} @var{beta} @var{gamma}
  9121. @deffnx Procedure make-intrinsic-zyx @var{alpha} @var{beta} @var{gamma}
  9122. These functions return quaternions representing the given Tait-Bryan
  9123. angle rotations.
  9124. @end deffn
  9125. @deffn Alias make-tait-bryan-xyz
  9126. @deffnx Alias make-tait-bryan-xzy
  9127. @deffnx Alias make-tait-bryan-yxz
  9128. @deffnx Alias make-tait-bryan-yzx
  9129. @deffnx Alias make-tait-bryan-zxy
  9130. @deffnx Alias make-tait-bryan-zyx
  9131. Aliases for the corresponding @code{make-intrinsic-} procedures.
  9132. @end deffn
  9133. @subsubheading Extrinsic Angle Sets
  9134. The extrinsic angle sets represent arbitrary rotations as a sequence of
  9135. three rotations about fixed-frame axes (i.e. the axes do not rotate with
  9136. the body).
  9137. There are twelve possible extrinsic angle sets, and each is the dual of
  9138. an intrinsic set. The extrinsic rotation about axes @code{A}, @code{B},
  9139. and @code{C} by angles @code{a}, @code{b}, and @code{c} is the same as
  9140. the intrinsic rotation about axes @code{C}, @code{B}, and @code{A} by
  9141. angles @code{c}, @code{b}, and @code{a}, with the order of the three
  9142. axes reversed.
  9143. @deffn Procedure extrinsic-xyx @var{q}
  9144. @deffnx Procedure extrinsic-xyz @var{q}
  9145. @deffnx Procedure extrinsic-xzx @var{q}
  9146. @deffnx Procedure extrinsic-zxy @var{q}
  9147. @deffnx Procedure extrinsic-yxy @var{q}
  9148. @deffnx Procedure extrinsic-yxz @var{q}
  9149. @deffnx Procedure extrinsic-yzx @var{q}
  9150. @deffnx Procedure extrinsic-yzy @var{q}
  9151. @deffnx Procedure extrinsic-zxy @var{q}
  9152. @deffnx Procedure extrinsic-zxz @var{q}
  9153. @deffnx Procedure extrinsic-zyx @var{q}
  9154. @deffnx Procedure extrinsic-zyz @var{q}
  9155. These functions decompose the rotation represented by @var{q} into
  9156. extrinsic angles of the given set and returns the three angles as
  9157. multiple values.
  9158. @end deffn
  9159. @deffn Procedure make-extrinsic-xyx @var{gamma} @var{beta} @var{alpha}
  9160. @deffnx Procedure make-extrinsic-xyz @var{gamma} @var{beta} @var{alpha}
  9161. @deffnx Procedure make-extrinsic-xzx @var{gamma} @var{beta} @var{alpha}
  9162. @deffnx Procedure make-extrinsic-xzy @var{gamma} @var{beta} @var{alpha}
  9163. @deffnx Procedure make-extrinsic-yxy @var{gamma} @var{beta} @var{alpha}
  9164. @deffnx Procedure make-extrinsic-yxz @var{gamma} @var{beta} @var{alpha}
  9165. @deffnx Procedure make-extrinsic-yzx @var{gamma} @var{beta} @var{alpha}
  9166. @deffnx Procedure make-extrinsic-yzy @var{gamma} @var{beta} @var{alpha}
  9167. @deffnx Procedure make-extrinsic-zxy @var{gamma} @var{beta} @var{alpha}
  9168. @deffnx Procedure make-extrinsic-zxz @var{gamma} @var{beta} @var{alpha}
  9169. @deffnx Procedure make-extrinsic-zyx @var{gamma} @var{beta} @var{alpha}
  9170. @deffnx Procedure make-extrinsic-zyz @var{gamma} @var{beta} @var{alpha}
  9171. These functions return quaternions representing the given extrinsic
  9172. angle rotations.
  9173. @end deffn
  9174. @deffn Alias rpy
  9175. @deffnx Alias make-rpy
  9176. Aliases for @func{extrinsic-xyz} and @func{make-extrinsic-xyz}.
  9177. @example
  9178. (let ((r (make-rpy 0.12 -0.23 0.34)))
  9179. (let-values (((a b c) (tait-bryan-zyx r)))
  9180. (list a b c))) @result{} (0.3400000000000001 -0.2300000000000001 0.12000000000000002)
  9181. @end example
  9182. @end deffn
  9183. @subsubsection Rotation Operations
  9184. @deffn Procedure rotate-vector @var{rq} @var{vq}
  9185. Applies the rotation represented by quaternion @var{rq} to the vector
  9186. represented by vector quaternion @var{vq}, and returns the rotated
  9187. vector. This is equivalent to @code{(* rq vq (conjugate rq))} for
  9188. normalized @var{rq}.
  9189. @example
  9190. (rotate-vector +k +2i) @result{} -2i
  9191. (rotate-vector 1/2+1/2i+1/2j+1/2k +i+2j+3k) @result{} +3.0i+1.0j+2.0k
  9192. @end example
  9193. @end deffn
  9194. @deffn Procedure make-rotation-procedure @var{rq}
  9195. A partial application of @func{rotate-vector}. Returns a
  9196. single-argument procedure which will take a vector quaternion argument
  9197. and rotate it by @var{rq}. The returned procedure closes over both
  9198. @var{rq} and its conjugate, so this will likely be more efficient than
  9199. @func{rotate-vector} at rotating many vectors by the same rotation.
  9200. @end deffn
  9201. @node Quantities
  9202. @section Quantities and Units
  9203. As a super-class of numbers, Kawa also provides quantities.
  9204. A @dfn{quantity} is a product of a @dfn{unit} and a pure number.
  9205. The number part can be an arbitrary complex number.
  9206. The unit is a product of integer powers of base units,
  9207. such as meter or second.
  9208. Quantity literals have the following syntax:
  9209. @display
  9210. @stxdef{quantity} @stxref{optional-sign} @stxref{decimal} @stxref{unit-term} [@stxlit{*} @stxref{unit-term}]... [@stxlit{/} @stxref{unit-term}]
  9211. @stxdef{unit-term} @stxref{unit-name} [@stxlit{^} @stxref{digit}+]
  9212. @stxdef{unit-name} @stxref{letter}+
  9213. @end display
  9214. Some examples are @code{10pt} (10 points), @code{5s} (5 seconds),
  9215. and @code{4cm^2} (4 square centimeters).
  9216. Note the @var{quantity} syntax is not recognized by the reader.
  9217. Instead these are read as symbols.
  9218. Assuming there is no lexical binding the for the symbol, it will be
  9219. rewritten at compile-time into an expression. For example @code{4cm^2}
  9220. is transformed into:
  9221. @example
  9222. (* 4.0 (expt unit:cm 2))
  9223. @end example
  9224. @deffn Procedure quantity? object
  9225. True iff @var{object} is a quantity. Note that all numbers are
  9226. quantities, but not the other way round.
  9227. Currently, there are no quantities that are not numbers.
  9228. To distinguish a plain unit-less number from a quantity,
  9229. you can use @code{complex?}.
  9230. @end deffn
  9231. @c FIXME Using @code{complex?} as the test would erroneously classify
  9232. @c @code{1+j} as non-plain. The right test would be @code{quaternion?},
  9233. @c though that requires importing the (kawa quaternions) module.
  9234. @deffn Procedure quantity->number q
  9235. Returns the pure number part of the quantity @var{q}, relative to
  9236. primitive (base) units.
  9237. If @var{q} is a number, returns @var{q}.
  9238. If @var{q} is a unit, yields the magitude of @var{q} relative to base units.
  9239. @end deffn
  9240. @deffn Procedure quantity->unit q
  9241. Returns the unit of the quantity @var{q}.
  9242. If @var{q} is a number, returns the empty unit.
  9243. @end deffn
  9244. @deffn Procedure make-quantity x unit
  9245. Returns the product of @var{x} (a pure number) and @var{unit}.
  9246. You can specify a string instead of @var{unit}, such as @code{"cm"}
  9247. or @code{"s"} (seconds).
  9248. @end deffn
  9249. @deffn Syntax define-base-unit unit-name dimension
  9250. Define @var{unit-name} as a base (primitive) unit,
  9251. which is used to measure along the specified @var{dimension}.
  9252. @example
  9253. (define-base-unit dollar "Money")
  9254. @end example
  9255. @end deffn
  9256. @deffn Syntax define-unit unit-name expression
  9257. Define @var{unit-name} as a unit (that can be used in literals)
  9258. equal to the quantity @var{expression}.
  9259. @example
  9260. (define-unit cent 0.01dollar)
  9261. @end example
  9262. The @var{unit-name} is declared in the @code{unit} namespace,
  9263. so the above is equivalent to:
  9264. @example
  9265. (define-constant unit:cent (* 0.01 unit:dollar))
  9266. @end example
  9267. @end deffn
  9268. @subheading Angles
  9269. The following angle units are dimensionless, with no base unit.
  9270. Some procedures treat a unit-less real number as if it were in radians
  9271. (which mathematicians prefer);
  9272. some procedures (such as @code{rotate}) treat a unit-less real number
  9273. as if it were in degrees
  9274. (which is common in Web and other standards).
  9275. @deffn Unit rad
  9276. A unit for angles specified in radians.
  9277. A full circle is 2*pi radians.
  9278. Note that @code{(= 1.5 1.5rad)} is true,
  9279. while @code{(eqv? 1.5 1.5rad)} is false.
  9280. @end deffn
  9281. @deffn Unit deg
  9282. A unit for angles specified in degrees.
  9283. A full circle is 360 degrees.
  9284. @end deffn
  9285. @deffn Unit grad
  9286. A unit for angles specified in gradians.
  9287. A full circle is 400 gradians.
  9288. @end deffn
  9289. @node Logical Number Operations
  9290. @section Logical Number Operations
  9291. These functions operate on the 2's complement binary representation
  9292. of an exact integer.
  9293. @deffn Procedure bitwise-not i
  9294. Returns the bit-wise logical inverse of the argument.
  9295. More formally, returns the exact integer whose two's
  9296. complement representation is the one's complement of the two's
  9297. complement representation of @var{i}.
  9298. @end deffn
  9299. @deffn Procedure bitwise-and i ...
  9300. @deffnx Procedure bitwise-ior i ...
  9301. @deffnx Procedure bitwise-xor i ...
  9302. These procedures return the exact integer that is the bit-wise
  9303. ``and'', ``inclusive or'', or ``exclusive or'' of the two's
  9304. complement representations of their arguments.
  9305. If they are passed only one argument, they return that argument.
  9306. If they are passed no arguments, they return the integer
  9307. that acts as identity for the operation: -1, 0, or 0, respectively.
  9308. @end deffn
  9309. @deffn Procedure bitwise-if i1 i2 i3
  9310. Returns the exact integer that is the bit-wise ``if'' of the twos
  9311. complement representations of its arguments, i.e. for each bit, if it
  9312. is 1 in i1, the corresponding bit in i2 becomes the value of the
  9313. corresponding bit in the result, and if it is 0, the corresponding bit
  9314. in i3 becomes the corresponding bit in the value of the result. This
  9315. is equivaent to the following computation:
  9316. @example
  9317. (bitwise-ior (bitwise-and i1 i2)
  9318. (bitwise-and (bitwise-not i1) i3))
  9319. @end example
  9320. @end deffn
  9321. @deffn Procedure bitwise-bit-count i
  9322. If i is non-negative, returns the number of 1 bits in the twos complement
  9323. representation of i. Otherwise it returns the result of the following
  9324. computation:
  9325. @example
  9326. (bitwise-not (bitwise-bit-count (bitwise-not i)))
  9327. @end example
  9328. @end deffn
  9329. @deffn Procedure bitwise-length i
  9330. Returns the number of bits needed to represent i if it is positive,
  9331. and the number of bits needed to represent @code{(bitwise-not @var{i})}
  9332. if it is negative, which is the exact integer that is the result of the
  9333. following computation:
  9334. @example
  9335. (do ((result 0 (+ result 1))
  9336. (bits (if (negative? i)
  9337. (bitwise-not i)
  9338. ei)
  9339. (bitwise-arithmetic-shift bits -1)))
  9340. ((zero? bits)
  9341. result))
  9342. @end example
  9343. This is the number of bits needed to represent @var{i} in an unsigned field.
  9344. @end deffn
  9345. @deffn Procedure bitwise-first-bit-set i
  9346. Returns the index of the least significant 1 bit in the twos complement
  9347. representation of i. If i is 0, then - 1 is returned.
  9348. @example
  9349. (bitwise-first-bit-set 0) @result{} -1
  9350. (bitwise-first-bit-set 1) @result{} 0
  9351. (bitwise-first-bit-set -4) @result{} 2
  9352. @end example
  9353. @end deffn
  9354. @deffn Procedure bitwise-bit-set? i1 i2
  9355. Returns @code{#t} if the i2'th bit (where @var{i2} must be non-negative)
  9356. is 1 in the two's complement representation of @var{i1}, and @code{#f}
  9357. otherwise. This is the result of the following computation:
  9358. @example
  9359. (not (zero?
  9360. (bitwise-and
  9361. (bitwise-arithmetic-shift-left 1 i2)
  9362. i1)))
  9363. @end example
  9364. @end deffn
  9365. @deffn Procedure bitwise-copy-bit i bitno replacement-bit
  9366. Returns the result of replacing the @var{bitno}'th bit of @var{i}
  9367. by @var{replacement-bit}, where @var{bitno} must be non-negative,
  9368. and @var{replacement-bit} must be either 0 or 1.
  9369. This is the result of the following computation:
  9370. @example
  9371. (let* ((mask (bitwise-arithmetic-shift-left 1 bitno)))
  9372. (bitwise-if mask
  9373. (bitwise-arithmetic-shift-left replacement-bit bitno)
  9374. i))
  9375. @end example
  9376. @end deffn
  9377. @deffn Procedure bitwise-bit-field n start end
  9378. Returns the integer formed from the (unsigned) bit-field
  9379. starting at @var{start} and ending just before @var{end}.
  9380. Same as:
  9381. @example
  9382. (let ((mask
  9383. (bitwise-not
  9384. (bitwise-arithmetic-shift-left -1 @var{end}))))
  9385. (bitwise-arithmetic-shift-right
  9386. (bitwise-and @var{n} mask)
  9387. @var{start}))
  9388. @end example
  9389. @end deffn
  9390. @deffn Procedure bitwise-copy-bit-field to start end from
  9391. Returns the result of replacing in @var{to} the bits at positions from @var{start} (inclusive) to @var{end} (exclusive) by the bits in @var{from} from position 0 (inclusive) to position @var{end} - @var{start} (exclusive).
  9392. Both @var{start} and @var{start} must be non-negative,
  9393. and @var{start} must be less than or equal to @var{start}.
  9394. This is the result of the following computation:
  9395. @example
  9396. (let* ((mask1
  9397. (bitwise-arithmetic-shift-left -1 start))
  9398. (mask2
  9399. (bitwise-not
  9400. (bitwise-arithmetic-shift-left -1 end)))
  9401. (mask (bitwise-and mask1 mask2)))
  9402. (bitwise-if mask
  9403. (bitwise-arithmetic-shift-left from
  9404. start)
  9405. to))
  9406. @end example
  9407. @end deffn
  9408. @deffn Procedure bitwise-arithmetic-shift i j
  9409. Shifts @var{i} by @var{j}.
  9410. It is a ``left'' shift if @code{@var{j}>0}, and
  9411. a ``right'' shift if @code{@var{j}<0}.
  9412. The result is equal to @code{(floor (* @var{i} (expt 2 @var{j})))}.
  9413. Examples:
  9414. @example
  9415. (bitwise-arithmetic-shift -6 -1) @result{}-3
  9416. (bitwise-arithmetic-shift -5 -1) @result{} -3
  9417. (bitwise-arithmetic-shift -4 -1) @result{} -2
  9418. (bitwise-arithmetic-shift -3 -1) @result{} -2
  9419. (bitwise-arithmetic-shift -2 -1) @result{} -1
  9420. (bitwise-arithmetic-shift -1 -1) @result{} -1
  9421. @end example
  9422. @end deffn
  9423. @deffn Procedure bitwise-arithmetic-shift-left i amount
  9424. @deffnx Procedure bitwise-arithmetic-shift-right i amount
  9425. The @var{amount} must be non-negative
  9426. The @code{bitwise-arithmetic-shift-left} procedure returns the same
  9427. result as @code{bitwise-arithmetic-shift},
  9428. and @code{(bitwise-arithmetic-shift-right @var{i} @var{amount})} returns the
  9429. same result as @code{(bitwise-arithmetic-shift @var{i} (- @var{amount}))}.
  9430. If @var{i} is a primitive integer type,
  9431. then @var{amount} must be less than the number of bits in the
  9432. promoted type of @var{i} (32 or 64).
  9433. If the type is unsigned, an unsigned (logic) shift is
  9434. done for @code{bitwise-arithmetic-shift-right},
  9435. rather than a signed (arithmetic) shift.
  9436. @end deffn
  9437. @deffn Procedure bitwise-rotate-bit-field n start end count
  9438. Returns the result of cyclically permuting in @var{n} the bits at positions
  9439. from @var{start} (inclusive) to @var{end} (exclusive) by
  9440. @var{count} bits towards the more significant bits,
  9441. @var{start} and @var{end} must be non-negative,
  9442. and @var{start} must be less than or equal to @var{end}.
  9443. This is the result of the following computation:
  9444. @example
  9445. (let* ((n ei1)
  9446. (width (- end start)))
  9447. (if (positive? width)
  9448. (let* ((count (mod count width))
  9449. (field0
  9450. (bitwise-bit-field n start end))
  9451. (field1 (bitwise-arithmetic-shift-left
  9452. field0 count))
  9453. (field2 (bitwise-arithmetic-shift-right
  9454. field0
  9455. (- width count)))
  9456. (field (bitwise-ior field1 field2)))
  9457. (bitwise-copy-bit-field n start end field))
  9458. n))
  9459. @end example
  9460. @end deffn
  9461. @deffn Procedure bitwise-reverse-bit-field i start end
  9462. Returns the result obtained from @var{i} by reversing the order of the bits at positions from @var{start} (inclusive) to @var{end} (exclusive),
  9463. where @var{start} and @var{end} must be non-negative,
  9464. and @var{start} must be less than or equal to @var{end}.
  9465. @example
  9466. (bitwise-reverse-bit-field #b1010010 1 4) @result{} 88 ; #b1011000
  9467. @end example
  9468. @end deffn
  9469. @deffn Procedure logop op x y
  9470. Perform one of the 16 bitwise operations of @var{x} and @var{y},
  9471. depending on @var{op}.
  9472. @end deffn
  9473. @deffn Procedure logtest i j
  9474. Returns true if the arguments have any bits in common.
  9475. Same as @code{(not (zero? (bitwise-and @var{i} @var{j})))},
  9476. but is more efficient.
  9477. @end deffn
  9478. @subsection SRFI-60 Logical Number Operations
  9479. Kawa supports SRFI-60 ``Integers as Bits'' as well, although we
  9480. generally recommend using the R6RS-compatible functions instead when
  9481. possible. Unless noted as being a builtin function, to use these you
  9482. must first @code{(require 'srfi-60)} or @code{(import (srfi :60))}
  9483. (or @code{(import (srfi :60 integer-bits))}).
  9484. @deffn Procedure logand i ...
  9485. Equivalent to @code{(bitwise-and @var{i} ...)}. Builtin.
  9486. @end deffn
  9487. @deffn Procedure logior i ...
  9488. Equivalent to @code{(bitwise-ior @var{i} ...)}. Builtin.
  9489. @end deffn
  9490. @deffn Procedure logxor i ...
  9491. Equivalent to @code{(bitwise-xor @var{i} ...)}. Builtin.
  9492. @end deffn
  9493. @deffn Procedure lognot i
  9494. Equivalent to @code{(bitwise-not @var{i})}. Builtin.
  9495. @end deffn
  9496. @deffn Procedure bitwise-merge mask i j
  9497. Equivalent to @code{(bitwise-if @var{mask} @var{i} @var{j})}.
  9498. @end deffn
  9499. @deffn Procedure any-bits-set? i j
  9500. Equivalent to @code{(logtest @var{i} @var{j})}.
  9501. @end deffn
  9502. @deffn Procedure logcount i
  9503. @deffnx Procedure bit-count i
  9504. Count the number of 1-bits in @var{i}, if it is non-negative.
  9505. If @var{i} is negative, count number of 0-bits.
  9506. Same as @code{(bitwise-bit-count @var{i})} if @var{i} is non-negative.
  9507. Builtin as @func{logcount}.
  9508. @end deffn
  9509. @deffn Procedure integer-length i
  9510. Equivalent to @code{(bitwise-length @var{i})}. Builtin.
  9511. @end deffn
  9512. @deffn Procedure log2-binary-factors i
  9513. @deffnx Procedure first-set-bit i
  9514. Equivalent to @code{(bitwise-first-bit-set @var{i})}.
  9515. @end deffn
  9516. @deffn Procedure logbit? pos i
  9517. @deffnx Procedure bit-set? pos i
  9518. Equivalent to @code{(bitwise-bit-set? @var{i} @var{pos})}.
  9519. @end deffn
  9520. @deffn Procedure copy-bit bitno i bool
  9521. Equivalent to @code{(bitwise-copy-bit @var{i} @var{bitno} (if @var{bool} 1 0))}.
  9522. @end deffn
  9523. @deffn Procedure bit-field n start end
  9524. Equivalent to @code{(bitwise-bit-field @var{n} @var{start} @var{end})}.
  9525. @end deffn
  9526. @deffn Procedure copy-bit-field to from start end
  9527. Equivalent to @code{(bitwise-copy-bit-field @var{to} @var{start} @var{end} @var{from})}.
  9528. @end deffn
  9529. @deffn Procedure arithmetic-shift i j
  9530. Equivalent to @code{(bitwise-arithmetic-shift @var{i} @var{j})}. Builtin.
  9531. @end deffn
  9532. @deffn Procedure ash i j
  9533. Alias for @code{arithmetic-shift}. Builtin.
  9534. @end deffn
  9535. @deffn Procedure rotate-bit-field n count start end
  9536. Equivalent to @code{(bitwise-rotate-bit-field @var{n} @var{start} @var{end} @var{count})}.
  9537. @end deffn
  9538. @deffn Procedure reverse-bit-field i start end
  9539. Equivalent to @code{(bitwise-reverse-bit-field @var{i} @var{start} @var{end})}.
  9540. @end deffn
  9541. @deffn Procedure integer->list @var{k} [@var{length}]
  9542. @deffnx Procedure list->integer @var{list}
  9543. The @func{integer->list} procedure returns a list of @var{length}
  9544. booleans corresponding to the bits of the non-negative integer @var{k},
  9545. with @code{#t} for @code{1} and @code{#f} for @code{0}. @var{length}
  9546. defaults to @code{(bitwise-length @var{k})}. The list will be in order
  9547. from MSB to LSB, with the value of @code{(odd? @var{k})} in the last
  9548. car.
  9549. The @func{list->integer} procedure returns the integer corresponding to
  9550. the booleans in the list @var{list}.
  9551. The @func{integer->list} and @func{list->integer} procedures are
  9552. inverses so far as @func{equal?} is concerned.
  9553. @end deffn
  9554. @deffn Procedure booleans->integer bool1 ...
  9555. Returns the integer coded by the @var{bool1} ... arguments.
  9556. Equivalent to @code{(list->integer (list @var{bool1} ...))}.
  9557. @end deffn
  9558. @subsection Deprecated Logical Number Operations
  9559. This older function is still available, but we
  9560. recommend using the R6RS-compatible function.
  9561. @deffn Procedure bit-extract n start end
  9562. Equivalent to @code{(bitwise-bit-field @var{n} @var{start} @var{end})}.
  9563. @end deffn
  9564. @node Performance of numeric operations
  9565. @section Performance of numeric operations
  9566. Kawa can generally do a pretty good job of generating
  9567. efficient code for numeric operations, at least when
  9568. it knows or can figure out the types of the operands.
  9569. The basic operations @code{+}, @code{-}, and @code{*}
  9570. are compiled to single-instruction bytecode if both
  9571. operands are @code{int} or @code{long}.
  9572. Likewise, if both operands are floating-point (or
  9573. one is floating-point and the other is rational),
  9574. then single-instruction @code{double} or @code{float}
  9575. instructions are emitted.
  9576. A binary operation involving an infinite-precision @code{integer}
  9577. and a fixed-size @code{int} or @code{long} is normally
  9578. evaluated by expanding the latter to @code{integer}
  9579. and using @code{integer} arithmetic. An exception is
  9580. an integer literal whose
  9581. value fits in an @code{int} or @code{long} - in that case
  9582. the operation is done using @code{int} or @code{long}
  9583. arithmetic.
  9584. In general, integer literals have amorphous type.
  9585. When used to infer the type of a variable, they have @code{integer} type:
  9586. @example
  9587. (let ((v1 0))
  9588. ... v1 has type integer ... )
  9589. @end example
  9590. However, a literal whose value fits in the @code{int} or @code{long} range
  9591. is implicitly viewed @code{int} or @code{long} in certain contexts,
  9592. primarily method overload resolution and binary arithmetic
  9593. (as mentioned above).
  9594. The comparison functions @code{<}, @code{<=}, @code{=},
  9595. @code{>}, and @code{=>} are also optimized to single instriction
  9596. operations if the operands have appropriate type.
  9597. However, the functions @code{zero?}, @code{positive?}, and @code{negative?}
  9598. have not yet been optimized.
  9599. Instead of @code{(positive? x)} write @code{(> x 0)}.
  9600. There are a number of integer division and modulo operations.
  9601. If the operands are @code{int} or @code{long}, it is faster
  9602. to use @code{quotient} and @code{remainder} rather
  9603. than @code{div} and @code{mod} (or @code{modulo}).
  9604. If you know the first operand is non-negative and the second is positive,
  9605. then use @code{quotient} and @code{remainder}.
  9606. (If an operand is an arbitrary-precision @code{integer},
  9607. then it dosn't really matter.)
  9608. The logical operations @code{bitwise-and}, @code{bitwise-ior},
  9609. @code{bitwise-xor}, @code{bitwise-not}, @code{bitwise-arithmetic-shift-left},
  9610. @code{bitwise-arithmetic-shift-right} are compiled
  9611. to single bitcode instructions if the operands are @code{int} or @code{long}.
  9612. Avoid @code{bitwise-arithmetic-shift} if the sign of the shift is known.
  9613. If the operands are arbitrary-precision @code{integer},
  9614. a library call is needed, but run-time type dispatch is avoided.
  9615. @node Characters and text, Data structures, Numbers, Top
  9616. @chapter Characters and text
  9617. @menu
  9618. * Characters::
  9619. * Character sets::
  9620. * Strings::
  9621. * String literals::
  9622. * Unicode:: Unicode character classes and conversions
  9623. * Regular expressions::
  9624. @end menu
  9625. @node Characters
  9626. @section Characters
  9627. Characters are objects that represent human-readable characters
  9628. such as letters and digits. More precisely, a character
  9629. represents a @uref{http://www.unicode.org/glossary/#unicode_scalar_value,
  9630. Unicode scalar value}. Each character has an integer value
  9631. in the range @code{0} to @code{#x10FFFF}
  9632. (excluding the range @code{#xD800} to @code{#xDFFF}
  9633. used for @uref{http://www.unicode.org/glossary/#surrogate_code_point, Surrogate Code Points}).
  9634. @quotation
  9635. @emph{Note:}
  9636. Unicode distinguishes
  9637. between glyphs, which are printed for humans to read, and characters,
  9638. which are abstract entities that map to glyphs (sometimes in a way
  9639. that’s sensitive to surrounding characters). Furthermore, different
  9640. sequences of scalar values sometimes correspond to the same
  9641. character. The relationships among scalar, characters, and glyphs are
  9642. subtle and complex.
  9643. Despite this complexity, most things that a literate human would call
  9644. a ``character'' can be represented by a single Unicode scalar value
  9645. (although several sequences of Unicode scalar values may represent
  9646. that same character). For example, Roman letters, Cyrillic letters,
  9647. Hebrew consonants, and most Chinese characters fall into this
  9648. category.
  9649. Unicode scalar values exclude the range @code{#xD800} to @code{#xDFFF},
  9650. which are part of the range of Unicode @dfn{code points}.
  9651. However, the Unicode code points in this range, the so-called
  9652. @dfn{surrogates}, are an artifact of the UTF-16 encoding, and can only
  9653. appear in specific Unicode encodings, and even then only in pairs that
  9654. encode scalar values. Consequently, all characters represent code
  9655. points, but the surrogate code points do not have representations as
  9656. characters.
  9657. @end quotation
  9658. @deffn Type character
  9659. A Unicode code point - normally a Unicode scalar value,
  9660. but could be a surrogate.
  9661. This is implemented using a 32-bit @code{int}.
  9662. When an object is needed (i.e. the @dfn{boxed} representation),
  9663. it is implemented an instance of @code{gnu.text.Char}.
  9664. @end deffn
  9665. @deffn Type character-or-eof
  9666. A @code{character} or the specical @code{#!eof} value (used to indicate
  9667. end-of-file when reading from a port).
  9668. This is implemented using a 32-bit @code{int},
  9669. where the value -1 indicates end-of-file.
  9670. When an object is needed, it is implemented an instance of
  9671. @code{gnu.text.Char} or the special @code{#!eof} object.
  9672. @end deffn
  9673. @deffn Type char
  9674. A UTF-16 code unit. Same as Java primitive @code{char} type.
  9675. Considered to be a sub-type of @code{character}.
  9676. When an object is needed, it is implemented as an instance
  9677. of @code{java.lang.Character}. Note the unfortunate inconsistency
  9678. (for historical reasons) of @code{char} boxed as @code{Character}
  9679. vs @code{character} boxed as @code{Char}.
  9680. @end deffn
  9681. Characters are written using the notation
  9682. @code{#\}@var{character} (which stands for the given @var{character};
  9683. @code{#\x}@var{hex-scalar-value} (the character whose scalar value
  9684. is the given hex integer);
  9685. or @code{#\}@var{character-name} (a character with a given name):
  9686. @c can't use @stxlit because of slash
  9687. @display
  9688. @stxdef{character} @code{@b{#\}}@var{any-character}
  9689. | @code{@b{#\}} @meta{character-name}
  9690. | @code{@b{#\x}} @stxref{hex-scalar-value}
  9691. | @code{@b{#\X}} @stxref{hex-scalar-value}
  9692. @end display
  9693. The following @meta{character-name} forms are recognized:
  9694. @table @code
  9695. @item @b{#\alarm}
  9696. @code{#\x0007} - the alarm (bell) character
  9697. @item @b{#\backspace}
  9698. @code{#\x0008}
  9699. @item @b{#\delete}
  9700. @item @b{#\del}
  9701. @item @b{#\rubout}
  9702. @code{#\x007f} - the delete or rubout character
  9703. @item @b{#\escape}
  9704. @item @b{#\esc}
  9705. @code{#\x001b}
  9706. @item @b{#\newline}
  9707. @itemx @b{#\linefeed}
  9708. @code{#\x001a} - the linefeed character
  9709. @item @b{#\null}
  9710. @itemx @b{#\nul}
  9711. @code{#\x0000} - the null character
  9712. @item @b{#\page}
  9713. @code{#\000c} - the formfeed character
  9714. @item @b{#\return}
  9715. @code{#\000d} - the carriage return character
  9716. @item @b{#\space}
  9717. @code{#\x0020} - the preferred way to write a space
  9718. @item @b{#\tab}
  9719. @code{#\x0009} - the tab character
  9720. @item @b{#\vtab}
  9721. @code{#\x000b} - the vertical tabulation character
  9722. @item @b{#\ignorable-char}
  9723. A special @code{character} value, but it is not a Unicode code point.
  9724. It is a special value returned when an index refers to the second
  9725. @code{char} (code point) of a surrogate pair, and which should be ignored.
  9726. (When writing a @code{character} to a string or file,
  9727. it will be written as one or two @code{char} values.
  9728. The exception is @code{#\ignorable-char}, for which zero
  9729. @code{char} values are written.)
  9730. @end table
  9731. @deffn Procedure {char?} @var{obj}
  9732. Return @true{} if @var{obj} is a character, @false{} otherwise.
  9733. (The @var{obj} can be any character, not just a 16-bit @code{char}.)
  9734. @end deffn
  9735. @deffn Procedure {char->integer} @var{char}
  9736. @deffnx Procedure {integer->char} @var{sv}
  9737. @var{sv} should be a Unicode scalar value, i.e., a non--negative exact
  9738. integer object in @code{[0, #xD7FF] union [#xE000, #x10FFFF]}.
  9739. (Kawa also allows values in the surrogate range.)
  9740. Given a character, @func{char->integer} returns its Unicode scalar value
  9741. as an exact integer object. For a Unicode scalar value @var{sv},
  9742. @func{integer->char} returns its associated character.
  9743. @example
  9744. (integer->char 32) @result{} #\space
  9745. (char->integer (integer->char 5000)) @result{} 5000
  9746. (integer->char #\xD800) @result{} throws ClassCastException
  9747. @end example
  9748. @PerformanceNote{} A call to @code{char->integer} is compiled as
  9749. casting the argument to a @code{character}, and then re-interpreting
  9750. that value as an @code{int}.
  9751. A call to @code{integer->char} is compiled as
  9752. casting the argument to an @code{int}, and then re-interpreting
  9753. that value as an @code{character}.
  9754. If the argument is the right type, no code is emitted: the value is
  9755. just re-interpreted as the result type.
  9756. @end deffn
  9757. @deffn Procedure {char=?} @vari{char} @varii{char} @variii{char} @dots{}
  9758. @deffnx Procedure {char<?} @vari{char} @varii{char} @variii{char} @dots{}
  9759. @deffnx Procedure {char>?} @vari{char} @varii{char} @variii{char} @dots{}
  9760. @deffnx Procedure {char<=?} @vari{char} @varii{char} @variii{char} @dots{}
  9761. @deffnx Procedure {char>=?} @vari{char} @varii{char} @variii{char} @dots{}
  9762. These procedures impose a total ordering on the set of characters
  9763. according to their Unicode scalar values.
  9764. @example
  9765. (char<? #\z #\ß) @result{} #t
  9766. (char<? #\z #\Z) @result{} #f
  9767. @end example
  9768. @PerformanceNote{} This is compiled as if converting each
  9769. argument using @code{char->integer} (which requires no code)
  9770. and the using the corresponing @code{int} comparison.
  9771. @end deffn
  9772. @deffn Procedure digit-value char
  9773. This procedure returns the numeric value (0 to 9) of its
  9774. argument if it is a numeric digit (that is, if @code{char-numeric?}
  9775. returns @code{#t}), or @code{#f} on any other character.
  9776. @example
  9777. (digit-value #\3) @result{} 3
  9778. (digit-value #\x0664) @result{} 4
  9779. (digit-value #\x0AE6) @result{} 0
  9780. (digit-value #\x0EA6) @result{} #f
  9781. @end example
  9782. @end deffn
  9783. @node Character sets
  9784. @section Character sets
  9785. Sets of characters are useful for text-processing code,
  9786. including parsing, lexing, and pattern-matching.
  9787. @uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14} specifies
  9788. a @code{char-set} type for such uses. Some examples:
  9789. @example
  9790. (import (srfi :14 char-sets))
  9791. (define vowel (char-set #\a #\e #\i #\o #\u))
  9792. (define vowely (char-set-adjoin vowel #\y))
  9793. (char-set-contains? vowel #\y) @result{} #f
  9794. (char-set-contains? vowely #\y) @result{} #t
  9795. @end example
  9796. See the @uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14 specification} for details.
  9797. @deffn Type char-set
  9798. The type of character sets.
  9799. In Kawa @code{char-set} is a type that can be used in type specifiers:
  9800. @example
  9801. (define vowely ::char-set (char-set-adjoin vowel #\y))
  9802. @end example
  9803. @end deffn
  9804. Kawa uses @uref{https://en.wikipedia.org/wiki/Inversion_list,inversion lists} for an efficient implementation, using Java @code{int} arrays
  9805. to represents character ranges (inversions).
  9806. The @code{char-set-contains?} function uses binary search,
  9807. so it takes time proportional to the logarithm of the number of inversions.
  9808. Other operations may take time proportional to the number of inversions.
  9809. @node Strings
  9810. @section Strings
  9811. Strings are sequences of characters. The @emph{length} of a string is
  9812. the number of characters that it contains, as an exact non-negative integer.
  9813. The @emph{valid indices} of a string are the
  9814. exact non-negative integers less than the length of the string.
  9815. The first character of a
  9816. string has index 0, the second has index 1, and so on.
  9817. Strings are @emph{implemented} as a sequence of 16-bit @code{char} values,
  9818. even though they're semantically a sequence of 32-bit Unicode code points.
  9819. A character whose value is greater than @code{#xffff}
  9820. is represented using two surrogate characters.
  9821. The implementation allows for natural interoperability with Java APIs.
  9822. However it does make certain operations (indexing or counting based on
  9823. character counts) difficult to implement efficiently. Luckily one
  9824. rarely needs to index or count based on character counts;
  9825. alternatives are discussed below.
  9826. @cindex istring
  9827. @cindex mstring
  9828. There are different kinds of strings:
  9829. @itemize
  9830. @item
  9831. An @dfn{istring} is @emph{immutable}:
  9832. It is fixed, and cannot be modified.
  9833. On the other hand, indexing (e.g. @code{string-ref}) is efficient (constant-time),
  9834. while indexing of other string implementations takes time proportional
  9835. to the index.
  9836. String literals are istrings, as are the return values of
  9837. most of the procedures in this chapter.
  9838. An @dfn{istring} is an instance of the @code{gnu.lists.IString} class.
  9839. @item
  9840. An @dfn{mstring} is @emph{mutable}:
  9841. You can replace individual characters (using @code{string-set!}).
  9842. You can also change the @var{mstring}'s length by inserting
  9843. or removing characters (using @code{string-append!} or @code{string-replace!}).
  9844. An @dfn{mstring} is an instance of the @code{gnu.lists.FString} class.
  9845. @item
  9846. Any other object that implements the @code{java.lang.CharSequence} interface
  9847. is also a string.
  9848. This includes standard Java @code{java.lang.String}
  9849. and @code{java.lang.StringBuilder} objects.
  9850. @end itemize
  9851. Some of the procedures that operate on strings ignore the
  9852. difference between upper and lower case. The names of
  9853. the versions that ignore case end with “@code{-ci}” (for “case
  9854. insensitive”).
  9855. @CompatibilityNote{}
  9856. Many of the following procedures (for example @code{string-append})
  9857. return an immutable istring in Kawa,
  9858. but return a ``freshly allocated'' mutable string in
  9859. standard Scheme (include R7RS) as well as most Scheme implementations
  9860. (including previous versions of Kawa).
  9861. To get the ``compatibility mode'' versions of those procedures
  9862. (which return mstrings),
  9863. invoke Kawa with one the @code{--r5rs}, @code{--r6rs}, or @code{--r7rs}
  9864. options, or you can @code{import} a standard library like @code{(scheme base)}.
  9865. @deffn Type string
  9866. The type of string objects.
  9867. The underlying type is the interface @code{java.lang.CharSequence}.
  9868. Immultable strings are @code{gnu.lists.IString} or @code{java.lang.String},
  9869. while mutable strings are @code{gnu.lists.FString}.
  9870. @end deffn
  9871. @subsection Basic string procedures
  9872. @deffn Procedure {string?} @var{obj}
  9873. Return @true{} if @var{obj} is a string, @false{} otherwise.
  9874. @end deffn
  9875. @deffn Procedure {istring?} @var{obj}
  9876. Return @true{} if @var{obj} is a istring (a immutable, constant-time-indexable string); @false{} otherwise.
  9877. @end deffn
  9878. @deffn Constructor string @var{char} @dots{}
  9879. Return a string composed of the arguments.
  9880. This is analogous to @var{list}.
  9881. @CompatibilityNote{} The result is an istring,
  9882. except in compatibility mode, when it is a new allocated mstring.
  9883. @end deffn
  9884. @deffn Procedure string-length @var{string}
  9885. Return the number of characters in the given @var{string} as an exact
  9886. integer object.
  9887. @PerformanceNote{} If the @var{string} is not an istring,
  9888. the calling @code{string-length} may take time proportional
  9889. to the length of the @var{string},
  9890. because of the need to scan for surrogate pairs.
  9891. @end deffn
  9892. @deffn Procedure string-ref @var{string} @var{k}
  9893. @var{k} must be a valid index of @var{string}. The @func{string-ref}
  9894. procedure returns character @var{k} of @var{string} using zero--origin
  9895. indexing.
  9896. @PerformanceNote{} If the @var{string} is not an istring,
  9897. then calling @code{string-ref} may take time proportional
  9898. to @var{k} because of the need to check for surrogate pairs.
  9899. An alternative is to use @code{string-cursor-ref}.
  9900. If iterating through a string, use @code{string-for-each}.
  9901. @end deffn
  9902. @deffn Procedure string-null? @var{string}
  9903. Is @var{string} the empty string?
  9904. Same result as @code{(= (string-length @var{string}) 0)} but
  9905. executes in O(1) time.
  9906. @end deffn
  9907. @deffn Procedure string-every pred string [start end])
  9908. @deffnx Procedure string-any pred string [start end])
  9909. Checks to see if every/any character in @var{string} satisfies @var{pred},
  9910. proceeding from left (index @var{start}) to right (index @var{end}). These
  9911. procedures are short-circuiting: if @var{pred} returns false,
  9912. @code{string-every} does not call @var{pred} on subsequent characters;
  9913. if @var{pred} returns true, @code{string-any} does not call @var{pred}
  9914. on subsequent characters. Both procedures are ``witness-generating'':
  9915. @itemize
  9916. @item
  9917. If @code{string-every} is given an empty interval (with @var{start} = @var{end}),
  9918. it returns @code{#t}.
  9919. @item
  9920. If @code{string-every} returns true for a non-empty interval
  9921. (with @var{start} < @var{end}), the returned true value is the one returned by the final call to the predicate on
  9922. @code{(string-ref @var{string} (- @var{end} 1))}.
  9923. @item
  9924. If @code{string-any} returns true, the returned true value is the one
  9925. returned by the predicate.
  9926. @end itemize
  9927. @emph{Note:} The names of these procedures do not end with a question
  9928. mark. This indicates a general value is returned instead of a simple
  9929. boolean (@code{#t} or @code{#f}).
  9930. @end deffn
  9931. @subsection Immutable String Constructors
  9932. @deffn Procedure string-tabulate proc len
  9933. Constructs a string of size @var{len} by calling @var{proc} on
  9934. each value from 0 (inclusive) to @var{len} (exclusive) to produce
  9935. the corresponding element of the string.
  9936. The procedure @var{proc} accepts an exact integer as its argument and returns a character.
  9937. The order in which @var{proc} is called on those indexes is not specifified.
  9938. @emph{Rationale:} Although @code{string-unfold} is more general,
  9939. @code{string-tabulate} is likely to run faster for the common special
  9940. case it implements.
  9941. @end deffn
  9942. @deffn Procedure string-unfold stop? mapper successor seed [base make-final]
  9943. @deffnx Procedure string-unfold-right stop? mapper successor seed [base make-final]
  9944. This is a fundamental and powerful constructor for strings.
  9945. @itemize
  9946. @item
  9947. @var{successor} is used to generate a series of ``seed'' values from the initial seed:
  9948. @var{seed}, @code{(}@var{successor} @var{seed}@code{)}, @code{(}@var{successor}@sup{2} @var{seed}@code{)}, @code{(}@var{successor}@sup{3} @var{seed}@code{)}, ...
  9949. @item
  9950. @var{stop?} tells us when to stop — when it returns true when applied to one of these seed values.
  9951. @item
  9952. @var{mapper} maps each seed value to the corresponding character(s) in the result string, which are assembled into that string in left-to-right order. It is an error for @var{mapper} to return anything other than a character or string.
  9953. @item
  9954. @var{base} is the optional initial/leftmost portion of the constructed string, which defaults to the empty string @code{""}.
  9955. It is an error if @var{base} is anything other than a character or string.
  9956. @item
  9957. @var{make-final} is applied to the terminal seed value (on which @var{stop?} returns true) to produce the final/rightmost portion of the constructed string. It defaults to @code{(lambda (x) "")}.
  9958. It is an error for @var{make-final} to return anything other than
  9959. a character or string.
  9960. @end itemize
  9961. @code{string-unfold-right} is the same as @code{string-unfold} except the
  9962. results of @var{mapper} are assembled into the string in right-to-left order,
  9963. @var{base} is the optional rightmost portion of the constructed string, and
  9964. @var{make-final} produces the leftmost portion of the constructed string.
  9965. You can use it @code{string-unfold} to convert a list to a string,
  9966. read a port into a string, reverse a string, copy a string, and so forth.
  9967. Examples:
  9968. @example
  9969. (define (port->string p)
  9970. (string-unfold eof-object? values
  9971. (lambda (x) (read-char p))
  9972. (read-char p)))
  9973. (define (list->string lis)
  9974. (string-unfold null? car cdr lis))
  9975. (define (string-tabulate f size)
  9976. (string-unfold (lambda (i) (= i size)) f add1 0))
  9977. @end example
  9978. To map @var{f} over a list @var{lis}, producing a string:
  9979. @example
  9980. (string-unfold null? (compose @var{f} car) cdr @var{lis})
  9981. @end example
  9982. Interested functional programmers may enjoy noting that @code{string-fold-right}
  9983. and @code{string-unfold} are in some sense inverses.
  9984. That is, given operations @var{knull?}, @var{kar}, @var{kdr},
  9985. @var{kons}, and @var{knil} satisfying
  9986. @example
  9987. (@var{kons} (@var{kar} x) (@var{kdr} x)) = x and (@var{knull?} @var{knil}) = #t
  9988. @end example
  9989. then
  9990. @example
  9991. (string-fold-right @var{kons} @var{knil} (string-unfold @var{knull?} @var{kar} @var{kdr} @var{x})) = @var{x}
  9992. @end example
  9993. and
  9994. @example
  9995. (string-unfold @var{knull?} @var{kar} @var{kdr} (string-fold-right @var{kons} @var{knil} @var{string})) = @var{string}.
  9996. @end example
  9997. This combinator pattern is sometimes called an ``anamorphism.''
  9998. @end deffn
  9999. @subsection Selection
  10000. @deffn Procedure substring @var{string} @var{start} @var{end}
  10001. @var{string} must be a string, and @var{start} and @var{end} must be
  10002. exact integer objects satisfying:
  10003. @example
  10004. 0 <= @var{start} <= @var{end} <= (string-length @var{string})
  10005. @end example
  10006. The @func{substring} procedure returns a newly allocated string formed
  10007. from the characters of @var{string} beginning with index @var{start}
  10008. (inclusive) and ending with index @var{end} (exclusive).
  10009. @end deffn
  10010. @deffn Procedure string-take string nchars
  10011. @deffnx Procedure string-drop string nchars
  10012. @deffnx Procedure string-take-right string nchars
  10013. @deffnx Procedure string-drop-right string nchars
  10014. @code{string-take} returns an immutable string containing the
  10015. first @var{nchars} of @var{string};
  10016. @code{string-drop} returns a string containing all but the first @var{nchars}
  10017. of @var{string}.
  10018. @code{string-take-right} returns a string containing the last @var{nchars}
  10019. of @var{string}; @code{string-drop-right} returns a string containing all
  10020. but the last @var{nchars} of @var{string}.
  10021. @example
  10022. (string-take "Pete Szilagyi" 6) @result{} "Pete S"
  10023. (string-drop "Pete Szilagyi" 6) @result{} "zilagyi"
  10024. (string-take-right "Beta rules" 5) @result{} "rules"
  10025. (string-drop-right "Beta rules" 5) @result{} "Beta "
  10026. @end example
  10027. It is an error to take or drop more characters than are in the string:
  10028. @example
  10029. (string-take "foo" 37) @result{} @i{error}
  10030. @end example
  10031. @end deffn
  10032. @deffn Procedure string-pad string len [char start end]
  10033. @deffnx Procedure string-pad-right string len [char start end]
  10034. Returns an istring of length @var{len} comprised of the characters
  10035. drawn from the given subrange of @var{string},
  10036. padded on the left (right) by as many occurrences of the
  10037. character @var{char} as needed.
  10038. If @var{string} has more than @var{len} chars, it is truncated on the
  10039. left (right) to length @var{len}.
  10040. The @var{char} defaults to @code{#\space}
  10041. @example.
  10042. (string-pad "325" 5) @result{} " 325"
  10043. (string-pad "71325" 5) @result{} "71325"
  10044. (string-pad "8871325" 5) @result{} "71325"
  10045. @end example
  10046. @end deffn
  10047. @deffn Procedure string-trim string [pred start end]
  10048. @deffnx Procedure string-trim-right string [pred start end]
  10049. @deffnx Procedure string-trim-both string [pred start end]
  10050. Returns an istring obtained from the given subrange of @var{string}
  10051. by skipping over all characters on the left / on the right / on both sides that satisfy the second argument @var{pred}:
  10052. @var{pred} defaults to @code{char-whitespace?}.
  10053. @example
  10054. (string-trim-both " The outlook wasn't brilliant, \n\r")
  10055. @result{} "The outlook wasn't brilliant,"
  10056. @end example
  10057. @end deffn
  10058. @subsection String Comparisons
  10059. @deffn Procedure {string=?} @vari{string} @varii{string} @variii{string} @dots{}
  10060. Return @true{} if the strings are the same length and contain the same
  10061. characters in the same positions. Otherwise, the @func{string=?}
  10062. procedure returns @false{}.
  10063. @example
  10064. (string=? "Straße" "Strasse") @result{} #f
  10065. @end example
  10066. @end deffn
  10067. @deffn Procedure {string<?} @vari{string} @varii{string} @variii{string} @dots{}
  10068. @deffnx Procedure {string>?} @vari{string} @varii{string} @variii{string} @dots{}
  10069. @deffnx Procedure {string<=?} @vari{string} @varii{string} @variii{string} @dots{}
  10070. @deffnx Procedure {string>=?} @vari{string} @varii{string} @variii{string} @dots{}
  10071. These procedures return @code{#t} if their arguments are (respectively):
  10072. monotonically increasing, monotonically decreasing,
  10073. monotonically non-decreasing, or monotonically nonincreasing.
  10074. These predicates are required to be transitive.
  10075. These procedures are the lexicographic extensions to strings of the
  10076. corresponding orderings on characters. For example, @func{string<?} is
  10077. the lexicographic ordering on strings induced by the ordering
  10078. @func{char<?} on characters. If two strings differ in length but are
  10079. the same up to the length of the shorter string, the shorter string is
  10080. considered to be lexicographically less than the longer string.
  10081. @example
  10082. (string<? "z" "ß") @result{} #t
  10083. (string<? "z" "zz") @result{} #t
  10084. (string<? "z" "Z") @result{} #f
  10085. @end example
  10086. @end deffn
  10087. @deffn Procedure string-ci=? @vari{string} @varii{string} @variii{string} @dots{}
  10088. @deffnx Procedure string-ci<? @vari{string} @varii{string} @variii{string} @dots{}
  10089. @deffnx Procedure string-ci>? @vari{string} @varii{string} @variii{string} @dots{}
  10090. @deffnx Procedure string-ci<=? @vari{string} @varii{string} @variii{string} @dots{}
  10091. @deffnx Procedure string-ci>=? @vari{string} @varii{string} @variii{string} @dots{}
  10092. These procedures are similar to @func{string=?}, etc.,
  10093. but behave as if they applied @code{string-foldcase} to their arguments
  10094. before invoking the corresponding procedures without @code{-ci}.
  10095. @example
  10096. (string-ci<? "z" "Z") @result{} #f
  10097. (string-ci=? "z" "Z") @result{} #t
  10098. (string-ci=? "Straße" "Strasse") @result{} #t
  10099. (string-ci=? "Straße" "STRASSE") @result{} #t
  10100. (string-ci=? "ΧΑΟΣ" "χαοσ") @result{} #t
  10101. @end example
  10102. @end deffn
  10103. @subsection Conversions
  10104. @deffn Procedure list->string @var{list}
  10105. The @func{list->string} procedure returns an istring
  10106. formed from the characters in @var{list}, in order.
  10107. It is an error if any element of @var{list} is not a character.
  10108. @CompatibilityNote{} The result is an istring,
  10109. except in compatibility mode, when it is an mstring.
  10110. @end deffn
  10111. @deffn Procedure reverse-list->string @var{list}
  10112. An efficient implementation of @code{(compose list->text reverse)}:
  10113. @example
  10114. (reverse-list->text '(#\a #\B #\c)) @result{} "cBa"
  10115. @end example
  10116. This is a common idiom in the epilogue of string-processing loops
  10117. that accumulate their result using a list in reverse order.
  10118. (See also @code{string-concatenate-reverse} for the ``chunked'' variant.)
  10119. @end deffn
  10120. @deffn Procedure string->list @var{string} [@var{start} [@var{end}]]
  10121. The @func{string->list} procedure returns a newly allocated list of the
  10122. characters of @var{string} between @var{start} and @var{end}, in order.
  10123. The @func{string->list} and @func{list->string} procedures are inverses
  10124. so far as @func{equal?} is concerned.
  10125. @end deffn
  10126. @deffn Procedure vector->string vector [start [end]]
  10127. The @code{vector->string} procedure returns a newly allocated
  10128. string of the objects contained in the elements of @var{vector}
  10129. between @var{start} and @var{end}.
  10130. It is an error if any element of @var{vector} between @var{start}
  10131. and @var{end} is not a character, or is a character forbidden in strings.
  10132. @example
  10133. (vector->string #(#\1 #\2 #\3)) @result{} "123"
  10134. (vector->string #(#\1 #\2 #\3 #\4 #\5) 2 4) @result{} "34"
  10135. @end example
  10136. @end deffn
  10137. @deffn Procedure string->vector string [start [end]]
  10138. The @code{string->vector} procedure
  10139. returns a newly created vector initialized to the elements
  10140. of the string @var{string} between @var{start} and @var{end}.
  10141. @example
  10142. (string->vector "ABC") @result{} #(#\A #\B #\C)
  10143. (string->vector "ABCDE" 1 3) @result{} #(#\B #\C)
  10144. @end example
  10145. @end deffn
  10146. @deffn Procedure string-upcase @var{string}
  10147. @deffnx Procedure string-downcase @var{string}
  10148. @deffnx Procedure string-titlecase @var{string}
  10149. @deffnx Procedure string-foldcase @var{string}
  10150. These procedures take a string argument and return a string result.
  10151. They are defined in terms of Unicode's locale--independent case mappings
  10152. from Unicode scalar--value sequences to scalar--value sequences. In
  10153. particular, the length of the result string can be different from the
  10154. length of the input string. When the specified result is equal in the
  10155. sense of @func{string=?} to the argument, these procedures may return
  10156. the argument instead of a newly allocated string.
  10157. The @func{string-upcase} procedure converts a string to upper case;
  10158. @func{string-downcase} converts a string to lower case. The
  10159. @func{string-foldcase} procedure converts the string to its case--folded
  10160. counterpart, using the full case--folding mapping, but without the
  10161. special mappings for Turkic languages. The @func{string-titlecase}
  10162. procedure converts the first cased character of each word, and downcases
  10163. all other cased characters.
  10164. @example
  10165. (string-upcase "Hi") @result{} "HI"
  10166. (string-downcase "Hi") @result{} "hi"
  10167. (string-foldcase "Hi") @result{} "hi"
  10168. (string-upcase "Straße") @result{} "STRASSE"
  10169. (string-downcase "Straße") @result{} "straße"
  10170. (string-foldcase "Straße") @result{} "strasse"
  10171. (string-downcase "STRASSE") @result{} "strasse"
  10172. (string-downcase "Σ") @result{} "σ"
  10173. ; Chi Alpha Omicron Sigma:
  10174. (string-upcase "ΧΑΟΣ") @result{} "ΧΑΟΣ"
  10175. (string-downcase "ΧΑΟΣ") @result{} "χαος"
  10176. (string-downcase "ΧΑΟΣΣ") @result{} "χαοσς"
  10177. (string-downcase "ΧΑΟΣ Σ") @result{} "χαος σ"
  10178. (string-foldcase "ΧΑΟΣΣ") @result{} "χαοσσ"
  10179. (string-upcase "χαος") @result{} "ΧΑΟΣ"
  10180. (string-upcase "χαοσ") @result{} "ΧΑΟΣ"
  10181. (string-titlecase "kNock KNoCK") @result{} "Knock Knock"
  10182. (string-titlecase "who's there?") @result{} "Who's There?"
  10183. (string-titlecase "r6rs") @result{} "R6rs"
  10184. (string-titlecase "R6RS") @result{} "R6rs"
  10185. @end example
  10186. Since these procedures are locale--independent, they may not be
  10187. appropriate for some locales.
  10188. @emph{Kawa Note:} The implementation of @func{string-titlecase}
  10189. does not correctly handle the case where an initial character
  10190. needs to be converted to multiple characters, such as
  10191. ``LATIN SMALL LIGATURE FL'' which should be converted to
  10192. the two letters @code{"Fl"}.
  10193. @CompatibilityNote{} The result is an istring,
  10194. except in compatibility mode, when it is an mstring.
  10195. @end deffn
  10196. @deffn Procedure string-normalize-nfd @var{string}
  10197. @deffnx Procedure string-normalize-nfkd @var{string}
  10198. @deffnx Procedure string-normalize-nfc @var{string}
  10199. @deffnx Procedure string-normalize-nfkc @var{string}
  10200. These procedures take a string argument and return a string result,
  10201. which is the input string normalized to Unicode normalization form D,
  10202. KD, C, or KC, respectively. When the specified result is equal in the
  10203. sense of @func{string=?} to the argument, these procedures may return
  10204. the argument instead of a newly allocated string.
  10205. @example
  10206. (string-normalize-nfd "\xE9;") @result{} "\x65;\x301;"
  10207. (string-normalize-nfc "\xE9;") @result{} "\xE9;"
  10208. (string-normalize-nfd "\x65;\x301;") @result{} "\x65;\x301;"
  10209. (string-normalize-nfc "\x65;\x301;") @result{} "\xE9;"
  10210. @end example
  10211. @end deffn
  10212. @subsection Searching and matching
  10213. @deffn Procedure string-prefix-length string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10214. @deffnx Procedure string-suffix-length string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10215. Return the length of the longest common prefix/suffix of @var{string@sub{1}}
  10216. and @var{string@sub{2}}.
  10217. For prefixes, this is equivalent to their ``mismatch index''
  10218. (relative to the start indexes).
  10219. The optional @var{start}/@var{end} indexes restrict the comparison
  10220. to the indicated substrings of @var{string@sub{1}} and @var{string@sub{2}}.
  10221. @end deffn
  10222. @deffn Procedure string-prefix? string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10223. @deffnx Procedure string-suffix? string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10224. Is @var{string@sub{1}} a prefix/suffix of @var{string@sub{2}}?
  10225. The optional @var{start}/@var{end} indexes restrict the comparison
  10226. to the indicated substrings of @var{string@sub{1}} and @var{string@sub{2}}.
  10227. @end deffn
  10228. @deffn Procedure string-index string pred [start end]
  10229. @deffnx Procedure string-index-right string pred [start end]
  10230. @deffnx Procedure string-skip string pred [start end]
  10231. @deffnx Procedure string-skip-right string pred [start end]
  10232. @code{string-index} searches through the given substring from the
  10233. left, returning the index of the leftmost character satisfying the
  10234. predicate @var{pred}.
  10235. @code{string-index-right} searches from the right, returning
  10236. the index of the rightmost character satisfying the predicate @var{pred}.
  10237. If no match is found, these procedures return @code{#f}.
  10238. The @var{start} and @var{end} arguments specify the beginning and end
  10239. of the search; the valid indexes relevant to the search include @var{start}
  10240. but exclude @var{end}. Beware of ``fencepost''" errors: when searching
  10241. right-to-left, the first index considered is @code{(- @var{end} 1)},
  10242. whereas when searching left-to-right, the first index considered is @var{start}.
  10243. That is, the start/end indexes describe the same half-open interval
  10244. @code{[@var{start},@var{end})}
  10245. in these procedures that they do in other string procedures.
  10246. The @code{-skip} functions are similar, but use the complement of the
  10247. criterion: they search for the first char that @emph{doesn't} satisfy
  10248. @var{pred}. To skip over initial whitespace, for example, say
  10249. @example
  10250. (substring string
  10251. (or (string-skip string char-whitespace?)
  10252. (string-length string))
  10253. (string-length string))
  10254. @end example
  10255. These functions can be trivially composed with @code{string-take} and
  10256. @code{string-drop} to produce @code{take-while}, @code{drop-while},
  10257. @code{span}, and @code{break} procedures without loss of efficiency.
  10258. @end deffn
  10259. @c SRFI-13 and Guile generalizes pred to char_pred, which can be a
  10260. @c predicate, a character, or a character set. That seems
  10261. @c convenient.
  10262. @deffn Procedure string-contains string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10263. @deffnx Procedure string-contains-right string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
  10264. Does the substring of @var{string@sub{1}} specified by @var{start@sub{1}} and @var{end@sub{1}} contain the sequence of characters given by the substring of @var{string@sub{2}} specified by @var{start@sub{2}} and @var{end@sub{2}}?
  10265. Returns @code{#f} if there is no match.
  10266. If @var{start@sub{2}} = @var{end@sub{2}}, @code{string-contains}
  10267. returns @var{start@sub{1}} but @code{string-contains-right}
  10268. returns @var{end@sub{1}}. Otherwise returns the index in @var{string@sub{1}} for the first character of the first/last match; that index lies within the half-open interval [@var{start@sub{1}},@var{end@sub{1}}), and the match lies entirely within the [@var{start@sub{1}},@var{end@sub{1}}) range of @var{string@sub{1}}.
  10269. @example
  10270. (string-contains "eek -- what a geek." "ee" 12 18) ; Searches "a geek"
  10271. @result{} 15
  10272. @end example
  10273. Note: The names of these procedures do not end with a question mark. This indicates a useful value is returned when there is a match.
  10274. @end deffn
  10275. @subsection Concatenation and replacing
  10276. @deffn Procedure string-append @var{string} @dots{}
  10277. Returns a string whose characters form the concatenation
  10278. of the given strings.
  10279. @CompatibilityNote{} The result is an istring,
  10280. except in compatibility mode, when it is an mstring.
  10281. @end deffn
  10282. @deffn Procedure string-concatenate string-list
  10283. Concatenates the elements of @var{string-list} together into a single istring.
  10284. @emph{Rationale:} Some implementations of Scheme limit the number of
  10285. arguments that may be passed to an n-ary procedure, so the
  10286. @code{(apply string-append @var{string-list})} idiom,
  10287. which is otherwise equivalent to using this procedure, is not as portable.
  10288. @end deffn
  10289. @deffn Procedure string-concatenate-reverse string-list [final-string [end]])
  10290. With no optional arguments, calling this procedure is equivalent to
  10291. @code{(string-concatenate (reverse @var{string-list}))}.
  10292. If the optional argument @var{final-string} is specified,
  10293. it is effectively consed onto the beginning of @var{string-list}
  10294. before performing the list-reverse and string-concatenate operations.
  10295. If the optional argument @var{end} is given, only the characters up to but not including @var{end} in @var{final-string} are added to the result,
  10296. thus producing
  10297. @example
  10298. (string-concatenate
  10299. (reverse (cons (substring final-string 0 end)
  10300. string-list)))
  10301. @end example
  10302. For example:
  10303. @example
  10304. (string-concatenate-reverse '(" must be" "Hello, I") " going.XXXX" 7)
  10305. @result{} "Hello, I must be going."
  10306. @end example
  10307. @emph{Rationale:} This procedure is useful when constructing
  10308. procedures that accumulate character data into lists of string
  10309. buffers, and wish to convert the accumulated data into a single string
  10310. when done. The optional end argument accommodates that use case when
  10311. @var{final-string} is a bob-full mutable string,
  10312. and is allowed (for uniformity) when
  10313. @var{final-string} is an immutable string.
  10314. @end deffn
  10315. @deffn Procedure string-join string-list [delimiter [grammar]]
  10316. This procedure is a simple unparser; it pastes strings together
  10317. using the @var{delimiter} string, returning an istring.
  10318. The @var{string-list} is a list of strings.
  10319. The @var{delimiter} is the string used to delimit elements; it defaults to a single space @code{" "}.
  10320. The @var{grammar} argument is a symbol that determines how the @var{delimiter}
  10321. is used, and defaults to @code{'infix}.
  10322. It is an error for @var{grammar} to be any symbol other than these four:
  10323. @table @code
  10324. @item 'infix
  10325. An infix or separator grammar: insert the delimiter between list elements. An empty list will produce an empty string.
  10326. @item 'strict-infix
  10327. Means the same as @code{'infix} if the string-list is non-empty,
  10328. but will signal an error if given an empty list.
  10329. (This avoids an ambiguity shown in the examples below.)
  10330. @item 'suffix
  10331. Means a suffix or terminator grammar: insert the @var{delimiter}
  10332. after every list element.
  10333. @item 'prefix
  10334. Means a prefix grammar: insert the @var{delimiter} before every list element.
  10335. @end table
  10336. @example
  10337. (string-join '("foo" "bar" "baz"))
  10338. @result{} "foo bar baz"
  10339. (string-join '("foo" "bar" "baz") "")
  10340. @result{} "foobarbaz"
  10341. (string-join '("foo" "bar" "baz") ":")
  10342. @result{} "foo:bar:baz"
  10343. (string-join '("foo" "bar" "baz") ":" 'suffix)
  10344. @result{} "foo:bar:baz:"
  10345. ;; Infix grammar is ambiguous wrt empty list vs. empty string:
  10346. (string-join '() ":") @result{} ""
  10347. (string-join '("") ":") @result{} ""
  10348. ;; Suffix and prefix grammars are not:
  10349. (string-join '() ":" 'suffix)) @result{} ""
  10350. (string-join '("") ":" 'suffix)) @result{} ":"
  10351. @end example
  10352. @end deffn
  10353. @deffn Procedure string-replace string@sub{1} string@sub{2} start@sub{1} end@sub{1} [start@sub{2} end@sub{2}]
  10354. Returns
  10355. @example
  10356. (string-append (substring @var{string@sub{1}} 0 @var{start@sub{1}})
  10357. (substring @var{string@sub{2}} @var{start@sub{2}} @var{end@sub{2}})
  10358. (substring @var{string@sub{1}} @var{end@sub{1}} (string-length @var{string@sub{1}})))
  10359. @end example
  10360. That is, the segment of characters in @var{string@sub{1}} from @var{start@sub{1}}
  10361. to @var{end@sub{1}} is replaced by the segment of characters in @var{string@sub{2}} from @var{start@sub{2}} to @var{end@sub{2}}.
  10362. If @var{start@sub{1}}=@var{end@sub{1}}, this simply splices the characters
  10363. drawn from @var{string@sub{2}} into @var{string@sub{1}} at that position.
  10364. Examples:
  10365. @example
  10366. (string-replace "The TCL programmer endured daily ridicule."
  10367. "another miserable perl drone" 4 7 8 22)
  10368. @result{} "The miserable perl programmer endured daily ridicule."
  10369. (string-replace "It's easy to code it up in Scheme." "lots of fun" 5 9)
  10370. @result{} "It's lots of fun to code it up in Scheme."
  10371. (define (string-insert s i t) (string-replace s t i i))
  10372. (string-insert "It's easy to code it up in Scheme." 5 "really ")
  10373. @result{} "It's really easy to code it up in Scheme."
  10374. (define (string-set s i c) (string-replace s (string c) i (+ i 1)))
  10375. (string-set "String-ref runs in O(n) time." 19 #\1)
  10376. @result{} "String-ref runs in O(1) time."
  10377. @end example
  10378. @end deffn
  10379. Also see @code{string-append!} and @code{string-replace!}
  10380. for destructive changes to a mutable string.
  10381. @subsection Mapping and folding
  10382. @deffn Procedure string-fold kons knil string [start end]
  10383. @deffnx Procedure string-fold-right kons knil string [start end]
  10384. These are the fundamental iterators for strings.
  10385. The @code{string-fold} procedure maps the @var{kons} procedure across
  10386. the given @var{string} from left to right:
  10387. @example
  10388. (... (@var{kons} @var{string}@sub{2} (@var{kons} @var{string}@sub{1} (@var{kons} @var{string}@sub{0} @var{knil}))))
  10389. @end example
  10390. In other words, string-fold obeys the (tail) recursion
  10391. @example
  10392. (string-fold @var{kons} @var{knil} @var{string} @var{start} @var{end})
  10393. = (string-fold @var{kons} (@var{kons} @var{string}@sub{start} @var{knil}) @var{start+1} @var{end})
  10394. @end example
  10395. The @code{string-fold-right} procedure maps @var{kons} across the given
  10396. string @var{string} from right to left:
  10397. @example
  10398. (@var{kons} @var{string}@sub{0}
  10399. (... (@var{kons} @var{string}@sub{@var{end-3}}
  10400. (@var{kons} @var{string}@sub{@var{end-2}}
  10401. (@var{kons} @var{string}@sub{@var{end-1}}
  10402. @var{knil})))))
  10403. @end example
  10404. obeying the (tail) recursion
  10405. @example
  10406. (string-fold-right @var{kons} @var{knil} @var{string} @var{start} @var{end})
  10407. = (string-fold-right @var{kons} (@var{kons} @var{string}@sub{@var{end-1}} @var{knil}) @var{start} @var{end-1})
  10408. @end example
  10409. Examples:
  10410. @example
  10411. ;;; Convert a string or string to a list of chars.
  10412. (string-fold-right cons '() string)
  10413. ;;; Count the number of lower-case characters in a string or string.
  10414. (string-fold (lambda (c count)
  10415. (if (char-lower-case? c)
  10416. (+ count 1)
  10417. count))
  10418. 0
  10419. string)
  10420. @end example
  10421. The string-fold-right combinator is sometimes called a "catamorphism."
  10422. @end deffn
  10423. @deffn Procedure string-for-each @var{proc} @vari{string} @varii{string} @dots{}
  10424. @deffnx Procedure string-for-each @var{proc} @vari{string} [start [end]]
  10425. The @var{string}s must all have the same length. @var{proc} should
  10426. accept as many arguments as there are @var{string}s.
  10427. The @var{start}-@var{end} variant is provided for compatibility
  10428. with the SRFI-13 version. (In that case @var{start} and @var{end}
  10429. count code Unicode scalar values (@code{character} values),
  10430. not Java 16-bit @code{char} values.)
  10431. The @func{string-for-each} procedure applies @var{proc} element--wise to
  10432. the characters of the @var{string}s for its side effects, in order from
  10433. the first characters to the last. @var{proc} is always called in the
  10434. same dynamic environment as @func{string-for-each} itself.
  10435. @c The return values of @func{string-for-each} are unspecified.
  10436. Analogous to @func{for-each}.
  10437. @example
  10438. (let ((v '()))
  10439. (string-for-each
  10440. (lambda (c) (set! v (cons (char->integer c) v)))
  10441. "abcde")
  10442. v)
  10443. @result{} (101 100 99 98 97)
  10444. @end example
  10445. @PerformanceNote{} The compiler generates efficient code
  10446. for @code{string-for-each}.
  10447. If @var{proc} is a lambda expression, it is inlined.
  10448. @end deffn
  10449. @deffn Procedure string-map @var{proc} @vari{string} @varii{string} @dots{}
  10450. The @code{string-map} procedure applies @var{proc} element-wise to
  10451. the elements of the strings and returns a string of the results, in order.
  10452. It is an error if @var{proc} does not accept as many arguments as there
  10453. are strings, or return other than a single character or a string.
  10454. If more than one string is given and not all strings have the same length,
  10455. @code{string-map} terminates when the shortest string runs out.
  10456. The dynamic order in
  10457. which @var{proc} is applied to the elements of the strings is unspecified.
  10458. @c If multiple returns occur from string-map, the
  10459. @c values returned by earlier returns are not mutated.
  10460. @example
  10461. (string-map char-foldcase "AbdEgH") @result{} "abdegh"
  10462. @end example
  10463. @example
  10464. (string-map
  10465. (lambda (c) (integer->char (+ 1 (char->integer c))))
  10466. "HAL")
  10467. @result{} "IBM"
  10468. @end example
  10469. @example
  10470. (string-map
  10471. (lambda (c k)
  10472. ((if (eqv? k #\u) char-upcase char-downcase) c))
  10473. "studlycaps xxx"
  10474. "ululululul")
  10475. @result{} "StUdLyCaPs"
  10476. @end example
  10477. Traditionally the result of @var{proc} had to be a character,
  10478. but Kawa (and SRFI-140) allows the result to be a string.
  10479. @PerformanceNote{} The @code{string-map} procedure has not been
  10480. optimized (mainly because it is not very useful):
  10481. The characters are boxed, and the @var{proc} is not inlined even if
  10482. it is a lambda expression.
  10483. @end deffn
  10484. @deffn Procedure string-map-index proc string [start end]
  10485. Calls @var{proc} on each valid index of the specified substring, converts
  10486. the results of those calls into strings, and returns the concatenation
  10487. of those strings. It is an error for @var{proc} to return anything other
  10488. than a character or string. The dynamic order in which proc is called
  10489. on the indexes is unspecified, as is the dynamic order in which the
  10490. coercions are performed. If any strings returned by @var{proc} are mutated
  10491. after they have been returned and before the call to @code{string-map-index}
  10492. has returned, then @code{string-map-index} returns a string with unspecified
  10493. contents; the @var{string-map-index} procedure itself does not mutate those
  10494. strings.
  10495. @end deffn
  10496. @deffn Procedure string-for-each-index proc string [start end]
  10497. Calls @var{proc} on each valid index of the specified substring, in
  10498. increasing order, discarding the results of those calls. This is
  10499. simply a safe and correct way to loop over a substring.
  10500. Example:
  10501. @example
  10502. (let ((txt (string->string "abcde"))
  10503. (v '()))
  10504. (string-for-each-index
  10505. (lambda (cur) (set! v (cons (char->integer (string-ref txt cur)) v)))
  10506. txt)
  10507. v) @result{} (101 100 99 98 97)
  10508. @end example
  10509. @end deffn
  10510. @deffn Procedure string-count string pred [start end]
  10511. Returns a count of the number of characters in the specified substring
  10512. of @var{string} that satisfy the predicate @var{pred}.
  10513. @end deffn
  10514. @deffn Procedure string-filter pred string [start end]
  10515. @deffnx Procedure string-remove pred string [start end]
  10516. Return an immutable string consisting of only selected characters, in order:
  10517. @code{string-filter} selects only the characters that satisfy @var{pred};
  10518. @code{string-remove} selects only the characters that @emph{not}
  10519. satisfy @var{pred}
  10520. @end deffn
  10521. @subsection Replication & splitting
  10522. @deffn Procedure string-repeat string-or-character len
  10523. Create an istring by repeating the first argument @var{len} times.
  10524. If the first argument is a character, it is as if it were wrapped with
  10525. the @code{string} constructor.
  10526. We can define string-repeat in terms of the more general @code{xsubstring}
  10527. procedure:
  10528. @example
  10529. (define (string-repeat S N)
  10530. (let ((T (if (char? S) (string S) S)))
  10531. (xsubstring T 0 (* N (string-length T))))
  10532. @end example
  10533. @end deffn
  10534. @deffn Procedure xsubstring string [from to [start end]]
  10535. This is an extended substring procedure that implements replicated copying of a substring.
  10536. The @var{string} is a string; @var{start} and @var{end} are optional arguments that specify a substring of @var{string},
  10537. defaulting to 0 and the length of @var{string}.
  10538. This substring is conceptually replicated both up and down the index space,
  10539. in both the positive and negative directions.
  10540. For example, if @var{string} is @code{"abcdefg"}, @var{start} is 3,
  10541. and @var{end} is 6, then we have the conceptual bidirectionally-infinite string
  10542. @example
  10543. ... d e f d e f d e f d e f d e f d e f d ...
  10544. -9 -8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7 +8 +9
  10545. @end example
  10546. @code{xsubstring} returns the substring of the @var{string} beginning
  10547. at index @var{from}, and ending at @var{to}.
  10548. It is an error if @var{from} is greater than @var{to}.
  10549. If @var{from} and @var{to} are missing they default to 0 and
  10550. @var{from}+(@var{end}-@var{start}), respectively.
  10551. This variant is a generalization of using @code{substring},
  10552. but unlike @code{substring} never shares substructures that would
  10553. retain characters or sequences of characters that are substructures of
  10554. its first argument or previously allocated objects.
  10555. You can use @code{xsubstring} to perform a variety of tasks:
  10556. @itemize
  10557. @item
  10558. To rotate a string left: @code{(xsubstring "abcdef" 2 8) @result{} "cdefab"}
  10559. @item
  10560. To rotate a string right: @code{(xsubstring "abcdef" -2 4) @result{} "efabcd"}
  10561. @item
  10562. To replicate a string: @code{(xsubstring "abc" 0 7) @result{} "abcabca"}
  10563. @end itemize
  10564. Note that
  10565. @itemize
  10566. @item
  10567. The @var{from}/@var{to} arguments give a half-open range containing the
  10568. characters from index @var{from} up to, but not including, index @var{to}.
  10569. @item
  10570. The @var{from}/@var{to} indexes are not expressed in the index space of
  10571. @var{string}. They refer instead to the replicated index space of the
  10572. substring defined by @var{string}, @var{start}, and @var{end}.
  10573. @end itemize
  10574. It is an error if @var{start}=@var{end}, unless @var{from}=@var{to},
  10575. which is allowed as a special case.
  10576. @end deffn
  10577. @deffn Procedure string-split string delimiter [grammar limit start end]
  10578. Returns a list of strings representing the words contained in the substring of @var{string} from @var{start} (inclusive) to @var{end} (exclusive).
  10579. The @var{delimiter} is a string to be used as the word separator.
  10580. This will often be a single character, but multiple characters are
  10581. allowed for use cases such as splitting on @code{"\r\n"}.
  10582. The returned list will have one more item than the number of non-overlapping
  10583. occurrences of the @var{delimiter} in the string.
  10584. If @var{delimiter} is an empty string, then the returned list contains a
  10585. list of strings, each of which contains a single character.
  10586. The @var{grammar} is a symbol with the same meaning as in
  10587. the @code{string-join} procedure.
  10588. If it is @code{infix}, which is the default, processing is done as
  10589. described above, except an empty string produces the empty list;
  10590. if grammar is @code{strict-infix}, then an empty string signals an error.
  10591. The values @code{prefix} and @code{suffix} cause a leading/trailing empty string in the result to be suppressed.
  10592. If @var{limit} is a non-negative exact integer, at most that many splits occur, and the remainder of string is returned as the final element of the list (so the result will have at most limit+1 elements). If limit is not specified or is #f, then as many splits as possible are made. It is an error if limit is any other value.
  10593. To split on a regular expression, you can use SRFI 115's @code{regexp-split}
  10594. procedure.
  10595. @end deffn
  10596. @subsection String mutation
  10597. The following procedures create a mutable string,
  10598. i.e. one that you can modify.
  10599. @deffn Procedure make-string [@var{k} [@var{char}]]
  10600. Return a newly allocated mstring of @var{k} characters,
  10601. where @var{k} defaults to 0. If @var{char} is
  10602. given, then all elements of the string are initialized to @var{char},
  10603. otherwise the contents of the @var{string} are unspecified.
  10604. The 1-argument version is deprecated as poor style, except when k is 0.
  10605. @emph{Rationale:} In many languags the most common pattern for mutable strings
  10606. is to allocate an empty string and incrementally append to it.
  10607. It seems natural to initialize the string
  10608. with @code{(make-string)}, rather than @code{(make-string 0)}.
  10609. To return an immutable string that repeats @var{k} times a character
  10610. @var{char} use @code{string-repeat}.
  10611. This is as R7RS, except the result is variable-size and we allow
  10612. leaving out @var{k} when it is zero.
  10613. @end deffn
  10614. @deffn Procedure string-copy @var{string} [@var{start} [@var{end}]]
  10615. Returns a newly allocated mutable (mstring) copy of the part of the given
  10616. @var{string} between @var{start} and @var{end}.
  10617. @end deffn
  10618. The following procedures modify a mutable string.
  10619. @deffn Procedure string-set! string k char
  10620. This procedure stores @var{char} in element @var{k} of @var{string}.
  10621. @example
  10622. (define s1 (make-string 3 #\*))
  10623. (define s2 "***")
  10624. (string-set! s1 0 #\?) @result{} @emph{void}
  10625. s1 @result{} "?**"
  10626. (string-set! s2 0 #\?) @result{} @emph{error}
  10627. (string-set! (symbol->string 'immutable) 0 #\?) @result{} @emph{error}
  10628. @end example
  10629. @PerformanceNote{} Calling @code{string-set!} may take time proportional
  10630. to the length of the string: First it must scan for the right position,
  10631. like @code{string-ref} does. Then if the new character requires
  10632. using a surrogate pair (and the old one doesn't) then we have to make room
  10633. in the string, possibly re-allocating a new @code{char} array.
  10634. Alternatively, if the old character requires using a surrogate pair
  10635. (and the new one doesn't) then following characters need to be moved.
  10636. The function @code{string-set!} is deprecated: It is inefficient,
  10637. and it very seldom does the correct thing. Instead, you can
  10638. construct a string with @code{string-append!}.
  10639. @end deffn
  10640. @deffn Procedure string-append! @var{string} @var{value} @dots{}
  10641. The @var{string} must be a mutable string, such as one returned
  10642. by @code{make-string} or @code{string-copy}.
  10643. The @code{string-append!} procedure extends @var{string}
  10644. by appending each @var{value} (in order) to the end of @var{string}.
  10645. Each @code{value} should be a character or a string.
  10646. @PerformanceNote{} The compiler converts a call with multiple @var{value}s
  10647. to multiple @code{string-append!} calls.
  10648. If a @var{value} is known to be a @code{character}, then
  10649. no boxing (object-allocation) is needed.
  10650. The following example shows how to efficiently process a string
  10651. using @code{string-for-each} and incrementally ``build'' a result string
  10652. using @code{string-append!}.
  10653. @example
  10654. (define (translate-space-to-newline str::string)::string
  10655. (let ((result (make-string 0)))
  10656. (string-for-each
  10657. (lambda (ch)
  10658. (string-append! result
  10659. (if (char=? ch #\Space) #\Newline ch)))
  10660. str)
  10661. result))
  10662. @end example
  10663. @end deffn
  10664. @deffn Procedure string-copy! @var{to} @var{at} @var{from} [@var{start} [@var{end}]]
  10665. Copies the characters of the string @var{from} that are between
  10666. @var{start} end @var{end} into the string @var{to},
  10667. starting at index @var{at}. The order in which characters are copied
  10668. is unspecified, except that if the source and destination overlap,
  10669. copying takes place as if the source is first copied into a
  10670. temporary string and then into the destination.
  10671. (This is achieved without allocating storage by making sure to copy in
  10672. the correct direction in such circumstances.)
  10673. This is equivalent to (and implemented as):
  10674. @example
  10675. (string-replace! to at (+ at (- end start)) from start end))
  10676. @end example
  10677. @example
  10678. (define a "12345")
  10679. (define b (string-copy "abcde"))
  10680. (string-copy! b 1 a 0 2)
  10681. b @result{} "a12de"
  10682. @end example
  10683. @end deffn
  10684. @deffn Procedure string-replace! @var{dst} @var{dst-start} @var{dst-end} @var{src} [@var{src-start} [@var{src-end}]]
  10685. Replaces the characters of string @var{dst} (between @var{dst-start} and @var{dst-end}) with the characters of @var{src} (between @var{src-start} and @var{src-end}).
  10686. The number of characters from @var{src} may be different than the
  10687. number replaced in @var{dst}, so the string may grow or contract.
  10688. The special case where @var{dst-start} is equal to @var{dst-end} corresponds to
  10689. insertion; the case where @var{src-start} is equal to @var{src-end}
  10690. corresponds to deletion.
  10691. The order in which characters are copied
  10692. is unspecified, except that if the source and destination overlap,
  10693. copying takes place as if the source is first copied into a
  10694. temporary string and then into the destination.
  10695. (This is achieved without allocating storage by making sure to copy in
  10696. the correct direction in such circumstances.)
  10697. @end deffn
  10698. @deffn Procedure string-fill! @var{string} @var{fill} [@var{start} [@var{end}]]
  10699. The @code{string-fill!} procedure stores @var{fill} in the elements
  10700. of @var{string} between @var{start} and @var{end}.
  10701. It is an error if @var{fill} is not a character or is forbidden in strings.
  10702. @end deffn
  10703. @subsection Strings as sequences
  10704. @subsubsection Indexing a string
  10705. Using function-call syntax with strings is convenient
  10706. and efficient. However, it has some ``gotchas''.
  10707. We will use the following example string:
  10708. @example
  10709. (! str1 "Smile \x1f603;!")
  10710. @end example
  10711. or if you're brave:
  10712. @example
  10713. (! str1 "Smile 😃!")
  10714. @end example
  10715. This is @code{"Smile "} followed by an emoticon (``smiling face with
  10716. open mouth'') followed by @code{"!"}.
  10717. The emoticon has scalar value @code{\x1f603} - it is not
  10718. in the 16-bit Basic Multi-language Plane,
  10719. and so it must be encoded by a surrogate pair
  10720. (@code{#\xd83d} followed by @code{#\xde03}).
  10721. The number of scalar values (@code{character}s) is 8,
  10722. while the number of 16-bits code units (@code{char}s) is 9.
  10723. The @code{java.lang.CharSequence:length} method
  10724. counts @code{char}s. Both the @code{length} and the
  10725. @code{string-length} procedures count @code{character}s. Thus:
  10726. @example
  10727. (length str1) @result{} 8
  10728. (string-length str1) @result{} 8
  10729. (str1:length) @result{} 9
  10730. @end example
  10731. Counting @code{char}s is a constant-time operation (since it
  10732. is stored in the data structure).
  10733. Counting @code{character}s depends on the representation used:
  10734. In geneeral it may take time proportional to the length of
  10735. the string, since it has to subtract one for each surrogate pair;
  10736. however the @var{istring} type (@code{gnu.lists.IString} class)
  10737. uses a extra structure so it can count characters in constant-time.
  10738. Similarly we can can index the string in 3 ways:
  10739. @example
  10740. (str1 1) @result{} #\m :: character
  10741. (string-ref str1 1) @result{} #\m :: character
  10742. (str1:charAt 1) @result{} #\m :: char
  10743. @end example
  10744. Using function-call syntax when the ``function'' is a string
  10745. and a single integer argument is the same as using @code{string-ref}.
  10746. Things become interesting when we reach the emoticon:
  10747. @example
  10748. (str1 6) @result{} #\😃 :: character
  10749. (str1:charAt 6) @result{} #\d83d :: char
  10750. @end example
  10751. Both @code{string-ref} and the function-call syntax return the
  10752. real character, while the @code{charAt} methods returns a partial character.
  10753. @example
  10754. (str1 7) @result{} #\! :: character
  10755. (str1:charAt 7) @result{} #\de03 :: char
  10756. (str1 8) @result{} @i{throws} StringIndexOutOfBoundsException
  10757. (str1:charAt 8) @result{} #\! :: char
  10758. @end example
  10759. @subsubsection Indexing with a sequence
  10760. You can index a string with a list of integer indexes,
  10761. most commonly a range:
  10762. @example
  10763. (@var{str} [@var{i} ...])
  10764. @end example
  10765. is basically the same as:
  10766. @example
  10767. (string (@var{str} @var{i}) ...)
  10768. @end example
  10769. Generally when working with strings it is best to
  10770. work with substrings rather than individual characters:
  10771. @example
  10772. (@var{str} [@var{start} <: @var{end}])
  10773. @end example
  10774. This is equivalent to invoking the @code{substring} procedure:
  10775. @example
  10776. (substring @var{str} @var{start} @var{end})
  10777. @end example
  10778. @c not implemented yet
  10779. @c @subsubsection Assigning to a subsequence
  10780. @anchor{String Cursor API}
  10781. @subsection String Cursor API
  10782. Indexing into a string (using for example @code{string-ref})
  10783. is inefficient because of the possible presence of surrogate pairs.
  10784. Hence given an index @var{i} access normally requires linearly
  10785. scanning the string until we have seen @var{i} characters.
  10786. The string-cursor API is defined in terms of abstract ``cursor values'',
  10787. which point to a position in the string. This avoids the linear scan.
  10788. Typical usage is:
  10789. @example
  10790. (let* ((str @var{whatever})
  10791. (end (string-cursor-end str)))
  10792. (do ((sc::string-cursor (string-cursor-start str)
  10793. (string-cursor-next str sc)))
  10794. ((string-cursor>=? sc end))
  10795. (let ((ch (string-cursor-ref str sc)))
  10796. (@var{do-something-with} ch))))
  10797. @end example
  10798. Alternatively, the following may be marginally faster:
  10799. @example
  10800. (let* ((str @var{whatever})
  10801. (end (string-cursor-end str)))
  10802. (do ((sc::string-cursor (string-cursor-start str)
  10803. (string-cursor-next-quick sc)))
  10804. ((string-cursor>=? sc end))
  10805. (let ((ch (string-cursor-ref str sc)))
  10806. (if (not (char=? ch #\ignorable-char))
  10807. (@var{do-something-with} ch)))))
  10808. @end example
  10809. The API is non-standard, but is based on that in Chibi Scheme.
  10810. @deffn Type string-cursor
  10811. An abstract position (index) in a string.
  10812. Implemented as a primitive @code{int} which counts the
  10813. number of preceding code units (16-bit @code{char} values).
  10814. @end deffn
  10815. @deffn Procedure string-cursor-start str
  10816. Returns a cursor for the start of the string.
  10817. The result is always 0, cast to a @code{string-cursor}.
  10818. @end deffn
  10819. @deffn Procedure string-cursor-end str
  10820. Returns a cursor for the end of the string - one past the last valid character.
  10821. Implemented as @code{(as string-cursor (invoke @var{str} 'length))}.
  10822. @end deffn
  10823. @deffn Procedure string-cursor-ref str cursor
  10824. Return the @code{character} at the @var{cursor}.
  10825. If the @var{cursor} points to the second @code{char} of a surrogate pair,
  10826. returns @code{#\ignorable-char}.
  10827. @end deffn
  10828. @deffn Procedure string-cursor-next string cursor [count]
  10829. Return the cursor position @var{count} (default 1) character
  10830. positions forwards beyond @var{cursor}.
  10831. For each @var{count} this may add either 1 or 2
  10832. (if pointing at a surrogate pair) to the @var{cursor}.
  10833. @end deffn
  10834. @deffn Procedure string-cursor-next-quiet cursor
  10835. Increment cursor by one raw @code{char} position,
  10836. even if @var{cursor} points to the start of a surrogate pair.
  10837. (In that case the next @code{string-cursor-ref} will
  10838. return @code{#\ignorable-char}.)
  10839. Same as @code{(+ @var{cursor} 1)} but with the @code{string-cursor} type.
  10840. @end deffn
  10841. @deffn Procedure string-cursor-prev string cursor [count]
  10842. Return the cursor position @var{count} (default 1) character
  10843. positions backwards before @var{cursor}.
  10844. @end deffn
  10845. @deffn Procedure substring-cursor string [start [end]]
  10846. Create a substring of the section of @var{string}
  10847. between the cursors @var{start} and @var{end}.
  10848. @end deffn
  10849. @deffn Procedure string-cursor<? cursor1 cursor2
  10850. @deffnx Procedure string-cursor<=? cursor1 cursor2
  10851. @deffnx Procedure string-cursor=? cursor1 cursor2
  10852. @deffnx Procedure string-cursor>=? cursor1 cursor2
  10853. @deffnx Procedure string-cursor>? cursor1 cursor2
  10854. Is the position of @var{cursor1} respectively before,
  10855. before or same, same, after, or after or same, as @var{cursor2}.
  10856. @PerformanceNote{} Implemented as the corresponding @code{int} comparison.
  10857. @end deffn
  10858. @c non-chibi
  10859. @deffn Procedure string-cursor-for-each proc string [start [end]]
  10860. Apply the procedure @var{proc} to each character position in
  10861. @var{string} between the cursors @var{start} and @var{end}.
  10862. @end deffn
  10863. @node String literals
  10864. @section String literals
  10865. Kaw support two syntaxes of string literals:
  10866. The traditional, portable, qdouble-quoted-delimited literals
  10867. like @code{"this"};
  10868. and extended SRFI-109 quasi-literals like @code{&@{this@}}.
  10869. @subsection Simple string literals
  10870. @display
  10871. @stxdef{string} @stxlit{"}@arbno{@stxref{string-element}}@stxlit{"}
  10872. @stxdef{string-element} @i{any character other than} @stxlit{"} @i{or} @stxlit{@backslashchar{}}
  10873. | @stxref{mnemonic-escape} | @stxlit{@backslashchar{}"} | @stxlit{@backslashchar{}@backslashchar{}}
  10874. | @stxlit{@backslashchar{}}@arbno{@stxref{intraline-whitespace}}@stxref{line-ending} @arbno{@stxref{intraline-whitespace}}
  10875. | @stxref{inline-hex-escape}
  10876. @stxdef{mnemonic-escape} @stxlit{@backslashchar{}a} | @stxlit{@backslashchar{}b} | @stxlit{@backslashchar{}t} | @stxlit{@backslashchar{}n} | @stxlit{@backslashchar{}r} | ... @i{(see below)}
  10877. @end display
  10878. A string is written as a sequence of characters enclosed
  10879. within quotation marks (@stxlit{"}).
  10880. Within a string literal, various escape sequence represent characters
  10881. other than themselves.
  10882. Escape sequences always start with a backslash (@stxlit{@backslashchar{}}):
  10883. @table @asis
  10884. @item @stxlit{@backslashchar{}a}
  10885. Alarm (bell), @code{#\x0007}.
  10886. @item @stxlit{@backslashchar{}b}
  10887. Backspace, @code{#\x0008}.
  10888. @item @stxlit{@backslashchar{}e}
  10889. Escape, @code{#\x001B}.
  10890. @item @stxlit{@backslashchar{}f}
  10891. Form feed, @code{#\x000C}.
  10892. @item @stxlit{@backslashchar{}n}
  10893. Linefeed (newline), @code{#\x000A}.
  10894. @item @stxlit{@backslashchar{}r}
  10895. Return, @code{#\x000D}.
  10896. @item @stxlit{@backslashchar{}t}
  10897. Character tabulation, @code{#\x0009}.
  10898. @item @stxlit{@backslashchar{}v}
  10899. Vertical tab, @code{#\x000B}.
  10900. @item @stxlit{@backslashchar{}C-}@meta{x}
  10901. @itemx @stxlit{@backslashchar{}^}@meta{x}
  10902. Returns the scalar value of @meta{x} masked (anded) with @code{#x9F}.
  10903. An alternative way to write the Ascii control characters:
  10904. For example @code{"\C-m"} or @code{"\^m"} is
  10905. the same as @code{"#\x000D"} (which the same as @code{"\r"}).
  10906. As a special case @code{\^?} is rubout (delete) (@code{\x7f;}).
  10907. @item @stxlit{@backslashchar{}x} @stxref{hex-scalar-value}@stxlit{;}
  10908. @itemx @stxlit{@backslashchar{}X} @stxref{hex-scalar-value}@stxlit{;}
  10909. A hex encoding that gives the scalar value of a character.
  10910. @item @stxlit{@backslashchar{}@backslashchar{}} @atleastone{@stxref{oct-digit}}
  10911. At most three octal digits that give the scalar value of a character.
  10912. (Historical, for C compatibility.)
  10913. @item @stxlit{@backslashchar{}u} @atleastone{@stxref{hex-digit}}
  10914. Exactly four hex digits that give the scalar value of a character.
  10915. (Historical, for Java compatibility.)
  10916. @item @stxlit{@backslashchar{}M-}@meta{x}
  10917. (Historical, for Emacs Lisp.)
  10918. Set the meta-bit (high-bit of single byte) of the following character @var{x}.
  10919. @item @stxlit{@backslashchar{}|}
  10920. Vertical line, @code{#\x007c}.
  10921. (Not useful for string literals, but useful for symbols.)
  10922. @item @stxlit{@backslashchar{}"}
  10923. Double quote, @code{#\x0022}.
  10924. @item @stxlit{@backslashchar{}@backslashchar{}}
  10925. Backslah, @code{#\005C}.
  10926. @item @stxlit{@backslashchar{}}@arbno{@stxref{intraline-whitespace}}@stxref{line-ending} @arbno{@stxref{intraline-whitespace}}
  10927. Nothing (ignored). Allows you to split up a long string over multiple
  10928. lines; ignoring initial whitespace on the continuation lines allows
  10929. you to indent them.
  10930. @end table
  10931. Except for a line ending, any character outside of an escape
  10932. sequence stands for itself in the string literal. A line ending
  10933. which is preceded by @stxlit{@backslashchar{}}@arbno{@meta{intraline-whitespace}}
  10934. expands to nothing (along with any trailing @meta{intraline-whitespace}),
  10935. and can be used to indent strings for improved legibility.
  10936. Any other line ending has the same effect as inserting a @stxlit{@backslashchar{}n}
  10937. character into the string.
  10938. Examples:
  10939. @example
  10940. "The word \"recursion\" has many meanings."
  10941. "Another example:\ntwo lines of text"
  10942. "Here’s text \
  10943. containing just one line"
  10944. "\x03B1; is named GREEK SMALL LETTER ALPHA."
  10945. @end example
  10946. @anchor{string quasi-literals}
  10947. @subsection String templates
  10948. The following syntax is a @dfn{string template} (also called
  10949. a string quasi-literal or
  10950. ``@uref{http://en.wikipedia.org/wiki/Here_document, here document}''):
  10951. @example
  10952. &@{Hello &[name]!@}
  10953. @end example
  10954. Assuming the variable @code{name} evaluates to @code{"John"}
  10955. then the example evaluates to @code{"Hello John!"}.
  10956. The Kawa reader converts the above example to:
  10957. @example
  10958. ($string$ "Hello " $<<$ name $>>$ "!")
  10959. @end example
  10960. See the @uref{http://srfi.schemers.org/srfi-109/srfi-109.html,SRFI-109}
  10961. specification for details.
  10962. @display
  10963. @stxdef{extended-string-literal} @stxlit{&@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{string-literal-part}} @stxlit{@rbracechar{}}
  10964. @stxdef{string-literal-part} @i{any character except} @stxlit{&}, @stxlit{@lbracechar{}} @i{or} @stxlit{@rbracechar{}}
  10965. | @stxlit{@lbracechar{}} @arbno{@stxref{string-literal-part}} @stxlit{@rbracechar{}}
  10966. | @stxref{char-ref}
  10967. | @stxref{entity-ref}
  10968. | @stxref{special-escape}
  10969. | @stxref{enclosed-part}
  10970. @end display
  10971. You can use the plain @code{"@var{string}"} syntax for
  10972. longer multiline strings, but @code{&@{@var{string}@}} has
  10973. various advantages.
  10974. The syntax is less error-prone because the start-delimiter is
  10975. different from the end-delimiter. Also note that nested braces
  10976. are allowed: a right brace @code{@rbracechar{}} is only an end-delimiter
  10977. if it is unbalanced, so you would seldom need to escape it:
  10978. @example
  10979. &@{This has a @{braced@} section.@}
  10980. @result{} "This has a @{braced@} section."
  10981. @end example
  10982. The escape character used for special characters is
  10983. @stxlit{&}. This is compatible with XML syntax and @ref{XML literals}.
  10984. @subsubsection Special characters
  10985. @display
  10986. @stxdef{char-ref}
  10987. @stxlit{&#} @atleastone{@stxref{digit}} @stxlit{;}
  10988. | @stxlit{&#x} @atleastone{@stxref{hex-digit}} @stxlit{;}
  10989. @stxdef{entity-ref}
  10990. @stxlit{&} @stxref{char-or-entity-name} @stxlit{;}
  10991. @stxdef{char-or-entity-name} @meta{tagname}
  10992. @end display
  10993. You can the standard XML syntax for character references, using
  10994. either decimal or hexadecimal values. The following string has two
  10995. instances of the Ascii escape character, as either decimal 27 or hex 1B:
  10996. @example
  10997. &@{&#27;&#x1B;@} @result{} "\e\e"
  10998. @end example
  10999. You can also use the pre-defined XML entity names:
  11000. @example
  11001. &@{&amp; &lt; &gt; &quot; &apos;@} @result{} "& < > \" '"
  11002. @end example
  11003. In addition, @code{&lbrace;} @code{&rbrace;} can be used for left and
  11004. right curly brace, though you don't need them for balanced parentheses:
  11005. @example
  11006. &@{ &rbrace;_&lbrace; / @{_@} @} @result{} " @}_@{ / @{_@} "
  11007. @end example
  11008. You can use the @uref{http://www.w3.org/2003/entities/2007/w3centities-f.ent,standard XML entity names}. For example:
  11009. @example
  11010. &@{L&aelig;rdals&oslash;yri@}
  11011. @result{} "Lærdalsøyri"
  11012. @end example
  11013. You can also use the standard R7RS character names @code{null},
  11014. @code{alarm}, @code{backspace}, @code{tab}, @code{newline}, @code{return},
  11015. @code{escape}, @code{space}, and @code{delete}.
  11016. For example:
  11017. @example
  11018. &@{&escape;&space;@}
  11019. @end example
  11020. The syntax @code{&@var{name};} is actually syntactic sugar
  11021. (specifically reader syntax) to the variable reference
  11022. @code{$entity$:@var{name}}.
  11023. Hence you can also define your own entity names:
  11024. @example
  11025. (define $entity$:crnl "\r\n")
  11026. &@{&crnl;@} ⟹ "\r\n"
  11027. @end example
  11028. @subsubsection Multiline string literals
  11029. @example
  11030. @stxdef{initial-ignored}
  11031. @arbno{@stxref{intraline-whitespace}} @stxref{line-ending} @arbno{@stxref{intraline-whitespace}} @stxlit{&|}
  11032. @stxdef{special-escape}
  11033. @arbno{@stxref{intraline-whitespace}} @stxlit{&|}
  11034. | @stxlit{&} @stxref{nested-comment}
  11035. | @stxlit{&-} @arbno{@stxref{intraline-whitespace}} @stxref{line-ending}
  11036. @end example
  11037. A line-ending directly in the text is becomes a newline,
  11038. as in a simple string literal:
  11039. @example
  11040. (string-capitalize &@{one two three
  11041. uno dos tres
  11042. @}) @result{} "One Two Three\nUno Dos Tres\n"
  11043. @end example
  11044. However, you have extra control over layout.
  11045. If the string is in a nested expression, it is confusing
  11046. (and ugly) if the string cannot be indented to match
  11047. the surrounding context. The indentation marker @stxlit{&|}
  11048. is used to mark the end of insignificant initial whitespace.
  11049. The @code{&|} characters and all the preceding whitespace are removed.
  11050. In addition, it also suppresses an initial newline. Specifically,
  11051. when the initial left-brace is followed by optional (invisible)
  11052. intraline-whitespace, then a newline, then optional
  11053. intraline-whitespace (the indentation), and finally the indentation
  11054. marker @code{&|} - all of which is removed from the output.
  11055. Otherwise the @code{&|} only removes initial intraline-whitespace
  11056. on the same line (and itself).
  11057. @example
  11058. (write (string-capitalize &@{
  11059. &|one two three
  11060. &|uno dos tres
  11061. @}) out)
  11062. @result{} @i{prints} "One Two Three\nUno Dos Tres\n"
  11063. @end example
  11064. As a matter of style, all of the indentation lines should line up.
  11065. It is an error if there are any non-whitespace characters between
  11066. the previous newline and the indentation marker.
  11067. It is also an error to write an indentation marker before the
  11068. first newline in the literal.
  11069. The line-continuation marker @stxlit{&-} is used to suppress a newline:
  11070. @example
  11071. &@{abc&-
  11072. def@} @result{} "abc def"
  11073. @end example
  11074. You can write a @code{#|...|#}-style comment following a @code{&}.
  11075. This could be useful for annotation, or line numbers:
  11076. @example
  11077. &@{&#|line 1|#one two
  11078. &#|line 2|# three
  11079. &#|line 3|#uno dos tres
  11080. @} @result{} "one two\n three\nuno dos tres\n"
  11081. @end example
  11082. @subsubsection Embedded expressions
  11083. @example
  11084. @stxdef{enclosed-part}
  11085. @stxlit{&} @arbno{@stxref{enclosed-modifier}} @stxlit{[} @arbno{@stxref{expression}} @stxlit{]}
  11086. | @stxlit{&} @arbno{@stxref{enclosed-modifier}} @stxlit{(} @atleastone{@stxref{expression}} @stxlit{)}
  11087. @end example
  11088. An embedded expression has the form @code{&[@var{expression}]}.
  11089. It is evaluated, the result converted to a string (as by @code{display}),
  11090. and the result added in the result string.
  11091. (If there are multiple expressions, they are all evaluated and
  11092. the corresponding strings inserted in the result.)
  11093. @example
  11094. &@{Hello &[(string-capitalize name)]!@}
  11095. @end example
  11096. You can leave out the square brackets when the expression
  11097. is a parenthesized expression:
  11098. @example
  11099. &@{Hello &(string-capitalize name)!@}
  11100. @end example
  11101. @subsubsection Formatting
  11102. @example
  11103. @stxdef{enclosed-modifier}
  11104. @stxlit{~} @meta{format-specifier-after-tilde}
  11105. @end example
  11106. Using @ref{Format,@code{format}} allows finer-grained control over the
  11107. output, but a problem is that the association between format
  11108. specifiers and data expressions is positional, which is hard-to-read
  11109. and error-prone. A better solution places the specifier adjacant to
  11110. the data expression:
  11111. @example
  11112. &@{The response was &~,2f(* 100.0 (/ responses total))%.@}
  11113. @end example
  11114. The following escape forms are equivalent to the corresponding
  11115. forms withput the @stxlit{~}@meta{fmt-spec}, except the
  11116. expression(s) are formatted using @code{format}:
  11117. @display
  11118. @stxlit{&~}@meta{fmt-spec}@stxlit{[}@arbno{@meta{expression}}@stxlit{]}
  11119. @end display
  11120. Again using parentheses like this:
  11121. @display
  11122. @stxlit{&~}@meta{fmt-spec}@stxlit{(}@atleastone{@meta{expression}}@stxlit{)}
  11123. @end display
  11124. is equivalent to:
  11125. @display
  11126. @stxlit{&~}@meta{fmt-spec}@stxlit{[(}@atleastone{@meta{expression}}@stxlit{)]}
  11127. @end display
  11128. The syntax of @code{format} specifications is arcane, but it allows you
  11129. to do some pretty neat things in a compact space.
  11130. For example to include @code{"_"} between each element of
  11131. the array @code{arr} you can use the @code{~@{...~@}} format speciers:
  11132. @example
  11133. (define arr [5 6 7])
  11134. &@{&~@{&[arr]&~^_&~@}@} @result{} "5_6_7"
  11135. @end example
  11136. If no format is specified for an enclosed expression,
  11137. the that is equivalent to a @code{~a} format specifier,
  11138. so this is equivalent to:
  11139. @example
  11140. &@{&~@{&~a[arr]&~^_&~@}@} @result{} "5_6_7"
  11141. @end example
  11142. which is in turn equivalent to:
  11143. @example
  11144. (format #f "~@{~a~^_~@}" arr)
  11145. @end example
  11146. The fine print that makes this work:
  11147. If there are multiple expressions in a @code{&[...]} with
  11148. no format specifier then there is an implicit @code{~a} for
  11149. each expression.
  11150. On the other hand, if there is an explicit format specifier,
  11151. it is not repeated for each enclosed expression: it appears
  11152. exactly once in the effective format string, whether
  11153. there are zero, one, or many expressions.
  11154. @node Unicode
  11155. @section Unicode character classes and conversions
  11156. @ignore
  11157. The procedures exported by the @rsixlibrary{unicode} library provide
  11158. access to some aspects of the Unicode semantics for characters and
  11159. strings: category information, case--independent comparisons, case
  11160. mappings, and normalization.
  11161. @end ignore
  11162. Some of the procedures that operate on characters or strings ignore the
  11163. difference between upper case and lower case. These procedures have
  11164. @code{-ci} (for ``case insensitive'') embedded in their names.
  11165. @subsection Characters
  11166. @deffn Procedure char-upcase @var{char}
  11167. @deffnx Procedure char-downcase @var{char}
  11168. @deffnx Procedure char-titlecase @var{char}
  11169. @deffnx Procedure char-foldcase @var{char}
  11170. These procedures take a character argument and return a character
  11171. result.
  11172. If the argument is an upper--case or title--case character, and if there
  11173. is a single character that is its lower--case form, then
  11174. @func{char-downcase} returns that character.
  11175. If the argument is a lower--case or title--case character, and there is
  11176. a single character that is its upper--case form, then @func{char-upcase}
  11177. returns that character.
  11178. If the argument is a lower--case or upper--case character, and there is
  11179. a single character that is its title--case form, then
  11180. @func{char-titlecase} returns that character.
  11181. If the argument is not a title--case character and there is no single
  11182. character that is its title--case form, then @func{char-titlecase}
  11183. returns the upper--case form of the argument.
  11184. Finally, if the character has a case--folded character, then
  11185. @func{char-foldcase} returns that character. Otherwise the character
  11186. returned is the same as the argument.
  11187. For Turkic characters @code{#\x130} and @code{#\x131},
  11188. @func{char-foldcase} behaves as the identity function; otherwise
  11189. @func{char-foldcase} is the same as @func{char-downcase} composed with
  11190. @func{char-upcase}.
  11191. @example
  11192. (char-upcase #\i) @result{} #\I
  11193. (char-downcase #\i) @result{} #\i
  11194. (char-titlecase #\i) @result{} #\I
  11195. (char-foldcase #\i) @result{} #\i
  11196. (char-upcase #\ß) @result{} #\ß
  11197. (char-downcase #\ß) @result{} #\ß
  11198. (char-titlecase #\ß) @result{} #\ß
  11199. (char-foldcase #\ß) @result{} #\ß
  11200. (char-upcase #\Σ) @result{} #\Σ
  11201. (char-downcase #\Σ) @result{} #\σ
  11202. (char-titlecase #\Σ) @result{} #\Σ
  11203. (char-foldcase #\Σ) @result{} #\σ
  11204. (char-upcase #\ς) @result{} #\Σ
  11205. (char-downcase #\ς) @result{} #\ς
  11206. (char-titlecase #\ς) @result{} #\Σ
  11207. (char-foldcase #\ς) @result{} #\σ
  11208. @end example
  11209. @quotation
  11210. @emph{Note:} @func{char-titlecase} does not always return a title--case
  11211. character.
  11212. @end quotation
  11213. @quotation
  11214. @emph{Note:} These procedures are consistent with Unicode's
  11215. locale--independent mappings from scalar values to scalar values for
  11216. upcase, downcase, titlecase, and case--folding operations. These
  11217. mappings can be extracted from @file{UnicodeData.txt} and
  11218. @file{CaseFolding.txt} from the Unicode Consortium, ignoring Turkic
  11219. mappings in the latter.
  11220. Note that these character--based procedures are an incomplete
  11221. approximation to case conversion, even ignoring the user's locale. In
  11222. general, case mappings require the context of a string, both in
  11223. arguments and in result. The @func{string-upcase},
  11224. @func{string-downcase}, @func{string-titlecase}, and
  11225. @func{string-foldcase} procedures perform more general case conversion.
  11226. @end quotation
  11227. @end deffn
  11228. @deffn Procedure char-ci=? @vari{char} @varii{char} @variii{char} @dots{}
  11229. @deffnx Procedure char-ci<? @vari{char} @varii{char} @variii{char} @dots{}
  11230. @deffnx Procedure char-ci>? @vari{char} @varii{char} @variii{char} @dots{}
  11231. @deffnx Procedure char-ci<=? @vari{char} @varii{char} @variii{char} @dots{}
  11232. @deffnx Procedure char-ci>=? @vari{char} @varii{char} @variii{char} @dots{}
  11233. These procedures are similar to @func{char=?}, etc., but operate on the
  11234. case--folded versions of the characters.
  11235. @example
  11236. (char-ci<? #\z #\Z) @result{} #f
  11237. (char-ci=? #\z #\Z) @result{} #f
  11238. (char-ci=? #\ς #\σ) @result{} #t
  11239. @end example
  11240. @end deffn
  11241. @deffn Procedure char-alphabetic? @var{char}
  11242. @deffnx Procedure char-numeric? @var{char}
  11243. @deffnx Procedure char-whitespace? @var{char}
  11244. @deffnx Procedure char-upper-case? @var{char}
  11245. @deffnx Procedure char-lower-case? @var{char}
  11246. @deffnx Procedure char-title-case? @var{char}
  11247. These procedures return @true{} if their arguments are alphabetic,
  11248. numeric, whitespace, upper--case, lower--case, or title--case
  11249. characters, respectively; otherwise they return @false{}.
  11250. A character is alphabetic if it has the Unicode ``Alphabetic'' property.
  11251. A character is numeric if it has the Unicode ``Numeric'' property. A
  11252. character is whitespace if has the Unicode ``White_Space'' property. A
  11253. character is upper case if it has the Unicode ``Uppercase'' property,
  11254. lower case if it has the ``Lowercase'' property, and title case if it is
  11255. in the Lt general category.
  11256. @example
  11257. (char-alphabetic? #\a) @result{} #t
  11258. (char-numeric? #\1) @result{} #t
  11259. (char-whitespace? #\space) @result{} #t
  11260. (char-whitespace? #\x00A0) @result{} #t
  11261. (char-upper-case? #\Σ) @result{} #t
  11262. (char-lower-case? #\σ) @result{} #t
  11263. (char-lower-case? #\x00AA) @result{} #t
  11264. (char-title-case? #\I) @result{} #f
  11265. (char-title-case? #\x01C5) @result{} #t
  11266. @end example
  11267. @end deffn
  11268. @deffn Procedure char-general-category @var{char}
  11269. Return a symbol representing the Unicode general category of
  11270. @var{char}, one of @code{Lu}, @code{Ll}, @code{Lt}, @code{Lm},
  11271. @code{Lo}, @code{Mn}, @code{Mc}, @code{Me}, @code{Nd}, @code{Nl},
  11272. @code{No}, @code{Ps}, @code{Pe}, @code{Pi}, @code{Pf}, @code{Pd},
  11273. @code{Pc}, @code{Po}, @code{Sc}, @code{Sm}, @code{Sk}, @code{So},
  11274. @code{Zs}, @code{Zp}, @code{Zl}, @code{Cc}, @code{Cf}, @code{Cs},
  11275. @code{Co}, or @code{Cn}.
  11276. @example
  11277. (char-general-category #\a) @result{} Ll
  11278. (char-general-category #\space) @result{} Zs
  11279. (char-general-category #\x10FFFF) @result{} Cn
  11280. @end example
  11281. @end deffn
  11282. @subsection Deprecated in-place case modification
  11283. The following functions are deprecated; they really don't
  11284. and cannot do the right thing, because in some languages
  11285. upper and lower case can use different number of characters.
  11286. @deffn Procedure string-upcase! str
  11287. @emph{Deprecated:} Destructively modify @var{str}, replacing the letters
  11288. by their upper-case equivalents.
  11289. @end deffn
  11290. @deffn Procedure string-downcase! str
  11291. @emph{Deprecated:} Destructively modify @var{str}, replacing the letters
  11292. by their upper-lower equivalents.
  11293. @end deffn
  11294. @deffn Procedure string-capitalize! str
  11295. @emph{Deprecated:} Destructively modify @var{str}, such that the letters that start a new word
  11296. are replaced by their title-case equivalents, while non-initial letters
  11297. are replaced by their lower-case equivalents.
  11298. @end deffn
  11299. @node Regular expressions, , Unicode, Characters and text
  11300. @section Regular expressions
  11301. Kawa provides @dfn{regular expressions}, which is a convenient
  11302. mechanism for matching a string against a @dfn{pattern}
  11303. and maybe replacing matching parts.
  11304. A regexp is a string that describes a pattern. A regexp matcher tries
  11305. to match this pattern against (a portion of) another string, which we
  11306. will call the text string. The text string is treated as raw text and
  11307. not as a pattern.
  11308. Most of the characters in a regexp pattern are meant to match
  11309. occurrences of themselves in the text string. Thus, the pattern ``@code{abc}''
  11310. matches a string that contains the characters ``@code{a}'', ``@code{b}'',
  11311. ``@code{c}'' in succession.
  11312. In the regexp pattern, some characters act as @dfn{metacharacters},
  11313. and some character sequences act as @dfn{metasequences}. That is, they
  11314. specify something other than their literal selves. For example, in the
  11315. pattern ``@code{a.c}'', the characters ``@code{a}'' and ``@code{c}'' do stand
  11316. for themselves but the metacharacter ``@code{.}'' can match any character
  11317. (other than newline). Therefore, the pattern ``@code{a.c}'' matches an
  11318. ``@code{a}'', followed by any character, followed by a ``@code{c}''.
  11319. If we needed to match the character ``@code{.}'' itself, we @dfn{escape}
  11320. it, ie, precede it with a backslash ``@code{\}''. The character sequence
  11321. ``@code{\.}'' is thus a metasequence, since it doesn’t match itself but
  11322. rather just ``@code{.}''. So, to match ``@code{a}'' followed by a literal
  11323. ``@code{.}'' followed by ``@code{c}'' we use the regexp pattern
  11324. ``@code{a\.c}''. To write this as a Scheme string literal,
  11325. you need to quote the backslash, so you need to write @code{"a\\.c"}.
  11326. Kawa also allows the literal syntax @code{#/a\.c/},
  11327. which avoids the need to double the backslashes.
  11328. You can choose between two similar styles of regular expressions.
  11329. The two differ slightly in terms of which characters act as metacharacters,
  11330. and what those metacharacters mean:
  11331. @itemize
  11332. @item
  11333. Functions starting with @code{regex-} are implemented using
  11334. the @code{java.util.regex} package.
  11335. This is likely to be more efficient, has better Unicode support and
  11336. some other minor extra features, and literal syntax @code{#/a\.c/}
  11337. mentioned above.
  11338. @item
  11339. Functions starting with @code{pregexp-} are implemented in pure Scheme
  11340. using Dorai Sitaram's ``Portable Regular Expressions for Scheme'' library.
  11341. These will be portable to more Scheme implementations, including BRL,
  11342. and is available on older Java versions.
  11343. @end itemize
  11344. @subsection Java regular expressions
  11345. The syntax for regular expressions is
  11346. @uref{http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html, documented here}.
  11347. @deffn Type regex
  11348. A compiled regular expression,
  11349. implemented as @code{java.util.regex.Pattern}.
  11350. @end deffn
  11351. @deffn Constructor regex arg
  11352. Given a regular expression pattern (as a string),
  11353. compiles it to a @code{regex} object.
  11354. @example
  11355. (regex "a\\.c")
  11356. @end example
  11357. This compiles into a pattern that matches an
  11358. ``@code{a}'', followed by any character, followed by a ``@code{c}''.
  11359. @end deffn
  11360. The Scheme reader recognizes ``@code{#/}'' as the start of a
  11361. regular expression @dfn{pattern literal}, which ends with the next
  11362. un-escaped ``@code{/}''.
  11363. This has the big advantage that you don't need to double the backslashes:
  11364. @example
  11365. #/a\.c/
  11366. @end example
  11367. This is equivalent to @code{(regex "a\\.c")}, except it is
  11368. compiled at read-time.
  11369. If you need a literal ``@code{/}'' in a pattern, just escape it
  11370. with a backslash: ``@code{#/a\/c/}'' matches a ``@code{a}'',
  11371. followed by a ``@code{/}'', followed by a ``@code{c}''.
  11372. You can add single-letter @emph{modifiers} following the pattern literal.
  11373. The following modifiers are allowed:
  11374. @table @code
  11375. @item i
  11376. The modifier ``@code{i}'' cause the matching to ignore case.
  11377. For example the following pattern matches ``@code{a}'' or ``@code{A}''.
  11378. @example
  11379. #/a/i
  11380. @end example
  11381. @item m
  11382. Enables ``metaline'' mode.
  11383. Normally metacharacters ``@code{^}'' and ``@code{$}'
  11384. match at the start end end of the entire input string.
  11385. In metaline mode ``@code{^}'' and ``@code{$}'' also
  11386. match just before or after a line terminator.
  11387. Multiline mode can also be enabled by the metasequence ``@code{(?m)}''.
  11388. @item s
  11389. Enable ``singleline'' (aka ``dot-all'') mode.
  11390. In this mode the matacharacter ``@code{.} matches any character,
  11391. including a line breaks.
  11392. This mode be enabled by the metasequence ``@code{(?s)}''.
  11393. @end table
  11394. The following functions accept a regex either as
  11395. a pattern string or a compiled @code{regex} pattern.
  11396. I.e. the following are all equivalent:
  11397. @example
  11398. (regex-match "b\\.c" "ab.cd")
  11399. (regex-match #/b\.c/ "ab.cd")
  11400. (regex-match (regex "b\\.c") "ab.cd")
  11401. (regex-match (java.util.regex.Pattern:compile "b\\.c") "ab.cd")
  11402. @end example
  11403. These all evaluate to the list @code{("b.c")}.
  11404. The following functions must be imported by doing one of:
  11405. @example
  11406. (require 'regex) ;; or
  11407. (import (kawa regex))
  11408. @end example
  11409. @deffn Procedure regex-match-positions regex string [start [end]]
  11410. The procedure @code{regex‑match‑position} takes pattern and a
  11411. text @var{string}, and returns a match if the regex matches (some part of)
  11412. the text string.
  11413. Returns @code{#f} if the regexp did not match the string;
  11414. and a list of index pairs if it did match.
  11415. @example
  11416. (regex-match-positions "brain" "bird") @result{} #f
  11417. (regex-match-positions "needle" "hay needle stack")
  11418. @result{} ((4 . 10))
  11419. @end example
  11420. In the second example, the integers 4 and 10 identify the substring
  11421. that was matched. 4 is the starting (inclusive) index and 10 the
  11422. ending (exclusive) index of the matching substring.
  11423. @example
  11424. (substring "hay needle stack" 4 10) @result{} "needle"
  11425. @end example
  11426. In this case the return list contains only one index
  11427. pair, and that pair represents the entire substring matched by the
  11428. regexp. When we discuss subpatterns later, we will see how a single
  11429. match operation can yield a list of submatches.
  11430. @code{regex‑match‑positions} takes optional third and fourth arguments
  11431. that specify the indices of the text string within which the matching
  11432. should take place.
  11433. @example
  11434. (regex-match-positions "needle"
  11435. "his hay needle stack -- my hay needle stack -- her hay needle stack"
  11436. 24 43)
  11437. @result{} ((31 . 37))
  11438. @end example
  11439. Note that the returned indices are still reckoned relative to the full text string.
  11440. @end deffn
  11441. @deffn Procedure regex-match regex string [start [end]]
  11442. The procedure @code{regex‑match} is called like @code{regex‑match‑positions}
  11443. but instead of returning index pairs it returns the matching substrings:
  11444. @example
  11445. (regex-match "brain" "bird") @result{} #f
  11446. (regex-match "needle" "hay needle stack")
  11447. @result{} ("needle")
  11448. @end example
  11449. @code{regex‑match} also takes optional third and fourth arguments,
  11450. with the same meaning as does @code{regex‑match‑positions}.
  11451. @end deffn
  11452. @deffn Procedure regex-split regex string
  11453. Takes two arguments, a @var{regex} pattern and a text @var{string},
  11454. and returns a list of substrings of the text string,
  11455. where the pattern identifies the delimiter separating the substrings.
  11456. @example
  11457. (regex-split ":" "/bin:/usr/bin:/usr/bin/X11:/usr/local/bin")
  11458. @result{} ("/bin" "/usr/bin" "/usr/bin/X11" "/usr/local/bin")
  11459. (regex-split " " "pea soup")
  11460. @result{} ("pea" "soup")
  11461. @end example
  11462. If the first argument can match an empty string, then the list of all
  11463. the single-character substrings is returned, plus we get
  11464. a empty strings at each end.
  11465. @example
  11466. (regex-split "" "smithereens")
  11467. @result{} ("" "s" "m" "i" "t" "h" "e" "r" "e" "e" "n" "s" "")
  11468. @end example
  11469. (Note: This behavior is different from @code{pregexp-split}.)
  11470. To identify one-or-more spaces as the delimiter, take care to use the regexp
  11471. ``@code{ +}'', not ``@code{ *}''.
  11472. @example
  11473. (regex-split " +" "split pea soup")
  11474. @result{} ("split" "pea" "soup")
  11475. (regex-split " *" "split pea soup")
  11476. @result{} ("" "s" "p" "l" "i" "t" "" "p" "e" "a" "" "s" "o" "u" "p" "")
  11477. @end example
  11478. @end deffn
  11479. @deffn Procedure regex‑replace regex string replacement
  11480. Replaces the matched portion of the text @var{string} by another a
  11481. @var{replacdement} string.
  11482. @example
  11483. (regex-replace "te" "liberte" "ty")
  11484. @result{} "liberty"
  11485. @end example
  11486. Submatches can be used in the replacement string argument.
  11487. The replacement string can use ``@code{$@var{n}}''
  11488. as a @dfn{backreference} to refer back to the @var{n}th
  11489. submatch, ie, the substring that matched the @var{n}th
  11490. subpattern. ``@code{$0}'' refers to the entire match.
  11491. @example
  11492. (regex-replace #/_(.+?)_/
  11493. "the _nina_, the _pinta_, and the _santa maria_"
  11494. "*$1*"))
  11495. @result{} "the *nina*, the _pinta_, and the _santa maria_"
  11496. @end example
  11497. @end deffn
  11498. @deffn Procedure regex‑replace* regex string replacement
  11499. Replaces all matches in the text @var{string} by the @var{replacement} string:
  11500. @example
  11501. (regex-replace* "te" "liberte egalite fraternite" "ty")
  11502. @result{} "liberty egality fratyrnity"
  11503. (regex-replace* #/_(.+?)_/
  11504. "the _nina_, the _pinta_, and the _santa maria_"
  11505. "*$1*")
  11506. @result{} "the *nina*, the *pinta*, and the *santa maria*"
  11507. @end example
  11508. @end deffn
  11509. @deffn Procedure regex-quote pattern
  11510. Takes an arbitrary string and returns a pattern string that precisely
  11511. matches it. In particular, characters in the input string that could
  11512. serve as regex metacharacters are escaped as needed.
  11513. @example
  11514. (regex-quote "cons")
  11515. @result{} "\Qcons\E"
  11516. @end example
  11517. @code{regex‑quote} is useful when building a composite regex
  11518. from a mix of regex strings and verbatim strings.
  11519. @end deffn
  11520. @subsection Portable Scheme regular expressions
  11521. This provides the procedures @code{pregexp}, @code{pregexp‑match‑positions},
  11522. @code{pregexp‑match}, @code{pregexp‑split}, @code{pregexp‑replace},
  11523. @code{pregexp‑replace*}, and @code{pregexp‑quote}.
  11524. Before using them, you must require them:
  11525. @example
  11526. (require 'pregexp)
  11527. @end example
  11528. These procedures have the same interface as the corresponding
  11529. @code{regex-} versions, but take slightly different pattern syntax.
  11530. The replace commands use ``@code{\}'' instead of ``@code{$}''
  11531. to indicate substitutions.
  11532. Also, @code{pregexp‑split} behaves differently from
  11533. @code{regex‑split} if the pattern can match an empty string.
  11534. See @uref{http://www.ccs.neu.edu/home/dorai/pregexp/index.html,here for details}.
  11535. @node Data structures
  11536. @chapter Data structures
  11537. @menu
  11538. * Sequences::
  11539. * Lists::
  11540. * Vectors::
  11541. * Uniform vectors::
  11542. * Bytevectors::
  11543. * Ranges::
  11544. * Streams:: Lazy lists.
  11545. * Arrays:: Multi-dimensional Arrays
  11546. * Hash tables::
  11547. @end menu
  11548. @node Sequences
  11549. @section Sequences
  11550. A @dfn{sequence} is a generalized list, consisting of zero or more values.
  11551. You can choose between a number of different kinds of sequence implementations.
  11552. Scheme traditionally has @ref{Lists,lists} and @ref{Vectors,vectors}.
  11553. Any Java class that implements @code{java.util.List} is a sequence type.
  11554. Raw Java arrays can also be viewerd as a sequence,
  11555. and strings can be viewed a sequence (or vector) of characters.
  11556. Kawa also provides @ref{Uniform vectors,uniform vectors}.
  11557. Sequence types differ in their API, but given a sequence type @var{stype}
  11558. you can construct instances of that type using the syntax:
  11559. @example
  11560. (@var{stype} @var{v0} @var{v1} .... @var{vn})
  11561. @end example
  11562. For example:
  11563. @example
  11564. (bytevector 9 8 7 6) @result{} #u8(9 8 7 6)
  11565. @end example
  11566. For a raw Java class name @var{jname} you may need to use
  11567. the empty keyword @code{||:} to separate constructor parameters (if any)
  11568. from sequence elements, as in:
  11569. @example
  11570. (gnu.lists.U8Vector ||: 9 8 7 6) @result{} #u8(9 8 7 6)
  11571. @end example
  11572. This syntax works with any type with a default constructor
  11573. and a 1-argument @code{add} method;
  11574. see @ref{Allocating objects} for details.
  11575. You can use the same syntax for allocating arrays,
  11576. though array creation supports @ref{Creating-new-Java-arrays,more options}.
  11577. To extract an element from Scheme sequence of type @var{stype}
  11578. there is usually a function @code{@var{stype}-ref}. For example:
  11579. @example
  11580. (define vec1 (vector 5 6 7 8))
  11581. (vector-ref vec1 2) @result{} 7
  11582. @end example
  11583. More concisely, you can use (Kawa-specific) function call syntax:
  11584. @example
  11585. (vec1 3) @result{} 8
  11586. @end example
  11587. The index can be another sequence, which creates a new sequence
  11588. of the selected indexes:
  11589. @example
  11590. (vec1 [3 0 2 1]) @result{} #(8 5 7 6)
  11591. @end example
  11592. It is convenient to use a @ref{Ranges,@dfn{range}} to select
  11593. a sub-sequence:
  11594. @example
  11595. (vec1 [1 <=: 3]) @result{} #(6 7 8)
  11596. (vec1 [2 <:]) @result{} #(7 8)
  11597. @end example
  11598. The same function call syntax also works for raw Java arrays
  11599. (though the index is restricted to an integer, not a sequence or array):
  11600. @example
  11601. (define arr1 (long[] 4 5 6 7))
  11602. (arr1 3) @result{} 7
  11603. @end example
  11604. To assign to (replace) an element from a sequence of Scheme type @var{stype}
  11605. there is usually a function @code{@var{stype}-set!}:
  11606. @example
  11607. (vector-set! vec1 1 9)
  11608. vec1 @result{} #(5 9 7 8)
  11609. @end example
  11610. Again, you can use the function call syntax:
  11611. @example
  11612. (set! (vec1 2) 'x)
  11613. vec1 @result{} #(5 9 x 8)
  11614. @end example
  11615. @deffn Procedure length seq
  11616. Returns the number of elements of the @var{seq}.
  11617. @example
  11618. (length '(a b c)) @result{} 3
  11619. (length '(a (b) (c d e))) @result{} 3
  11620. (length '()) @result{} 0
  11621. (length [3 4 [] 12]) @result{} 4
  11622. (length (vector)) @result{} 0
  11623. (length (int[] 7 6)) @result{} 2
  11624. @end example
  11625. The length of a string is the number of characters (Unicode code points).
  11626. In contrast, the @code{length} @emph{method} (of the @code{CharSequence} interface)
  11627. returns the number of 16-bit code points:
  11628. @example
  11629. (length "Hello") @result{} 5
  11630. (define str1 "Hello \x1f603;!")
  11631. (invoke str1 'length) @result{} 9
  11632. (length str1) @result{} 8 ; Used to return 9 in Kawa 2.x.
  11633. (string-length str1) @result{} 8
  11634. @end example
  11635. @end deffn
  11636. @node Lists
  11637. @section Lists
  11638. A pair (sometimes called a @dfn{dotted pair}) is a record structure
  11639. with two fields called the car and cdr fields (for historical
  11640. reasons). Pairs are created by the procedure @code{cons}. The
  11641. car and cdr fields are accessed by the procedures @code{car} and
  11642. @code{cdr}. The car and cdr fields are assigned by the procedures
  11643. @code{set-car!} and @code{set-cdr!}.
  11644. Pairs are used primarily to represent lists. A @dfn{list} can be
  11645. defined recursively as either the empty list or a pair whose
  11646. cdr is a list. More precisely, the set of lists is defined as
  11647. the smallest set @var{X} such that:
  11648. @itemize
  11649. @item
  11650. The empty list is in @var{X}.
  11651. @item
  11652. If @var{list} is in @var{X}, then any pair whose cdr field contains
  11653. @var{list} is also in @var{X}.
  11654. @end itemize
  11655. The objects in the car fields of successive pairs of a list are
  11656. the elements of the list. For example, a two-element list
  11657. is a pair whose car is the first element and whose cdr is a
  11658. pair whose car is the second element and whose cdr is the
  11659. empty list. The length of a list is the number of elements,
  11660. which is the same as the number of pairs.
  11661. The empty list is a special object of its own type. It is not
  11662. a pair, it has no elements, and its length is zero.
  11663. @emph{Note:} The above definitions imply that all lists have finite
  11664. length and are terminated by the empty list.
  11665. The most general notation (external representation) for
  11666. Scheme pairs is the “dotted” notation @code{(@var{c1} . @var{c2} )}
  11667. where @var{c1} is the value of the car field and
  11668. @var{c2} is the value of the cdr field.
  11669. For example @code{(4 . 5)} is a pair whose car is 4 and
  11670. whose cdr is 5. Note that @code{(4 . 5)} is the external representation
  11671. of a pair, not an expression that evaluates to a pair.
  11672. A more streamlined notation can be used for lists: the
  11673. elements of the list are simply enclosed in parentheses and
  11674. separated by spaces. The empty list is written @code{()}.
  11675. For example,
  11676. @example
  11677. (a b c d e)
  11678. @end example
  11679. and
  11680. @example
  11681. (a . (b . (c . (d . (e . ())))))
  11682. @end example
  11683. are equivalent notations for a list of symbols.
  11684. A chain of pairs not ending in the empty list is called an
  11685. @dfn{improper list}. Note that an improper list is not a list.
  11686. The list and dotted notations can be combined to represent
  11687. improper lists:
  11688. @example
  11689. (a b c . d)
  11690. @end example
  11691. is equivalent to
  11692. @example
  11693. (a . (b . (c . d)))
  11694. @end example
  11695. @emph{Needs to finish merging from R7RS!}
  11696. @deffn Procedure make-list k [fill]
  11697. Returns a newly allocated list of @var{k} elements. If a second argument
  11698. is given, the each element is initialized to @var{fill}.
  11699. Otherwise the initial contents of each element is unspecified.
  11700. @example
  11701. (make-list 2 3) @result{} (3 3)
  11702. @end example
  11703. @end deffn
  11704. @anchor{SRFI-1}
  11705. @subsection SRFI-1 list library
  11706. The @uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI-1 List Library}
  11707. is available, though not enabled by default. To use its functions you
  11708. must @code{(require 'list-lib)} or @code{(require 'srfi-1)}.
  11709. @example
  11710. (require 'list-lib)
  11711. (iota 5 0 -0.5) @result{} (0.0 -0.5 -1.0 -1.5 -2.0)
  11712. @end example
  11713. @deffn Procedure reverse! list
  11714. The result is a list consisting of the elements of @var{list} in reverse order.
  11715. No new pairs are allocated, instead the pairs of @var{list} are re-used,
  11716. with @code{cdr} cells of @var{list} reversed in place. Note that if @var{list}
  11717. was pair, it becomes the last pair of the reversed result.
  11718. @end deffn
  11719. @anchor{SRFI-101}
  11720. @subsection SRFI-101 Purely Functional Random-Access Pairs and Lists
  11721. @uref{http://srfi.schemers.org/srfi-101/srfi-101.html, SRFI-101}
  11722. specifies immutable (read-only) lists with fast (logarithmic) indexing
  11723. and functional
  11724. update (i.e. return a modified list).
  11725. These are implemented by a @code{RAPair} class
  11726. which extends the generic @code{pair} type, which means that most
  11727. code that expects a standard list will work on these lists as well.
  11728. @node Vectors
  11729. @section Vectors
  11730. Vectors are heterogeneous structures whose elements are indexed by
  11731. integers. A vector typically occupies less space than a list of the
  11732. same length, and the average time needed to access a randomly chosen
  11733. element is typically less for the vector than for the list.
  11734. The @emph{length} of a vector is the number of elements that it
  11735. contains. This number is a non--negative integer that is fixed when the
  11736. vector is created. The @emph{valid indices} of a vector are the exact
  11737. non--negative integer objects less than the length of the vector. The
  11738. first element in a vector is indexed by zero, and the last element is
  11739. indexed by one less than the length of the vector.
  11740. Vectors are written using the notation @code{#(@var{obj} ...)}.
  11741. For example, a vector of length 3 3 containing the number zero
  11742. in element 0, the list @code{(2 2 2 2)} in element 1, and the
  11743. string @code{"Anna"} in element 2 can be written as following:
  11744. @example
  11745. #(0 (2 2 2 2) "Anna")
  11746. @end example
  11747. Note that this is the external representation of a vector.
  11748. In Kawa, a vector datum is self-evaluating,
  11749. but for style (and compatibility with R7RS) is is suggested
  11750. you quote a vector constant:
  11751. @example
  11752. ’#(0 (2 2 2 2) "Anna") @result{} #(0 (2 2 2 2) "Anna")
  11753. @end example
  11754. Compare these different ways of creating a vector:
  11755. @table @code
  11756. @item (vector a b c)
  11757. In this case @code{a}, @code{b}, and @code{c} are expressions evaluated at
  11758. run-time and the results used to initialize a newly-allocated 3-element vector.
  11759. @item [a b c]
  11760. Same as using vector, but more concise, and results in an immutable
  11761. (non-modifiable) vector.
  11762. @item #(a b c)
  11763. This is reader syntax and creates a vector literal,
  11764. at read-time, early in compile-time.
  11765. The symbols @code{a}, @code{b}, and @code{c} are not evaluated
  11766. but instead used literally.
  11767. @item `#(,a ,b ,c)
  11768. This is reader-syntax, using quasi-quotation,
  11769. so @code{a}, @code{b}, and @code{c} are expressions evaluated at run-time.
  11770. This is equivalent to @code{[a b c]} in that it results in an immutable vector.
  11771. @end table
  11772. @deffn Type vector
  11773. The type of vector objects.
  11774. @end deffn
  11775. @deffn Constructor vector @var{obj} @dots{}
  11776. Return a newly allocated vector whose elements contain the given
  11777. arguments. Analogous to @code{list}.
  11778. @example
  11779. (vector 'a 'b 'c) @result{} #(a b c)
  11780. @end example
  11781. Alternatively, you can use square-bracket syntax,
  11782. which results in an immutable vector:
  11783. @example
  11784. ['a 'b 'c] @result{} #(a b c)
  11785. @end example
  11786. @end deffn
  11787. @deffn Procedure make-vector @var{k}
  11788. @deffnx Procedure make-vector @var{k} @var{fill}
  11789. Return a newly allocated vector of @var{k} elements. If a second
  11790. argument is given, then each element is initialized to @var{fill}.
  11791. Otherwise the initial contents of each element is @code{#!null}.
  11792. @end deffn
  11793. @deffn Procedure vector? @var{obj}
  11794. Return @true{} if @var{obj} is a vector, @false{} otherwise.
  11795. @end deffn
  11796. @deffn Procedure vector-length @var{vector}
  11797. Return the number of elements in @var{vector} as an exact integer.
  11798. @end deffn
  11799. @deffn Procedure vector-ref @var{vector} @var{k}
  11800. It is an error if @var{k} is not a valid index of @var{vector}.
  11801. The @func{vector-ref}
  11802. procedure returns the contents of element @var{k} of @var{vector}.
  11803. @example
  11804. (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
  11805. (vector-ref '#(1 1 2 3 5 8 13 21)
  11806. (inexact->exact (round (* 2 (acos -1)))))
  11807. @result{} 13
  11808. @end example
  11809. @end deffn
  11810. @deffn Procedure vector-set! @var{vector} @var{k} @var{obj}
  11811. It is an error if @var{k} is not a valid index of @var{vector}.
  11812. The @func{vector-set!}
  11813. procedure stores @var{obj} in element @var{k} of @var{vector}, and
  11814. returns no values.
  11815. @example
  11816. (let ((vec (vector 0 '(2 2 2 2) "Anna")))
  11817. (vector-set! vec 1 '("Sue" "Sue"))
  11818. vec)
  11819. @result{} #(0 ("Sue" "Sue") "Anna")
  11820. (vector-set! '#(0 1 2) 1 "doe")
  11821. @result{} @i{error} ;; constant vector
  11822. @end example
  11823. @end deffn
  11824. A concise alternative to @code{vector-ref} and @code{vector-set!}
  11825. is to use function call syntax. For example:
  11826. @example
  11827. (let ((vec (vector 0 '(2 2 2 2) "Anna")))
  11828. (set! (vec 1) '("Sue" "Sue"))
  11829. (list (vec 2) (vec 1)))
  11830. @result{} ("Anna" ("Sue" "Sue"))
  11831. @end example
  11832. @deffn Procedure vector->list @var{vector} [@var{start} [@var{end}]]
  11833. The @func{vector->list} procedure returns a newly allocated list of the
  11834. objects contained in the elements of @var{vector}
  11835. between @var{start} and @var{end}.
  11836. @example
  11837. (vector->list '#(dah dah didah)) @result{} (dah dah didah)
  11838. (vector->list '#(dah dah didah) 1 2) @result{} (dah)
  11839. @end example
  11840. @end deffn
  11841. @deffn Procedure list->vector @var{list}
  11842. The @func{list->vector} procedure returns a newly created vector
  11843. initialized to the elements of the list @var{list}, in order.
  11844. @example
  11845. (list->vector '(dididit dah)) @result{} #(dididit dah)
  11846. @end example
  11847. @end deffn
  11848. @deffn Procedure vector-copy vector [start [end]]
  11849. Returns a newly allocated copy of the elements of the given
  11850. @var{vector} between @var{start} and @var{end} . The elements of the new
  11851. vector are the same (in the sense of @code{eqv?}) as the elements
  11852. of the old.
  11853. @example
  11854. (define a #(1 8 2 8)) ; a may be immutable
  11855. (define b (vector-copy a))
  11856. (vector-set! b 0 3) ; b is mutable
  11857. b @result{} #(3 8 2 8)
  11858. (define c (vector-copy b 1 3))
  11859. c @result{} #(8 2)
  11860. @end example
  11861. @end deffn
  11862. @deffn Procedure vector-copy! to at from [start [end]]
  11863. Copies the elements of vector from between start and end
  11864. to vector to, starting at at. The order in which elements
  11865. are copied is unspecified, except that if the source and
  11866. destination overlap, copying takes place as if the source is first
  11867. copied into a temporary vector and then into the destination.
  11868. This can be achieved without allocating storage by making
  11869. sure to copy in the correct direction in such circumstances.
  11870. It is an error if @var{at} is less than zero or greater than the length
  11871. of @var{to}.
  11872. It is also an error if @code{(- (vector-length @var{to}) @var{at})} is less
  11873. than @code{(- @var{end} @var{start})}.
  11874. @example
  11875. (define a (vector 1 2 3 4 5))
  11876. (define b (vector 10 20 30 40 50))
  11877. (vector-copy! b 1 a 0 2)
  11878. b @result{} #(10 1 2 40 50)
  11879. @end example
  11880. @end deffn
  11881. @deffn Procedure vector-append @var{arg}...
  11882. Creates a newly allocated vector whose elements are the
  11883. concatenation of the elements of the given arguments.
  11884. Each @var{arg} may be a vector or a list.
  11885. @example
  11886. (vector-append #(a b c) #(d e f))
  11887. @result{} #(a b c d e f)
  11888. @end example
  11889. @end deffn
  11890. @deffn Procedure {vector-fill!} @var{vector fill} [@var{start} [@var{end}]]
  11891. Stores @var{fill} in in the elements of @var{vector}
  11892. between @var{start} and @var{end}.
  11893. @example
  11894. (define a (vector 1 2 3 4 5))
  11895. (vector-fill! a 'smash 2 4)
  11896. a @result{} #(1 2 smash smash 5)
  11897. @end example
  11898. @end deffn
  11899. The procedures @code{vector-map} and @code{vector-for-each}
  11900. are documented in @ref{Mapping functions}.
  11901. @node Uniform vectors
  11902. @section Uniform vectors
  11903. Uniform vectors are vectors whose elements are of the same numeric type.
  11904. The are defined by @uref{http://srfi.schemers.org/srfi-4/srfi-4.html,SRFI-4}.
  11905. The type names (such as @code{s8vector}) are a Kawa extension.
  11906. @display
  11907. @stxdef{uniform-vector} @stxlit{#} @stxref{uniform-tag} @stxref{list}
  11908. @stxdef{uniform-tag} @stxlit{f32} | @stxlit{f64}
  11909. | @stxlit{s8} | @stxlit{s16} | @stxlit{s32} | @stxlit{s64}
  11910. | @stxlit{u8} | @stxlit{u16} | @stxlit{u32} | @stxlit{u64}
  11911. @end display
  11912. This example is a literal for a 5-element vector of unsigned short (@code{ushort}) values:
  11913. @example
  11914. (define uvec1 #u16(64000 3200 160 8 0))
  11915. @end example
  11916. Since a uniform vector is a sequence, you can use function-call
  11917. notation to index one. For example:
  11918. @example
  11919. (uvec1 1) @result{} 3200
  11920. @end example
  11921. In this case the result is a primitive unsigned short (@code{ushort}),
  11922. which is converted to a @code{gnu.math.UShort} if an object is needed.
  11923. @deffn Type s8vector
  11924. The type of uniform vectors where each element can contain
  11925. a signed 8-bit integer. Represented using an array of @code{byte}.
  11926. @end deffn
  11927. @deffn Type u8vector
  11928. The type of uniform vectors where each element can contain
  11929. an unsigned 8-bit integer. Represented using an array of @code{<byte>},
  11930. but each element is treated as if unsigned.
  11931. This type is a synonym for @code{bytevector},
  11932. which has @ref{Bytevectors, extra functions}.
  11933. @end deffn
  11934. @deffn Type s16vector
  11935. The type of uniform vectors where each element can contain
  11936. a signed 16-bit integer. Represented using an array of @code{short}.
  11937. @end deffn
  11938. @deffn Type u16vector
  11939. The type of uniform vectors where each element can contain
  11940. an unsigned 16-bit integer. Represented using an array of @code{short},
  11941. but each element is treated as if unsigned.
  11942. @end deffn
  11943. @deffn Type s32vector
  11944. The type of uniform vectors where each element can contain
  11945. a signed 32-bit integer. Represented using an array of @code{int}.
  11946. @end deffn
  11947. @deffn Type u32vector
  11948. The type of uniform vectors where each element can contain
  11949. an unsigned 32-bit integer. Represented using an array of @code{int},
  11950. but each element is treated as if unsigned.
  11951. @end deffn
  11952. @deffn Type s64vector
  11953. The type of uniform vectors where each element can contain
  11954. a signed 64-bit integer. Represented using an array of @code{long}.
  11955. @end deffn
  11956. @deffn Type u64vector
  11957. The type of uniform vectors where each element can contain
  11958. an unsigned 64-bit integer. Represented using an array of @code{long},
  11959. but each element is treated as if unsigned.
  11960. @end deffn
  11961. @deffn Type f32vector
  11962. The type of uniform vectors where each element can contain
  11963. a 32-bit floating-point real. Represented using an array of @code{float}.
  11964. @end deffn
  11965. @deffn Type f64vector
  11966. The type of uniform vectors where each element can contain
  11967. a 64-bit floating-point real. Represented using an array of @code{double}.
  11968. @end deffn
  11969. @deffn Procedure s8vector? value
  11970. @deffnx Procedure u8vector? value
  11971. @deffnx Procedure s16vector? value
  11972. @deffnx Procedure u16vector? value
  11973. @deffnx Procedure s32vector? value
  11974. @deffnx Procedure u32vector? value
  11975. @deffnx Procedure s64vector? value
  11976. @deffnx Procedure u64vector? value
  11977. @deffnx Procedure f32vector? value
  11978. @deffnx Procedure f64vector? value
  11979. Return true iff @var{value} is a uniform vector of the specified type.
  11980. @end deffn
  11981. @deffn Procedure make-s8vector n [value]
  11982. @deffnx Procedure make-u8vector n [value]
  11983. @deffnx Procedure make-s16vector n [value]
  11984. @deffnx Procedure make-u16vector n [value]
  11985. @deffnx Procedure make-s32vector n [value]
  11986. @deffnx Procedure make-u32vector n [value]
  11987. @deffnx Procedure make-s64vector n [value]
  11988. @deffnx Procedure make-u64vector n [value]
  11989. @deffnx Procedure make-f32vector n [value]
  11990. @deffnx Procedure make-f64vector n [value]
  11991. Create a new uniform vector of the specified type,
  11992. having room for @var{n} elements.
  11993. Initialize each element to @var{value} if it is specified; zero otherwise.
  11994. @end deffn
  11995. @deffn Constructor s8vector value ...
  11996. @deffnx Constructor u8vector value ...
  11997. @deffnx Constructor s16vector value ..
  11998. @deffnx Constructor u16vector value ...
  11999. @deffnx Constructor s32vector value ...
  12000. @deffnx Constructor u32vector value ...
  12001. @deffnx Constructor s64vector value ...
  12002. @deffnx Constructor u64vector value ...
  12003. @deffnx Constructor f32vector value ...
  12004. @deffnx Constructor f64vector value ...
  12005. Create a new uniform vector of the specified type,
  12006. whose length is the number of @var{value}s specified,
  12007. and initialize it using those @var{value}s.
  12008. @end deffn
  12009. @deffn Procedure s8vector-length v
  12010. @deffnx Procedure u8vector-length v
  12011. @deffnx Procedure s16vector-length v
  12012. @deffnx Procedure u16vector-length v
  12013. @deffnx Procedure s32vector-length v
  12014. @deffnx Procedure u32vector-length v
  12015. @deffnx Procedure s64vector-length v
  12016. @deffnx Procedure u64vector-length v
  12017. @deffnx Procedure f32vector-length v
  12018. @deffnx Procedure f64vector-length v
  12019. Return the length (in number of elements) of the uniform vector @var{v}.
  12020. @end deffn
  12021. @deffn Procedure s8vector-ref v i
  12022. @deffnx Procedure u8vector-ref v i
  12023. @deffnx Procedure s16vector-ref v i
  12024. @deffnx Procedure u16vector-ref v i
  12025. @deffnx Procedure s32vector-ref v i
  12026. @deffnx Procedure u32vector-ref v i
  12027. @deffnx Procedure s64vector-ref v i
  12028. @deffnx Procedure u64vector-ref v i
  12029. @deffnx Procedure f32vector-ref v i
  12030. @deffnx Procedure f64vector-ref v i
  12031. Return the element at index @var{i} of the uniform vector @var{v}.
  12032. @end deffn
  12033. @deffn Procedure s8vector-set! v i x
  12034. @deffnx Procedure u8vector-set! v i x
  12035. @deffnx Procedure s16vector-set! v i x
  12036. @deffnx Procedure u16vector-set! v i x
  12037. @deffnx Procedure s32vector-set! v i x
  12038. @deffnx Procedure u32vector-set! v i x
  12039. @deffnx Procedure s64vector-set! v i x
  12040. @deffnx Procedure u64vector-set! v i x
  12041. @deffnx Procedure f32vector-set! v i x
  12042. @deffnx Procedure f64vector-set! v i x
  12043. Set the element at index @var{i} of uniform vector @var{v}
  12044. to the value @var{x}, which must be a number coercible
  12045. to the appropriate type.
  12046. @end deffn
  12047. @deffn Procedure s8vector->list v
  12048. @deffnx Procedure u8vector->list v
  12049. @deffnx Procedure s16vector->list v
  12050. @deffnx Procedure u16vector->list v
  12051. @deffnx Procedure s32vector->list v
  12052. @deffnx Procedure u32vector->list v
  12053. @deffnx Procedure s64vector->list v
  12054. @deffnx Procedure u64vector->list v
  12055. @deffnx Procedure f32vector->list v
  12056. @deffnx Procedure f64vector->list v
  12057. Convert the uniform vetor @var{v} to a list containing the elments of @var{v}.
  12058. @end deffn
  12059. @deffn Procedure list->s8vector l
  12060. @deffnx Procedure list->u8vector l
  12061. @deffnx Procedure list->s16vector l
  12062. @deffnx Procedure list->u16vector l
  12063. @deffnx Procedure list->s32vector l
  12064. @deffnx Procedure list->u32vector l
  12065. @deffnx Procedure list->s64vector l
  12066. @deffnx Procedure list->u64vector l
  12067. @deffnx Procedure list->f32vector l
  12068. @deffnx Procedure list->f64vector l
  12069. Create a uniform vector of the appropriate type, initializing it
  12070. with the elements of the list @var{l}. The elements of @var{l}
  12071. must be numbers coercible the new vector's element type.
  12072. @end deffn
  12073. @subsection Relationship with Java arrays
  12074. Each uniform array type is implemented as an @dfn{underlying Java array},
  12075. and a length field.
  12076. The underlying type is
  12077. @code{byte[]} for @code{u8vector} or @code{s8vector};
  12078. @code{short[]} for @code{u16vector} or @code{u16vector};
  12079. @code{int[]} for @code{u32vector} or @code{s32vector};
  12080. @code{long[]} for @code{u64vector} or @code{s64vector};
  12081. @code{float[]} for @code{f32vector}; and
  12082. @code{double[]} for @code{f32vector}.
  12083. The length field allows a uniform array to only use the
  12084. initial part of the underlying array. (This can be used
  12085. to support Common Lisp's fill pointer feature.)
  12086. This also allows resizing a uniform vector. There is no
  12087. Scheme function for this, but you can use the @code{setSize} method:
  12088. @example
  12089. (invoke some-vector 'setSize 200)
  12090. @end example
  12091. If you have a Java array, you can create a uniform vector
  12092. sharing with the Java array:
  12093. @example
  12094. (define arr :: byte[] ((primitive-array-new byte) 10))
  12095. (define vec :: u8vector (make u8vector arr))
  12096. @end example
  12097. At this point @code{vec} uses @code{arr} for its underlying storage,
  12098. so changes to one affect the other.
  12099. It @code{vec} is re-sized so it needs a larger underlying array,
  12100. then it will no longer use @code{arr}.
  12101. @node Bytevectors
  12102. @section Bytevectors
  12103. @dfn{Bytevectors} represent blocks of binary data. They are
  12104. fixed-length sequences of bytes, where a @var{byte} is an exact
  12105. integer in the range [0, 255]. A bytevector is typically more
  12106. space-efficient than a vector containing the same values.
  12107. The length of a bytevector is the number of elements that
  12108. it contains. This number is a non-negative integer that is
  12109. fixed when the bytevector is created. The valid indexes of
  12110. a bytevector are the exact non-negative integers less than
  12111. the length of the bytevector, starting at index zero as with
  12112. vectors.
  12113. The @code{bytevector} type is equivalent to the @code{u8vector}
  12114. @ref{Uniform vectors,uniform vector} type, but is specified
  12115. by the R7RS standard.
  12116. Bytevectors are written using the notation @code{#u8(byte . . . )}.
  12117. For example, a bytevector of length 3 containing the byte
  12118. 0 in element 0, the byte 10 in element 1, and the byte 5 in
  12119. element 2 can be written as following:
  12120. @example
  12121. #u8(0 10 5)
  12122. @end example
  12123. Bytevector constants are self-evaluating, so they do not
  12124. need to be quoted in programs.
  12125. @deffn Type bytevector
  12126. The type of bytevector objects.
  12127. @end deffn
  12128. @deffn Constructor bytevector @var{byte} @dots{}
  12129. Return a newly allocated bytevector whose elements contain the given
  12130. arguments. Analogous to @code{vector}.
  12131. @example
  12132. (bytevector 1 3 5 1 3 5) @result{} #u8(1 3 5 1 3 5)
  12133. (bytevector) @result{} #u8()
  12134. @end example
  12135. @end deffn
  12136. @deffn Procedure bytevector? @var{obj}
  12137. Return @true{} if @var{obj} is a bytevector, @false{} otherwise.
  12138. @end deffn
  12139. @deffn Procedure make-bytevector k
  12140. @deffnx Procedure make-bytevector k byte
  12141. The @code{make-bytevector} procedure returns a newly allocated
  12142. bytevector of length @var{k}. If @var{byte} is given, then all elements
  12143. of the bytevector are initialized to @var{byte},
  12144. otherwise the contents of each element are unspecified.
  12145. @example
  12146. (make-bytevector 2 12) @result{} #u8(12 12)
  12147. @end example
  12148. @end deffn
  12149. @deffn Procedure bytevector-length bytevector
  12150. Returns the length of @var{bytevector} in bytes
  12151. as an exact integer.
  12152. @end deffn
  12153. @deffn Procedure bytevector-u8-ref bytevector k
  12154. It is an error if @var{k} is not a valid index of @var{bytevector}.
  12155. Returns the @var{k}th byte of @var{bytevector}.
  12156. @example
  12157. (bytevector-u8-ref ’#u8(1 1 2 3 5 8 13 21) 5)
  12158. @result{} 8
  12159. @end example
  12160. @end deffn
  12161. @deffn Procedure bytevector-u8-set! bytevector k byte
  12162. It is an error if @var{k} is not a valid index of @var{bytevector}.
  12163. Stores @var{byte} as the @var{k}th byte of @var{bytevector}.
  12164. @example
  12165. (let ((bv (bytevector 1 2 3 4)
  12166. (bytevector-u8-set! bv 1 3)
  12167. bv)
  12168. @result{} #u8(1 3 3 4)
  12169. @end example
  12170. @end deffn
  12171. @deffn Procedure bytevector-copy bytevector [start [end]]
  12172. Returns a newly allocated bytevector containing the bytes
  12173. in @var{bytevector} between @var{start} and @var{end}.
  12174. @example
  12175. (define a #u8(1 2 3 4 5))
  12176. (bytevector-copy a 2 4))
  12177. @result{} #u8(3 4)
  12178. @end example
  12179. @end deffn
  12180. @deffn Procedure bytevector-copy! to at from [start [end]]
  12181. Copies the bytes of bytevector@var{from} between @var{start} and @var{end}
  12182. to bytevector @var{to}, starting at @var{at}. The order in which bytes
  12183. are copied is unspecified, except that if the source and destination overlap,
  12184. copying takes place as if the source is first
  12185. copied into a temporary bytevector and then into the destination.
  12186. This is achieved without allocating storage
  12187. by making sure to copy in the correct direction in such
  12188. circumstances.
  12189. It is an error if @var{at} is less than zero or greater than the length
  12190. of @var{to}.
  12191. It is also an error if @code{(- (bytevector-length @var{to}) @var{at})}
  12192. is less than @code{(- @var{end} @var{start})}.
  12193. @example
  12194. (define a (bytevector 1 2 3 4 5))
  12195. (define b (bytevector 10 20 30 40 50))
  12196. (bytevector-copy! b 1 a 0 2)
  12197. b @result{} #u8(10 1 2 40 50)
  12198. @end example
  12199. @end deffn
  12200. @deffn Procedure bytevector-append bytevector...
  12201. Returns a newly allocated bytevector whose elements are
  12202. the concatenation of the elements in the given bytevectors.
  12203. @example
  12204. (bytevector-append #u8(0 1 2) #u8(3 4 5))
  12205. @result{} #u8(0 1 2 3 4 5)
  12206. @end example
  12207. @end deffn
  12208. @subsection Converting to or from strings
  12209. @deffn Procedure utf8->string bytevector [start [end]]
  12210. This procedure decodes the bytes of a bytevector between @var{start}
  12211. and @var{end}, interpreting as a UTF-8-encoded string,
  12212. and returns the corresponding string.
  12213. It is an error for @var{bytevector} to contain invalid UTF-8 byte sequences.
  12214. @example
  12215. (utf8->string #u8(#x41)) @result{} "A"
  12216. @end example
  12217. @end deffn
  12218. @deffn Procedure utf16->string bytevector [start [end]]
  12219. @deffnx Procedure utf16be->string bytevector [start [end]]
  12220. @deffnx Procedure utf16le->string bytevector [start [end]]
  12221. These procedures interpret their <var>bytevector</var> argument as
  12222. a UTF-16 encoding of a sequence of characters,
  12223. and return an istring containing that sequence.
  12224. The bytevector subrange given to @code{utf16->string}
  12225. may begin with a byte order mark (BOM); if so, that BOM
  12226. determines whether the rest of the subrange is to be
  12227. interpreted as big-endian or little-endian; in either case,
  12228. the BOM will not become a character in the returned string.
  12229. If the subrange does not begin with a BOM, it is decoded using
  12230. the same implementation-dependent endianness used by
  12231. @code{string->utf16}.
  12232. The @code{utf16be->string} and @code{utf16le->string}
  12233. procedures interpret their inputs as big-endian or little-endian,
  12234. respectively. If a BOM is present, it is treated as a normal
  12235. character and will become part of the result.
  12236. It is an error if @code{(- @var{end} @var{start})} is odd,
  12237. or if the bytevector subrange contains invalid UTF-16 byte sequences.
  12238. @end deffn
  12239. @deffn Procedure string->utf8 string [start [end]]
  12240. This procedure encodes the characters of a string between
  12241. @var{start} and @var{end} and returns the corresponding bytevector,
  12242. in UTF-8 encoding.
  12243. @example
  12244. (string->utf8 "λ") @result{} " #u8(#xCE #xBB)
  12245. @end example
  12246. @end deffn
  12247. @deffn Procedure string->utf16 string [start [end]]
  12248. @deffnx Procedure string->utf16be string [start [end]]
  12249. @deffnx Procedure string->utf16le string [start [end]]
  12250. These procedures return a newly allocated (unless empty)
  12251. bytevector containing a UTF-16 encoding of the given substring.
  12252. The bytevectors returned by @code{string->utf16be}
  12253. and @code{string->utf16le}
  12254. do not contain a byte-order mark (BOM);
  12255. @code{string->utf16be}> returns a big-endian encoding,
  12256. while @code{string->utf16le} returns a little-endian encoding.
  12257. The bytevectors returned by @code{string->utf16}
  12258. begin with a BOM that declares an implementation-dependent
  12259. endianness, and the bytevector elements following that BOM
  12260. encode the given substring using that endianness.
  12261. @emph{Rationale:}
  12262. These procedures are consistent with the Unicode standard.
  12263. Unicode suggests UTF-16 should default to big-endian, but
  12264. Microsoft prefers little-endian.
  12265. @end deffn
  12266. @node Ranges
  12267. @section Ranges
  12268. A @dfn{range} is an immutable sequence of values
  12269. that increase ``linearly'' - i.e. by a fixed amount.
  12270. Most commonly it's a sequence of consequtive integers.
  12271. An example of the syntax is @code{[3 <: 7]} which evaluates
  12272. to the sequence @code{[3 4 5 6]}.
  12273. You can specify an explicit increment with a @code{by:} option.
  12274. There are multiple ways to specify when the sequence stops.
  12275. For example @code{[3 by 2 <=: 7]} is the even numbers from
  12276. 3 up to 7 (inclusive, because of the @code{<=}).
  12277. Ranges are very useful for loop indexes, or selecting a sub-sequence.
  12278. If you have a sequence @var{q} and a range @var{r}, and you
  12279. use the syntax @code{(@var{q} @var{r})} to
  12280. ``apply''@var{q} with the argument @var{r},
  12281. is result is to select elements of @var{q} with indexes in @var{r}.
  12282. @example
  12283. ("ABCDEFG" [1 by: 2 <: 7]) @result{} "BDF"
  12284. @end example
  12285. A range can be @dfn{unbounded}, or non-finite, if you leave off
  12286. the end value. For example @code{[3 by: 2]} is the odd integers starting at 3.
  12287. @display
  12288. @stxdef{unbounded-range}
  12289. @stxlit{[} @var{start-expression} @stxlit{by:} @var{step-expression} @stxlit{]}
  12290. | @stxlit{[} @var{start-expression} @stxlit{<:} @stxlit{]}
  12291. @end display
  12292. The expression @code{[@var{start} by: @var{step}]} evaluates to an
  12293. infinite sequence of values, starting with @var{start}, and followed by
  12294. @code{(+ @var{start} @var{step})},
  12295. @code{(+ @var{start} (* 2 @var{step}))}, and so on.
  12296. The syntax @code{[@var{start-expression} <:]}
  12297. is shorthand for @code{[@var{start-expression} by: 1]}.
  12298. @display
  12299. @stxdef{bounded-range} @stxlit{[} @var{start-expression} [@stxlit{by:} @var{step-expression}] @stxref{range-end} @stxlit{]}
  12300. @stxdef{range-end} @stxlit{<:} @var{end-expression}
  12301. | @stxlit{<=:} @var{end-expression}
  12302. | @stxlit{>:} @var{end-expression}
  12303. | @stxlit{>=:} @var{end-expression}
  12304. | @stxlit{size:} @var{size-expression}
  12305. @end display
  12306. A bounded range takes an initial subsequence of the unbounded
  12307. range specified by the @var{start-expression} and optional @var{step-expression}.
  12308. The different @var{end-expression} variants provide different
  12309. ways to specify the initial subsequence.
  12310. If @code{size: @var{size}} is specified, then the resulting range
  12311. is the first @var{size} elements of unbounded sequence.
  12312. In the @code{<: @var{end}} or @code{<=: @var{end}} cases then
  12313. the sequence counts up: The @var{step} must be positive, and defaults to 1.
  12314. The resulting values are those @var{x} such that @code{(< @var{x} @var{end})},
  12315. or @code{(<= @var{x} @var{end})}, respectively.
  12316. In the @code{>: @var{end}} or @code{>=: @var{end}} cases then
  12317. the sequence counts down: The @var{step} must be negative, and defaults to -1.
  12318. The resulting values are those @var{x} such that @code{(> @var{x} @var{end})},
  12319. or @code{(>= @var{x} @var{end})}, respectively.
  12320. The @var{start-expression}, @var{step-expression}, and @var{size-expression}
  12321. must evaluate to real numbers, not necessarily integers.
  12322. For example: @code{[1 by: 0.5 <=: 3.0]} is @code{[1.0 1.5 2.0 2.5 3.0]}.
  12323. The two pseudo-ranges @code{[<:]} and @code{[>:]} are useful as
  12324. array indexes. They mean ``all of the valid indexes'' of the array being indexed.
  12325. For increasing index values use @code{[<:]}; for decreasing
  12326. index values (i.e. reversing) use @code{[>:]}.
  12327. @node Streams
  12328. @section Streams - lazy lists
  12329. Streams, sometimes called lazy lists, are a sequential data structure
  12330. containing elements computed only on demand. A stream is either null
  12331. or is a pair with a stream in its cdr. Since elements of a stream are
  12332. computed only when accessed, streams can be infinite. Once computed,
  12333. the value of a stream element is cached in case it is needed again.
  12334. @emph{Note:} These are not the same as Java 8 streams.
  12335. @example
  12336. (require 'srfi-41)
  12337. (define fibs
  12338. (stream-cons 1
  12339. (stream-cons 1
  12340. (stream-map +
  12341. fibs
  12342. (stream-cdr fibs)))))
  12343. (stream->list 8 fibs) @result{} (1 1 2 3 5 8 13 21)
  12344. @end example
  12345. See the @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41 specification} for details.
  12346. The Kawa implementations builds on @ref{Lazy evaluation,,promises}.
  12347. The @code{stream-null} value is a promise that evaluates to the empty list.
  12348. The result of @code{stream-cons} is an eager immutable pair whose
  12349. @code{car} and @code{cdr} properties return promises.
  12350. @node Arrays
  12351. @section Multi-dimensional Arrays
  12352. Arrays are heterogeneous data structures that generaize vectors to multiple
  12353. indexes or dimensions. Instead of a single integer index,
  12354. there are multiple indexes: An index is a vector of integers;
  12355. the length of a valid index sequence
  12356. is the rank or the number of dimensions of an array.
  12357. @c @example
  12358. @c (define arr1 (
  12359. @c @end example
  12360. Kawa multi-dimensional arrays follows the
  12361. by @uref{http://srfi.schemers.org/srfi-25/srfi-25.html,SRFI-25 specification},
  12362. with additions from Racket's
  12363. @uref{https://docs.racket-lang.org/math/array.html, math.array} package
  12364. and other sources.
  12365. An array whose rank is 1, and where the (single) lower bound is 0
  12366. is a sequence.
  12367. Furthermore, if such an array is simple (not created by @code{share-array})
  12368. it will be implemented using a @code{<vector>}.
  12369. Uniform vectors and strings are also arrays in Kawa.
  12370. A rank-0 array has a single value. It is essentially a box for that
  12371. value. Functions that require arrays may treat non-arrays
  12372. as a rank-0 array containing that value.
  12373. An array of rank 2 is frequently called a @dfn{matrix}.
  12374. Note that Kawa arrays are distinct from Java (native) arrays.
  12375. The latter is a simpler one-dimensional vector-like data structure,
  12376. which is used to implement Kawa arrays and vectors.
  12377. @deffn Procedure array? obj
  12378. Returns @code{#t} if @var{obj} is an array, otherwise returns @code{#f}.
  12379. @end deffn
  12380. @subsection Array shape
  12381. The @dfn{shape} of an array consists of bounds for each index.
  12382. @c a simple-array is either a SimpleVector or a GeneralArray
  12383. @c a generic vector implements AVector
  12384. @c a stored-array is a simple-array or a transform (view) of a simple-array
  12385. The lower bound @var{b} and the upper bound @var{e} of a dimension are
  12386. exact integers with @code{(<= @var{b} @var{e})}. A valid index along the
  12387. dimension is an exact integer @var{i} that satisfies both
  12388. @code{(<= @var{b} @var{i})} and @code{(< @var{i} @var{e})}.
  12389. The length of the array along the dimension is the difference
  12390. @code{(- @var{e} @var{b})}.
  12391. The size of an array is the product of the lengths of its dimensions.
  12392. A procedure that requires a @var{shape} accepts any of the following:
  12393. @itemize
  12394. @item
  12395. A vector of simple @ref{Ranges,ranges}, one for each
  12396. dimension, all of who are
  12397. bounded (finite), consist of integer values,
  12398. and have a @var{step} of 1.
  12399. Each range, which is usually written as @code{[@var{b} <: @var{e}]},
  12400. expresses the bounds of the corresponding dimension.
  12401. For example @code{[[0 <: 5] [2 <=: 6]]} is the shape
  12402. of a rank-2 array, where the first index can be from 0 to 5 (exclusive),
  12403. while the second index can be from 2 to 6 (inclusive).
  12404. @item
  12405. A vector of simple integers.
  12406. Each integer @var{e} is an upper bound,
  12407. and is equivalent to the range @code{[0 <: @var{e}]}.
  12408. @item
  12409. A vector consisting of a mix of integers and ranges.
  12410. @item
  12411. A rank-2 array @var{S} whose own shape is @code{[@var{r} 2]}.
  12412. For each dimension @var{k}
  12413. (where @code{(<= @var{k} 0)} and @code{(< @var{k} @var{r})}),
  12414. the lower bound @var{b@sub{k}} is @code{(S @var{k} 0)},
  12415. and the upper bound @var{e@sub{k}} is @code{(S @var{k} 1)}.
  12416. @end itemize
  12417. @deffn Procedure shape bound ...
  12418. Returns a shape. The sequence @var{bound} ... must consist of an even number
  12419. of exact integers that are pairwise not decreasing. Each pair gives the
  12420. lower and upper bound of a dimension.
  12421. If the shape is used to specify the dimensions of an array
  12422. and @var{bound} ... is the sequence @var{b0} @var{e0} ... @var{bk} @var{ek}
  12423. ... of @var{n} pairs of bounds, then a valid index to the array is any
  12424. sequence @var{j0} ... @var{jk} ... of @var{n} exact integers where
  12425. each @var{jk} satisfies @code{(<= @var{bk} @var{jk})}
  12426. and @code{(< @var{jk} @var{ek})}.
  12427. The shape of a @var{d}-dimensional array is a @var{d} * 2 array
  12428. where the element at @var{k 0} contains the lower bound for an index along
  12429. dimension @var{k} and the element at @var{k 1} contains the
  12430. corresponding upper bound, where @var{k} satisfies @code{(<= 0 @var{k})}
  12431. and @code{(< @var{k} @var{d})}.
  12432. @code{(shape @@@var{bounds})}
  12433. is equivalent to:
  12434. @code{(array [2 (/ (length @var{bounds}) 2)] @@@var{bounds})}
  12435. @end deffn
  12436. @deffn Procedure array-rank array
  12437. Returns the number of dimensions of @var{array}.
  12438. @example
  12439. (array-rank
  12440. (make-array (shape 1 2 3 4)))
  12441. @end example
  12442. Returns 2.
  12443. @end deffn
  12444. @deffn Procedure array-start array k
  12445. Returns the lower bound (inclusive) for the index along dimension @var{k}.
  12446. This is most commonly 0.
  12447. @end deffn
  12448. @deffn Procedure array-end array k
  12449. Returns the upper bound for the index along dimension @var{k}.
  12450. The bound is exclusive - i.e. the first integer higher
  12451. than the last legal index.
  12452. @end deffn
  12453. @deffn Procedure array-size array
  12454. Return the total number of elements of @var{array}.
  12455. This is the product of @code{(- (array-end @var{array} @var{k}) (array-start @var{array} @var{k}))} for every valid @var{k}.
  12456. @end deffn
  12457. @subsection Array types
  12458. @deffn Type array
  12459. @deffnx Type array@var{N}
  12460. @deffnx Type array[@var{etype}]
  12461. @deffnx Type array@var{N}[@var{etype}]
  12462. The type @code{array} matches all array values.
  12463. The type @code{array@var{N}}, where @var{N} is an integer
  12464. matches array of rank @var{N}.
  12465. For example @code{array2} matches rank-2 array - i.e. matrixes.
  12466. You can optionally specify the element type @var{etype}.
  12467. This can be a primitive type.
  12468. For example a @code{array2[double]} is a rank-2 array
  12469. whose elements are @code{double} values.
  12470. @end deffn
  12471. @anchor{array-literals}
  12472. @subsection Array literals and printing
  12473. An array literal starts with @code{#} followed by its rank,
  12474. followed by a tag that describes the underlying vector (by default @code{a}),
  12475. optionally followed by information about its shape,
  12476. and finally followed by the cells, organized into dimensions using parentheses.
  12477. For example, @code{#2a((11 12 13) (21 22 23))} is a rank-2 array (a matrix)
  12478. whose shape is @code{[2 3]} or equivalently @code{[[0 <: 2] [0 <: 3]]}.
  12479. It is pretty-printed as:
  12480. @example
  12481. ╔#2a:2:3═╗
  12482. ║11│12│13║
  12483. ╟──┼──┼──╢
  12484. ║21│22│23║
  12485. ╚══╧══╧══╝
  12486. @end example
  12487. @display
  12488. @stxdef{array-literal} @stxref{array-literal-header} @stxref{datum}
  12489. @stxdef{array-literal-header} @stxlit{#} @var{rank} @stxref{vectag} @arbno{@stxref{array-bound}}
  12490. @stxdef{array-bound} [@stxlit{@@}@var{lower}]@stxlit{:}@var{length} | @stxlit{@@}@var{lower}
  12491. @stxdef{vectag} @stxlit{a} | @stxref{uniform-tag}
  12492. @end display
  12493. The @var{vectag} specifies the type of the elements of the array.
  12494. Following the @var{vectag} you can optionally include information
  12495. about the shape: For each dimension you can optionally specify
  12496. the lower bounds (after the character @code{"@@"}),
  12497. followed by the length of the dimension (after the character @code{":"}).
  12498. The shape information is required if a lower bound is non-zero,
  12499. or any length is zero.
  12500. The @stxref{datum} contains the elements in a nested-list format:
  12501. a rank-1 array (i.e. vector) uses a single list,
  12502. a rank-2 array uses a list-of-lists, and so on.
  12503. The elements are in lexicographic order.
  12504. A uniform u32 array of rank 2 with index ranges 2..3 and 3..4:
  12505. @example
  12506. #2u32@@2@@3((1 2) (2 3))
  12507. @end example
  12508. This syntax follows Common Lisp with
  12509. @uref{https://www.gnu.org/software/guile/manual/html_node/Array-Syntax.html,Guile
  12510. extensions}. (Note that Guile prints rank-0 arrays with an extra
  12511. set of parentheses. Kawa follows Common Lisp in not doing so.)
  12512. When an array is printed with the @code{write} function,
  12513. the result is an @code{array-literal}.
  12514. Printing with @code{display} formats the array in a rectangular grid
  12515. using the @code{format-array} procedure.
  12516. (Note that @code{format-array} is only used when the output is in column 0,
  12517. because Kawa has very limited support for printing rectangles.)
  12518. @deffn Procedure format-array value [port] [element-format]
  12519. Produce a nice ``pretty'' display for @var{value}, which is usually an array.
  12520. If @var{port} is an output port, the formatted output is written into
  12521. that port.
  12522. Otherwise, @var{port} must be a boolean (one of @code{#t} or @code{#f}).
  12523. If the port is @code{#t}, output is to the @code{(current-output-port)}.
  12524. If the port is @code{#f} or no port is specified,
  12525. the output is returned as a string.
  12526. If the port is specified and is @code{#t} or an output-port,
  12527. the result of the @code{format-array} procedure is unspecified.
  12528. (This convention matches that of the @code{format} procedure.)
  12529. The top line includes an @code{array-literal-header}.
  12530. The lower bound are only printed if non-zero.
  12531. The dimension lengths are printed if there is room, or if one of them is zero.
  12532. @example
  12533. #|kawa:34|# @kbd{(! arr (array [[1 <=: 2] [1 <=: 3]]}
  12534. #|.....35|# @kbd{ #2a((1 2) (3 4)) 9 #2a((3 4) (5 6))}
  12535. #|.....36|# @kbd{ [42 43] #2a:1:3((8 7 6)) #2a((90 91) (100 101))))}
  12536. #|kawa:37|# @kbd{arr}
  12537. ╔#2a@@1:2@@1:3════╤═════════╗
  12538. ║#2a═╗ │ 9│#2a═╗ ║
  12539. ║║1│2║ │ │║3│4║ ║
  12540. ║╟─┼─╢ │ │╟─┼─╢ ║
  12541. ║║3│4║ │ │║5│6║ ║
  12542. ║╚═╧═╝ │ │╚═╧═╝ ║
  12543. ╟───────┼───────┼─────────╢
  12544. ║╔#1a:2╗│#2a:1:3│╔#2a:2:2╗║
  12545. ║║42│43║│║8│7│6║│║ 90│ 91║║
  12546. ║╚══╧══╝│╚═╧═╧═╝│╟───┼───╢║
  12547. ║ │ │║100│101║║
  12548. ║ │ │╚═══╧═══╝║
  12549. ╚═══════╧═══════╧═════════╝
  12550. @end example
  12551. If @var{element-format} is specified, it is a format string used
  12552. for format each non-array:
  12553. @example
  12554. #|kawa:38|# @kbd{(format-array arr "~4,2f")}
  12555. ╔#2a@@1:2@@1:3══╤════════════════╤═══════════════╗
  12556. ║╔#2a:2:2══╗ │ 9.00│╔#2a:2:2══╗ ║
  12557. ║║1.00│2.00║ │ │║3.00│4.00║ ║
  12558. ║╟────┼────╢ │ │╟────┼────╢ ║
  12559. ║║3.00│4.00║ │ │║5.00│6.00║ ║
  12560. ║╚════╧════╝ │ │╚════╧════╝ ║
  12561. ╟─────────────┼────────────────┼───────────────╢
  12562. ║╔#1a:2╤═════╗│╔#2a:1:3══╤════╗│╔#2a:2:2══════╗║
  12563. ║║42.00│43.00║│║8.00│7.00│6.00║│║ 90.00│ 91.00║║
  12564. ║╚═════╧═════╝│╚════╧════╧════╝│╟──────┼──────╢║
  12565. ║ │ │║100.00│101.00║║
  12566. ║ │ │╚══════╧══════╝║
  12567. ╚═════════════╧════════════════╧═══════════════╝
  12568. @end example
  12569. If the rank is more than 2, then each ``layer''
  12570. is printed separated by double lines.
  12571. @example
  12572. #|kawa:42|# @kbd{(array-reshape [1 <=: 24] [3 2 4])}
  12573. ╔#3a:3:2:4══╗
  12574. ║ 1│ 2│ 3│ 4║
  12575. ╟──┼──┼──┼──╢
  12576. ║ 5│ 6│ 7│ 8║
  12577. ╠══╪══╪══╪══╣
  12578. ║ 9│10│11│12║
  12579. ╟──┼──┼──┼──╢
  12580. ║13│14│15│16║
  12581. ╠══╪══╪══╪══╣
  12582. ║17│18│19│20║
  12583. ╟──┼──┼──┼──╢
  12584. ║21│22│23│24║
  12585. ╚══╧══╧══╧══╝
  12586. @end example
  12587. @end deffn
  12588. @subsection Array construction
  12589. See also @code{array-reshape}
  12590. @deffn Procedure array shape obj ...
  12591. Returns a new array whose shape is given by @var{shape} and the initial
  12592. contents of the elements are @var{obj} ... in row major order. The array does
  12593. not retain a reference to @var{shape}.
  12594. @end deffn
  12595. @deffn Procedure make-array shape
  12596. @deffnx Procedure make-array shape value...
  12597. Returns a newly allocated array whose shape is given by @var{shape}.
  12598. If @var{value} is provided, then each element is initialized to it.
  12599. If there is more than one @var{value}, they are used in order, starting
  12600. over when the @var{value}s are exhausted.
  12601. If there is no @var{value}, the initial contents of each element is
  12602. unspecified. (Actually, it is the @code{#!null}.)
  12603. The array does not retain a reference to @var{shape}.
  12604. @example
  12605. #|kawa:16|# @kbd{(make-array [2 4] 1 2 3 4 5)}
  12606. ╔#2a:2:4╗
  12607. ║1│2│3│4║
  12608. ╟─┼─┼─┼─╢
  12609. ║5│1│2│3║
  12610. ╚═╧═╧═╧═╝
  12611. @end example
  12612. @CompatibilityNote{} Guile has an incompatible @code{make-array} procedure.
  12613. @end deffn
  12614. @deffn Procedure build-array shape getter [setter[
  12615. Construct a ``virtual array'' of the given @var{shape},
  12616. which uses no storage for the elements.
  12617. Instead, elements are calculated on-demand by calling @var{getter},
  12618. which takes a single argument, an index vector.
  12619. There is no caching or memoization.
  12620. @example
  12621. #|kawa:1|# @kbd{(build-array [[10 <: 12] 3]}
  12622. #|....:2|# @kbd{ (lambda (ind)}
  12623. #|....:3|# @kbd{ (let ((x (ind 0)) (y (ind 1)))}
  12624. #|....:4|# @kbd{ (- x y))))}
  12625. #2a@@10:2:3
  12626. ║10│ 9│8║
  12627. ╟──┼──┼─╢
  12628. ║11│10│9║
  12629. ╚══╧══╧═╝
  12630. @end example
  12631. The resulting array is mutable if a @var{setter} is provided.
  12632. The @var{setter} takes two arguments:
  12633. An index vector, and the new value for the specified element.
  12634. Below is a simple and space-efficient (but slow) implementation
  12635. of sparse arrays: Most element have a default initial value,
  12636. but you can override specific elements.
  12637. @example
  12638. (define (make-sparse-array shape default-value)
  12639. (let ((vals '())) ;; association list of (INDEX-VECTOR . VALUE)
  12640. (build-array shape
  12641. (lambda (I)
  12642. (let ((v (assoc I vals)))
  12643. (if v (cdr v)
  12644. default-value)))
  12645. (lambda (I newval)
  12646. (let ((v (assoc I vals)))
  12647. (if v
  12648. (set-cdr! v newval)
  12649. (set! vals (cons (cons I newval) vals))))))))
  12650. @end example
  12651. @end deffn
  12652. @deffn Procedure index-array shape
  12653. Return a new immutable array of the specified @var{shape}
  12654. where each element is the corresponding row-major index.
  12655. Same as @code{(array-reshape [0 <: @var{size}] @var{shape})}
  12656. where @var{size} is the @code{array-size} of the resulting array.
  12657. @example
  12658. #|kawa:1|# @kbd{(index-array [[1 <: 3] [2 <: 6]])}
  12659. #2a@@1:2@@2:4
  12660. ║0│1│2│3║
  12661. ╟─┼─┼─┼─╢
  12662. ║4│5│6│7║
  12663. ╚═╧═╧═╧═╝
  12664. @end example
  12665. @end deffn
  12666. @subsection Array indexing
  12667. If you ``call'' an array as it it were a function,
  12668. it is equivalent to using @code{array-index-ref},
  12669. which is generalization of @code{array-ref}.
  12670. For example, given a rank-2 array @var{arr} with integer indexes @var{i}
  12671. and @var{j}, the following all get the element of @var{arr}
  12672. at index @code{[@var{i} @var{j}]}.
  12673. @example
  12674. (@var{arr} @var{i} @var{j})
  12675. (array-index-ref @var{arr} @var{i} @var{j})
  12676. (array-ref @var{arr} @var{i} @var{j})
  12677. (array-ref @var{arr} [@var{i} @var{j}])
  12678. @end example
  12679. Using function-call notation or @code{array-index-ref}
  12680. (but not plain @code{array-ref}) you can do generalized APL-style
  12681. slicing and indirect indexing.
  12682. See under @code{array-index-ref} for examples.
  12683. @deffn Procedure array-ref array k ...
  12684. @deffnx Procedure array-ref array index
  12685. Returns the contents of the element of @var{array} at index @var{k} ....
  12686. The sequence @var{k} ... must be a valid index to @var{array}.
  12687. In the second form, @var{index} must be either a vector
  12688. (a 0-based 1-dimensional array) containing @var{k} ....
  12689. @example
  12690. (array-ref (array [2 3]
  12691. 'uno 'dos 'tres
  12692. 'cuatro 'cinco 'seis)
  12693. 1 0)
  12694. @end example
  12695. Returns @code{cuatro}.
  12696. @example
  12697. (let ((a (array (shape 4 7 1 2) 3 1 4)))
  12698. (list (array-ref a 4 1)
  12699. (array-ref a (vector 5 1))
  12700. (array-ref a (array (shape 0 2)
  12701. 6 1))))
  12702. @end example
  12703. Returns @code{(3 1 4)}.
  12704. @end deffn
  12705. @deffn Procedure array-index-ref array index ...
  12706. Generalized APL-style array indexing, where each @var{index}
  12707. can be either an array or an integer.
  12708. If each @var{index} is an integer, then the result is the same as @code{array-ref}.
  12709. Otherwise, the result is an immutable array whose rank is the sum of the ranks of
  12710. each @var{index}. An integer is treated as rank-0 array.
  12711. If @var{marr} is the result of @code{(array-index-ref @var{arr} @var{M@sub{1}} @var{M@sub{2}} ...)} then:
  12712. @example
  12713. (@var{marr} @var{i@sub{11}} @var{i@sub{12}} ... @var{i@sub{21}} @var{i@sub{22}} ...)
  12714. @end example
  12715. is defined as:
  12716. @example
  12717. (@var{arr} (@var{M@sub{1}} @var{i@sub{11}} @var{i@sub{12}} ...) (@var{M@sub{2}} @var{i@sub{21}} @var{i@sub{22}} ...) ...)
  12718. @end example
  12719. Each @var{M@sub{k}} gets as many indexes as its rank.
  12720. If @var{M@sub{k}} is an integer, then it we use
  12721. it directly without any indexing.
  12722. Here are some examples, starting with simple indexing.
  12723. @example
  12724. #|kawa:1|# @kbd{(define arr (array #2a((1 4) (0 4))}
  12725. #|.....2|# @kbd{ 10 11 12 13 20 21 22 23 30 31 32 33))}
  12726. #|kawa:3|# @kbd{arr}
  12727. ╔#2a@@1:3:4══╗
  12728. ║10│11│12│13║
  12729. ╟──┼──┼──┼──╢
  12730. ║20│21│22│23║
  12731. ╟──┼──┼──┼──╢
  12732. ║30│31│32│33║
  12733. ╚══╧══╧══╧══╝
  12734. #|kawa:4|# @kbd{(arr 2 3)}
  12735. 23
  12736. @end example
  12737. If one index is a vector and the rest are scalar integers,
  12738. then the result is a vector:
  12739. @example
  12740. #|kawa:5|# @kbd{(arr 2 [3 1])}
  12741. #(23 21)
  12742. @end example
  12743. You can select a ``sub-matrix'' when all indexes are vectors:
  12744. @example
  12745. #|kawa:6|# @kbd{(arr [2 1] [3 1 3])}
  12746. ╔#2a:2:3═╗
  12747. ║23│21│23║
  12748. ╟──┼──┼──╢
  12749. ║13│11│13║
  12750. ╚══╧══╧══╝
  12751. @end example
  12752. Using ranges for index vectors selects a rectangular sub-matrix.
  12753. @example
  12754. #|kawa:7|# @kbd{(arr [1 <: 3] [1 <: 4])}
  12755. ╔#2a:2:3═╗
  12756. ║11│12│13║
  12757. ╟──┼──┼──╢
  12758. ║21│22│23║
  12759. ╚══╧══╧══╝
  12760. @end example
  12761. You can add new dimensions:
  12762. @example
  12763. #|kawa:8|# @kbd{(arr [2 1] #2a((3 1) (3 2)))}
  12764. #3a╤══╗
  12765. ║23│21║
  12766. ╟──┼──╢
  12767. ║23│22║
  12768. ╠══╪══╣
  12769. ║13│11║
  12770. ╟──┼──╢
  12771. ║13│12║
  12772. ╚══╧══╝
  12773. @end example
  12774. The pseudo-range @code{[<:]} can be used to select all the indexes
  12775. along a dimension. To select row 2 (1-origin):
  12776. @example
  12777. #|kawa:9|# @kbd{(arr 2 [<:])}
  12778. #(20 21 22 23)
  12779. @end example
  12780. To reverse the order use @code{[>:]}:
  12781. @example
  12782. #|kawa:10|# @kbd{(arr 2 [>:])}
  12783. #(23 22 21 20)
  12784. @end example
  12785. To select column 3:
  12786. @example
  12787. #|kawa:11|# @kbd{(arr [<:] 3)}
  12788. #(13 23 33)
  12789. @end example
  12790. If you actually want a column matrix (i.e. with shape @code{[3 1]}
  12791. you can place the index in a single-element vector:
  12792. @example
  12793. #|kawa:12|# @kbd{(arr [<:] [3])}
  12794. #2a╗
  12795. ║13║
  12796. ╟──╢
  12797. ║23║
  12798. ╟──╢
  12799. ║33║
  12800. ╚══╝
  12801. @end example
  12802. To expand that column to 5 colums you can repeat the column index:
  12803. @example
  12804. #|kawa:13|# @kbd{[3 by: 0 size: 5]}
  12805. #(3 3 3 3 3)
  12806. #|kawa:14|# @kbd{(arr [<:] [3 by: 0 size: 5])}
  12807. ╔#2a:3:5═╤══╤══╗
  12808. ║13│13│13│13│13║
  12809. ╟──┼──┼──┼──┼──╢
  12810. ║23│23│23│23│23║
  12811. ╟──┼──┼──┼──┼──╢
  12812. ║33│33│33│33│33║
  12813. ╚══╧══╧══╧══╧══╝
  12814. @end example
  12815. @end deffn
  12816. @subsection Modifying arrays
  12817. You can use @code{set!} to modify one or multiple elements.
  12818. To modify a single element:
  12819. @example
  12820. (set! (@var{arr} @var{index} ...) @var{new-value})
  12821. @end example
  12822. is equivalent to
  12823. @example
  12824. (array-set! @var{arr} @var{index} ... @var{new-value})
  12825. @end example
  12826. You can set a slice (or all of the elements).
  12827. In that case:
  12828. @example
  12829. (set! (@var{arr} @var{index} ...) @var{new-array})
  12830. @end example
  12831. is equivalent to:
  12832. @example
  12833. (array-copy! (array-index-share @var{arr} @var{index} ...) @var{new-array})
  12834. @end example
  12835. @deffn Procedure array-set! array k ... obj
  12836. @deffnx Procedure array-set! array index obj
  12837. Stores @var{obj} in the element of @var{array} at index @var{k} ....
  12838. Returns the void value.
  12839. The sequence @var{k} ... must be a valid index to @var{array}.
  12840. In the second form, @var{index} must be either a vector or a
  12841. 0-based 1-dimensional array containing @var{k} ....
  12842. @example
  12843. (let ((a (make-array
  12844. (shape 4 5 4 5 4 5))))
  12845. (array-set! a 4 4 4 "huuhkaja")
  12846. (array-ref a 4 4 4))
  12847. @end example
  12848. Returns @code{"huuhkaja"}.
  12849. @CompatibilityNote{} SRFI-47, Guile and Scheme-48 have @code{array-set!} with a
  12850. different argument order.
  12851. @end deffn
  12852. @deffn Procedure array-copy! dst src
  12853. @CompatibilityNote{} Guile has a @code{array-copy!} with the reversed
  12854. argument order.
  12855. @end deffn
  12856. @deffn Procedure array-fill! array value
  12857. Set all the values @var{array} to @var{value}.
  12858. @end deffn
  12859. @subsection Transformations and views
  12860. A view or transform of an array is an array @var{a@sub{2}}
  12861. whose elements come from some other array @var{a@sub{1}},
  12862. given some transform function @var{T} that maps @var{a@sub{2}} indexes
  12863. to @var{a@sub{1}} indexes.
  12864. Specifically @code{(array-ref @var{a@sub{2}} @var{indexes})}
  12865. is @code{(array-ref @var{a@sub{1}} (@var{T} @var{indexes}))}.
  12866. Modifying @var{a@sub{2}} causes @var{a@sub{1}} to be modified;
  12867. modifying @var{a@sub{1}} may modify @var{a@sub{2}}
  12868. (depending on the transform function).
  12869. The shape of @var{a@sub{2}} is in generally different than that of @var{a@sub{1}}.
  12870. @deffn Procedure array-transform array shape transform
  12871. This is a general mechanism for creating a view.
  12872. The result is a new array with the given @var{shape}.
  12873. Accessing this new array is implemented by calling the @var{transform}
  12874. function on the index vector, which must return a new index vector
  12875. valid for indexing the original @var{array}.
  12876. Here is an example (using the same @code{arr} as in
  12877. the @code{array-index-ref} example):
  12878. @example
  12879. #|kawa:1|# @kbd{(define arr (array #2a((1 4) (0 4))}
  12880. #|.....2|# @kbd{ 10 11 12 13 20 21 22 23 30 31 32 33))}
  12881. #|kawa:14|# @kbd{(array-transform arr #2a((0 3) (1 3) (0 2))}
  12882. #|.....15|# @kbd{ (lambda (ix) (let ((i (ix 0)) (j (ix 1)) (k (ix 2)))}
  12883. #|.....16|# @kbd{ [(+ i 1)}
  12884. #|.....17|# @kbd{ (+ (* 2 (- j 1)) k)])))}
  12885. #3a:3@@1:2:2
  12886. ║10│11║
  12887. ╟──┼──╢
  12888. ║12│13║
  12889. ╠══╪══╣
  12890. ║20│21║
  12891. ╟──┼──╢
  12892. ║22│23║
  12893. ╠══╪══╣
  12894. ║30│31║
  12895. ╟──┼──╢
  12896. ║32│33║
  12897. ╚══╧══╝
  12898. @end example
  12899. The @code{array-transform} is generalization of @code{share-array},
  12900. in that it does not require the @var{transform} to be affine.
  12901. Also note the different calling conversions for the @var{tranform}:
  12902. @code{array-transform} takes a single argument (a vector of indexes),
  12903. and returns a single result (a vector of indexes);
  12904. @code{share-array} takes one argument for each index, and returns
  12905. one value for each index. The difference is historical.
  12906. @end deffn
  12907. @deffn Procedure array-index-share array index ...
  12908. This does the same generalized APL-style indexing
  12909. as @code{array-index-ref}. However, the resulting array
  12910. is a modifiable view into the argument @var{array}.
  12911. @end deffn
  12912. @deffn Procedure array-reshape array shape
  12913. Creates a new array @var{narray} of the given @var{shape},
  12914. such that @code{(array->vector @var{array})} and
  12915. @code{(array->vector @var{narray})} are equivalent.
  12916. I.e. the @var{i}'th element in row-major-order of @var{narray}
  12917. is the @var{i}'th element in row-major-order of @var{array}.
  12918. Hence @code{(array-size @var{narray})} (as specied from the @var{shape})
  12919. must be equal to @code{(array-size @var{array})}.
  12920. The resulting @var{narray} is a view such that modifying @var{array}
  12921. also modifies @var{narray} and vice versa.
  12922. @end deffn
  12923. @deffn Procedure share-array array shape proc
  12924. Returns a new array of @var{shape} shape that shares elements of @var{array}
  12925. through @var{proc}. The procedure @var{proc} must implement an affine
  12926. function that returns indices of @var{array} when given indices of the
  12927. array returned by @code{share-array}.
  12928. The array does not retain a reference to @var{shape}.
  12929. @example
  12930. (define i_4
  12931. (let* ((i (make-array
  12932. (shape 0 4 0 4)
  12933. 0))
  12934. (d (share-array i
  12935. (shape 0 4)
  12936. (lambda (k)
  12937. (values k k)))))
  12938. (do ((k 0 (+ k 1)))
  12939. ((= k 4))
  12940. (array-set! d k 1))
  12941. i))
  12942. @end example
  12943. Note: the affinity requirement for @var{proc} means that each value must
  12944. be a sum of multiples of the arguments passed to @var{proc}, plus a constant.
  12945. Implementation note: arrays have to maintain an internal index mapping
  12946. from indices @var{k1} ... @var{kd} to a single index into a backing vector;
  12947. the composition of this mapping and @var{proc} can be recognised
  12948. as @code{(@var{+ n0} (* @var{n1} @var{k1}) ... (* @var{nd} @var{kd}))}
  12949. by setting each index in turn to 1 and others to 0,
  12950. and all to 0 for the constant term; the composition can then be compiled
  12951. away, together with any complexity that the user introduced in their
  12952. procedure.
  12953. Here is an example where the @var{array} is a uniform vector:
  12954. @example
  12955. (share-array
  12956. (f64vector 1.0 2.0 3.0 4.0 5.0 6.0)
  12957. (shape 0 2 0 3)
  12958. (lambda (i j) (+ (* 2 i) j)))
  12959. @result{} #2f64((1.0 2.0 3.0) (4.0 5.0 6.0))
  12960. @end example
  12961. @end deffn
  12962. @deffn Procedure array-flatten array
  12963. @deffnx Procedure array->vector array
  12964. Return a vector consisting of the elements of the @var{array}
  12965. in row-major-order.
  12966. The result of @code{array-flatten} is fresh (mutable) copy, not a view.
  12967. The result of @code{array->vector} is a view: If @var{array} is mutable,
  12968. then modifying @var{array} changes the flattened result and vice versa.
  12969. If @var{array} is ``simple'', @code{array->vector} returns the original vector.
  12970. Specifically, if @var{vec} is a vector then:
  12971. @example
  12972. (eq? @var{vec} (array->vector (array-reshape @var{vec} @var{shape})))
  12973. @end example
  12974. @end deffn
  12975. @subsection Miscellaneous
  12976. @deffn Procedure format-array value [element-format]
  12977. @end deffn
  12978. @node Hash tables
  12979. @section Hash tables
  12980. A @dfn{hashtable} is a data structure that
  12981. associates keys with values.
  12982. The hashtable has no intrinsic order for the (key, value) associations
  12983. it contains, and
  12984. supports in-place modification as the primary means of setting the contents
  12985. of a hash table.
  12986. Any object can be used as a key, provided a @dfn{hash function} and a suitable
  12987. @dfn{equivalence function} is available.
  12988. A hash function is a procedure that
  12989. maps keys to exact integer objects.
  12990. The hashtable provides key lookup and destructive update in amortised
  12991. constant time, provided that a good hash function is used.
  12992. A hash function @var{h} is acceptable for an equivalence predicate @var{e} iff
  12993. @code{(@var{e} @var{obj1} @var{obj2})} implies
  12994. @code{(= (@var{h} @var{obj1}) (@var{h} @var{obj2}))}.
  12995. A hash function @var{h} is good for a equivalence predicate @var{e} if
  12996. it distributes the resulting hash values for non-equal objects
  12997. (by @var{e}) as uniformly as possible over the range of hash
  12998. values, especially in the case when some (non-equal) objects resemble
  12999. each other by e.g. having common subsequences. This definition is
  13000. vague but should be enough to assert that e.g. a constant function is
  13001. not a good hash function.
  13002. Kawa provides two complete sets of functions for hashtables:
  13003. @itemize
  13004. @item
  13005. The functions specified by R6RS have names starting with @code{hashtable-}
  13006. @item
  13007. The functions specified by the older
  13008. @uref{http://srfi.schemers.org/srfi-69/srfi-69.html, SRFI-69} specifiation
  13009. have names starting with @code{hash-table-}
  13010. @end itemize
  13011. Both interfaces use the same underlying datatype, so it is possible
  13012. to mix and match from both sets.
  13013. That datatype implements @code{java.util.Map}.
  13014. @c The Kawa implementation has been optimized for performance and better
  13015. @c Java integration. Specifically, the default hash function uses
  13016. @c the standard Java @code{hashCode} method.
  13017. Freshly-written code should probably use the R6RS functions.
  13018. @subsection R6RS hash tables
  13019. To use these hash table functions in your Kawa program you must first:
  13020. @example
  13021. (import (rnrs hashtables))
  13022. @end example
  13023. This section uses the @var{hashtable} parameter name for arguments that
  13024. must be hashtables, and the @var{key} parameter name for arguments that
  13025. must be hashtable keys.
  13026. @deffn Procedure make-eq-hashtable
  13027. @deffnx Procedure make-eq-hashtable @var{k}
  13028. Return a newly allocated mutable hashtable that accepts arbitrary
  13029. objects as keys, and compares those keys with @func{eq?}. If an
  13030. argument is given, the initial capacity of the hashtable is set to
  13031. approximately @var{k} elements.
  13032. @end deffn
  13033. @deffn Procedure make-eqv-hashtable
  13034. @deffnx Procedure make-eqv-hashtable @var{k}
  13035. Return a newly allocated mutable hashtable that accepts arbitrary
  13036. objects as keys, and compares those keys with @func{eqv?}. If an
  13037. argument is given, the initial capacity of the hashtable is set to
  13038. approximately @var{k} elements.
  13039. @end deffn
  13040. @deffn Procedure make-hashtable @var{hash-function} @var{equiv}
  13041. @deffnx Procedure make-hashtable @var{hash-function} @var{equiv} @var{k}
  13042. @var{hash-function} and @var{equiv} must be procedures.
  13043. @var{hash-function} should accept a key as an argument and should return
  13044. a non--negative exact integer object. @var{equiv} should accept two
  13045. keys as arguments and return a single value. Neither procedure should
  13046. mutate the hashtable returned by @func{make-hashtable}.
  13047. The @func{make-hashtable} procedure returns a newly allocated mutable
  13048. hashtable using @var{hash-function} as the hash function and @var{equiv}
  13049. as the equivalence function used to compare keys. If a third argument
  13050. is given, the initial capacity of the hashtable is set to approximately
  13051. @var{k} elements.
  13052. Both @var{hash-function} and @var{equiv} should behave like pure
  13053. functions on the domain of keys. For example, the @func{string-hash}
  13054. and @func{string=?} procedures are permissible only if all keys are
  13055. strings and the contents of those strings are never changed so long as
  13056. any of them continues to serve as a key in the hashtable. Furthermore,
  13057. any pair of keys for which @var{equiv} returns true should be hashed to
  13058. the same exact integer objects by @var{hash-function}.
  13059. @quotation
  13060. @emph{Note:} Hashtables are allowed to cache the results of calling the
  13061. hash function and equivalence function, so programs cannot rely on the
  13062. hash function being called for every lookup or update. Furthermore any
  13063. hashtable operation may call the hash function more than once.
  13064. @end quotation
  13065. @end deffn
  13066. @subsubsection Procedures
  13067. @deffn Procedure {hashtable?} @var{obj}
  13068. Return @true{} if @var{obj} is a hashtable, @false{} otherwise.
  13069. @end deffn
  13070. @deffn Procedure hashtable-size @var{hashtable}
  13071. Return the number of keys contained in @var{hashtable} as an exact
  13072. integer object.
  13073. @end deffn
  13074. @deffn Procedure hashtable-ref @var{hashtable} @var{key} @var{default}
  13075. Return the value in @var{hashtable} associated with @var{key}. If
  13076. @var{hashtable} does not contain an association for @var{key},
  13077. @var{default} is returned.
  13078. @end deffn
  13079. @deffn Procedure {hashtable-set!} @var{hashtable} @var{key} @var{obj}
  13080. Change @var{hashtable} to associate @var{key} with @var{obj}, adding a
  13081. new association or replacing any existing association for @var{key}, and
  13082. returns unspecified values.
  13083. @end deffn
  13084. @deffn Procedure {hashtable-delete!} @var{hashtable} @var{key}
  13085. Remove any association for @var{key} within @var{hashtable} and returns
  13086. unspecified values.
  13087. @end deffn
  13088. @deffn Procedure {hashtable-contains?} @var{hashtable} @var{key}
  13089. Return @true{} if @var{hashtable} contains an association for @var{key},
  13090. @false{} otherwise.
  13091. @end deffn
  13092. @deffn Procedure {hashtable-update!} @var{hashtable} @var{key} @var{proc} @var{default}
  13093. @var{proc} should accept one argument, should return a single value, and
  13094. should not mutate @var{hashtable}.
  13095. The @func{hashtable-update!} procedure applies @var{proc} to the value
  13096. in @var{hashtable} associated with @var{key}, or to @var{default} if
  13097. @var{hashtable} does not contain an association for @var{key}. The
  13098. @var{hashtable} is then changed to associate @var{key} with the value
  13099. returned by @var{proc}.
  13100. The behavior of @func{hashtable-update!} is equivalent to the following
  13101. code, but is may be (and is in Kawa) implemented more efficiently in cases
  13102. where the implementation can avoid multiple lookups of the same key:
  13103. @example
  13104. (hashtable-set!
  13105. hashtable key
  13106. (proc (hashtable-ref
  13107. hashtable key default)))
  13108. @end example
  13109. @end deffn
  13110. @deffn Procedure hashtable-copy @var{hashtable}
  13111. @deffnx Procedure hashtable-copy @var{hashtable} @var{mutable}
  13112. Return a copy of @var{hashtable}. If the @var{mutable} argument is
  13113. provided and is true, the returned hashtable is mutable; otherwise it is
  13114. immutable.
  13115. @end deffn
  13116. @deffn Procedure {hashtable-clear!} @var{hashtable}
  13117. @deffnx Procedure {hashtable-clear!} @var{hashtable} @var{k}
  13118. Remove all associations from @var{hashtable} and returns unspecified
  13119. values.
  13120. If a second argument is given, the current capacity of the hashtable is
  13121. reset to approximately @var{k} elements.
  13122. @end deffn
  13123. @deffn Procedure hashtable-keys @var{hashtable}
  13124. Return a vector of all keys in @var{hashtable}. The order of the vector
  13125. is unspecified.
  13126. @end deffn
  13127. @deffn Procedure hashtable-entries @var{hashtable}
  13128. Return two values, a vector of the keys in @var{hashtable}, and a vector
  13129. of the corresponding values.
  13130. Example:
  13131. @example
  13132. (let ((h (make-eqv-hashtable)))
  13133. (hashtable-set! h 1 'one)
  13134. (hashtable-set! h 2 'two)
  13135. (hashtable-set! h 3 'three)
  13136. (hashtable-entries h))
  13137. @result{} #(1 2 3) #(one two three) ; two return values
  13138. @end example
  13139. @noindent
  13140. the order of the entries in the result vectors is not known.
  13141. @end deffn
  13142. @subsubsection Inspection
  13143. @deffn Procedure hashtable-equivalence-function @var{hashtable}
  13144. Return the equivalence function used by @var{hashtable} to compare keys.
  13145. For hashtables created with @func{make-eq-hashtable} and
  13146. @func{make-eqv-hashtable}, returns @func{eq?} and @func{eqv?}
  13147. respectively.
  13148. @end deffn
  13149. @deffn Procedure hashtable-hash-function @var{hashtable}
  13150. Return the hash function used by @var{hashtable}. For hashtables
  13151. created by @func{make-eq-hashtable} or @func{make-eqv-hashtable},
  13152. @false{} is returned.
  13153. @end deffn
  13154. @deffn Procedure {hashtable-mutable?} @var{hashtable}
  13155. Return @true{} if @var{hashtable} is mutable, otherwise @false{}.
  13156. @end deffn
  13157. @subsubsection Hash functions
  13158. The @func{equal-hash}, @func{string-hash}, and @func{string-ci-hash}
  13159. procedures of this section are acceptable as the hash functions of a
  13160. hashtable only if the keys on which they are called are not mutated
  13161. while they remain in use as keys in the hashtable.
  13162. @deffn Procedure equal-hash @var{obj}
  13163. Return an integer hash value for @var{obj}, based on its structure and
  13164. current contents. This hash function is suitable for use with
  13165. @func{equal?} as an equivalence function.
  13166. @quotation
  13167. @emph{Note:} Like @func{equal?}, the @func{equal-hash} procedure must
  13168. always terminate, even if its arguments contain cycles.
  13169. @end quotation
  13170. @end deffn
  13171. @deffn Procedure string-hash @var{string}
  13172. Return an integer hash value for @var{string}, based on its current
  13173. contents. This hash function is suitable for use with @func{string=?}
  13174. as an equivalence function.
  13175. @end deffn
  13176. @deffn Procedure string-ci-hash @var{string}
  13177. Return an integer hash value for @var{string} based on its current
  13178. contents, ignoring case. This hash function is suitable for use with
  13179. @func{string-ci=?} as an equivalence function.
  13180. @end deffn
  13181. @deffn Procedure symbol-hash @var{symbol}
  13182. Return an integer hash value for @var{symbol}.
  13183. @end deffn
  13184. @subsection SRFI-69 hash tables
  13185. To use these hash table functions in your Kawa program you must first:
  13186. @example
  13187. (require 'srfi-69)
  13188. @end example
  13189. or
  13190. @example
  13191. (require 'hash-table)
  13192. @end example
  13193. or
  13194. @example
  13195. (import (srfi 69 basic-hash-tables))
  13196. @end example
  13197. @subsubsection Type constructors and predicate
  13198. @deffn Procedure make-hash-table [ equal? [ hash [ size-hint]]] → hash-table
  13199. Create a new hash table with no associations.
  13200. The @var{equal?} parameter is a predicate
  13201. that should accept two keys and return a boolean telling whether they
  13202. denote the same key value; it defaults to the @code{equal?} function.
  13203. The @var{hash} parameter is a hash function, and defaults to an
  13204. appropriate hash function
  13205. for the given @var{equal?} predicate (see the Hashing section).
  13206. However, an
  13207. acceptable default is not guaranteed to be given for any equivalence
  13208. predicate coarser than @code{equal?}, except for @code{string-ci=?}.
  13209. (The function @code{hash} is acceptable for @code{equal?}, so if you
  13210. use coarser equivalence than @code{equal?} other than @code{string-ci=?},
  13211. you must always provide the function hash yourself.)
  13212. (An equivalence predicate @var{c1} is coarser than a equivalence
  13213. predicate @var{c2} iff there exist values @var{x} and @var{y} such
  13214. that @code{(and (@var{c1} @var{x} @var{y}) (not (@var{c2} @var{x} @var{y})))}.)
  13215. The @var{size-hint} parameter can be used to suggested an approriate
  13216. initial size. This option is not part of the SRFI-69 specification
  13217. (though it is handled by the reference implementation), so specifying
  13218. that option might be unportable.
  13219. @end deffn
  13220. @deffn Procedure hash-table? obj → boolean
  13221. A predicate to test whether a given object @var{obj} is a hash table.
  13222. @end deffn
  13223. @deffn Procedure alist->hash-table alist [ equal? [ hash [ size-hint]]] → hash-table
  13224. Takes an association list @var{alist} and creates a hash table
  13225. @var{hash-table} which maps the @code{car} of every element in
  13226. @var{alist} to the @code{cdr} of corresponding elements in
  13227. @var{alist}. The @var{equal?}, @var{hash}, and @var{size-hint}
  13228. parameters are interpreted as in @code{make-hash-table}. If some key
  13229. occurs multiple times in @var{alist}, the value in the first
  13230. association will take precedence over later ones. (Note: the choice of
  13231. using @code{cdr} (instead of @code{cadr}) for values tries to strike
  13232. balance between the two approaches: using @var{cadr} would render this
  13233. procedure unusable for @code{cdr} alists, but not vice versa.)
  13234. @end deffn
  13235. @subsubsection Reflective queries
  13236. @deffn Procedure hash-table-equivalence-function hash-table
  13237. Returns the equivalence predicate used for keys of @var{hash-table}.
  13238. @end deffn
  13239. @deffn Procedure hash-table-hash-function hash-table
  13240. Returns the hash function used for keys of @var{hash-table}.
  13241. @end deffn
  13242. @subsubsection Dealing with single elements
  13243. @deffn Procedure hash-table-ref hash-table key [ thunk ] → value
  13244. This procedure returns the value associated to @var{key} in
  13245. @var{hash-table}. If no value is associated to @var{key} and
  13246. @var{thunk} is given, it is called with no arguments and its value is
  13247. returned; if @var{thunk} is not given, an error is signalled. Given a
  13248. good hash function, this operation should have an (amortised) complexity
  13249. of O(1) with respect to the number of associations in @var{hash-table}.
  13250. @end deffn
  13251. @deffn Procedure hash-table-ref/default hash-table key default → value
  13252. Evaluates to the same value as @code{(hash-table-ref @var{hash-table}
  13253. @var{key} (lambda () @var{default}))}. Given a good hash function, this
  13254. operation should have an (amortised) complexity of O(1) with respect
  13255. to the number of associations in hash-table.
  13256. @end deffn
  13257. @deffn Procedure hash-table-set! hash-table key value → void
  13258. This procedure sets the value associated to @var{key} in
  13259. @var{hash-table}. The previous association (if any) is removed. Given
  13260. a good hash function, this operation should have an (amortised)
  13261. complexity of O(1) with respect to the number of associations in
  13262. hash-table.
  13263. @end deffn
  13264. @deffn Procedure hash-table-delete! hash-table key → void
  13265. This procedure removes any association to @var{key} in
  13266. @var{hash-table}. It is not an error if no association for the
  13267. @var{key} exists; in this case, nothing is done. Given a good hash
  13268. function, this operation should have an (amortised) complexity of O(1)
  13269. with respect to the number of associations in hash-table.
  13270. @end deffn
  13271. @deffn Procedure hash-table-exists? hash-table key → boolean
  13272. This predicate tells whether there is any association to @var{key} in
  13273. @var{hash-table}. Given a good hash function, this operation should
  13274. have an (amortised) complexity of O(1) with respect to the number of
  13275. associations in hash-table.
  13276. @end deffn
  13277. @deffn Procedure hash-table-update! hash-table key function [ thunk ] → void
  13278. Semantically equivalent to, but may be implemented more efficiently than,
  13279. the following code:
  13280. @example
  13281. (hash-table-set! @var{hash-table key}
  13282. (function (hash-table-ref @var{hash-table} @var{key} @var{thunk})))
  13283. @end example
  13284. @end deffn
  13285. @deffn Procedure hash-table-update!/default hash-table key function default → void
  13286. Behaves as if it evaluates to
  13287. @code{(hash-table-update! @var{hash-table} @var{key} @var{function} (lambda () @var{default}))}.
  13288. @end deffn
  13289. @subsubsection Dealing with the whole contents
  13290. @deffn Procedure hash-table-size hash-table → integer
  13291. Returns the number of associations in @var{hash-table}. This operation takes
  13292. constant time.
  13293. @end deffn
  13294. @deffn Procedure hash-table-keys hash-table → list
  13295. Returns a list of keys in @var{hash-table}.
  13296. The order of the keys is unspecified.
  13297. @end deffn
  13298. @deffn Procedure hash-table-values hash-table → list
  13299. Returns a list of values in @var{hash-table}. The order of the values is
  13300. unspecified, and is not guaranteed to match the order of keys in the
  13301. result of @code{hash-table-keys}.
  13302. @end deffn
  13303. @deffn Procedure hash-table-walk hash-table proc → void
  13304. @var{proc} should be a function taking two arguments, a key and a
  13305. value. This procedure calls @var{proc} for each association in
  13306. @var{hash-table}, giving the key of the association as key and the
  13307. value of the association as value. The results of @var{proc} are
  13308. discarded. The order in which @var{proc} is called for the different
  13309. associations is unspecified.
  13310. @end deffn
  13311. @deffn Procedure hash-table-fold hash-table f init-value → final-value
  13312. This procedure calls @var{f} for every association in @var{hash-table}
  13313. with three arguments: the key of the association key, the value of the
  13314. association value, and an accumulated value, @var{val}. The @var{val}
  13315. is @var{init-value} for the first invocation of @var{f}, and for
  13316. subsequent invocations of @var{f}, the return value of the previous
  13317. invocation of @var{f}. The value @var{final-value} returned by
  13318. @code{hash-table-fold} is the return value of the last invocation of
  13319. @var{f}. The order in which @var{f} is called for different
  13320. associations is unspecified.
  13321. @end deffn
  13322. @deffn Procedure hash-table->alist hash-table → alist
  13323. Returns an association list such that the @code{car} of each element
  13324. in @var{alist} is a key in @var{hash-table} and the corresponding
  13325. @code{cdr} of each element in @var{alist} is the value associated to
  13326. the key in @var{hash-table}. The order of the elements is unspecified.
  13327. The following should always produce a hash table with the same mappings
  13328. as a hash table @var{h}:
  13329. @example
  13330. (alist->hash-table (hash-table->alist @var{h})
  13331. (hash-table-equivalence-function @var{h})
  13332. (hash-table-hash-function @var{h}))
  13333. @end example
  13334. @end deffn
  13335. @deffn Procedure hash-table-copy hash-table → hash-table
  13336. Returns a new hash table with the same equivalence predicate, hash
  13337. function and mappings as in @var{hash-table}.
  13338. @end deffn
  13339. @deffn Procedure hash-table-merge! hash-table1 hash-table2 → hash-table
  13340. Adds all mappings in @var{hash-table2} into @var{hash-table1} and
  13341. returns the resulting hash table. This function may modify
  13342. @var{hash-table1} destructively.
  13343. @end deffn
  13344. @subsubsection Hash functions
  13345. The Kawa implementation always calls these hash functions with a single
  13346. parameter, and expects the result to be within the entire
  13347. (32-bit signed) @code{int} range, for compatibility with
  13348. standard @code{hashCode} methods.
  13349. @deffn Procedure hash object [ bound ] → integer
  13350. Produces a hash value for object in the range from 0 (inclusive) tp to
  13351. @var{bound} (exclusive).
  13352. If @var{bound} is not given, the Kawa implementation returns a value within
  13353. the range @w{@code{(- (expt 2 32))}} (inclusive)
  13354. to @w{@code{(- (expt 2 32) 1)}} (inclusive).
  13355. It does this by calling the standard @code{hashCode} method,
  13356. and returning the result as is.
  13357. (If the @var{object} is the Java @code{null} value, 0 is returned.)
  13358. This hash function is acceptable for @code{equal?}.
  13359. @end deffn
  13360. @deffn Procedure string-hash string [ bound ] → integer
  13361. The same as @code{hash}, except that the argument string must be a string.
  13362. (The Kawa implementation returns the same as the @code{hash} function.)
  13363. @end deffn
  13364. @deffn Procedure string-ci-hash string [ bound ] → integer
  13365. The same as @code{string-hash}, except that the case of characters in
  13366. string does not affect the hash value produced.
  13367. (The Kawa implementation returns the same the @code{hash} function
  13368. applied to the lower-cased @var{string}.)
  13369. @end deffn
  13370. @deffn Procedure hash-by-identity object [ bound ] → integer
  13371. The same as @code{hash}, except that this function is only guaranteed
  13372. to be acceptable for @code{eq?}.
  13373. Kawa uses the @code{identityHashCode} method of @code{java.lang.System}.
  13374. @end deffn
  13375. @node Eval and Environments
  13376. @chapter Eval and Environments
  13377. @deffn Procedure environment @arbno{list}
  13378. This procedure returns a specifier for the environment that
  13379. results by starting with an empty environment and then
  13380. importing each @var{list}, considered as an @stxref{import-set}, into it.
  13381. The bindings of the environment represented by the specifier
  13382. are immutable, as is the environment itself.
  13383. See the @code{eval} function for examples.
  13384. @end deffn
  13385. @deffn Procedure null-environment version
  13386. This procedure returns an environment that contains no variable bindings,
  13387. but contains (syntactic) bindings for all the syntactic keywords.
  13388. The effect of assigning to a variable in this environment (such
  13389. as @code{let}) is undefined.
  13390. @end deffn
  13391. @deffn Procedure scheme-report-environment version
  13392. The @var{version} must be an exact non-negative inetger corresponding to
  13393. a version of one of the Revised@var{version} Reports on Scheme.
  13394. The procedure returns an environment that contains exactly the set of
  13395. bindings specified in the corresponding report.
  13396. This implementation supports @var{version} that is 4 or 5.
  13397. The effect of assigning to a variable in this environment (such
  13398. as @code{car}) is undefined.
  13399. @end deffn
  13400. @deffn Procedure interaction-environment
  13401. This procedure return an environment that contains implementation-defined
  13402. bindings, as well as top-level user bindings.
  13403. @end deffn
  13404. @deffn Procedure environment-bound? environment symbol
  13405. Return true @code{#t} if there is a binding for @var{symbol}
  13406. in @var{environment}; otherwise returns @code{#f}.
  13407. @end deffn
  13408. @deffn Procedure environment-fold environment proc init
  13409. Call @var{proc} for each key in the @var{environment},
  13410. which may be any argument to @code{eval}, such as
  13411. @code{(interaction-environment)} or a call to
  13412. the @code{environment} procedure.
  13413. The @var{proc} is called with two arguments:
  13414. The binding's key, and an accumulator value.
  13415. The @var{init} is the initial accumulator value;
  13416. the result returned by @var{proc} is used for subsequent accumulator values.
  13417. The value returned by @code{environment-fold} is the final
  13418. acumulator value.
  13419. A key is normally a symbol,
  13420. but can also be a @code{KeyPair} object (a pair of a symbol and a
  13421. property symbol used to implement Common Lisp-style property lists).
  13422. @example
  13423. (environment-fold (environment '(scheme write)) cons '())
  13424. @result{} (display write-shared write write-simple)
  13425. @end example
  13426. To get all the predefined bindings use @code{(environment '(kawa base))}.
  13427. @end deffn
  13428. @deffn Syntax fluid-let ((variable init) ...) body ...
  13429. Evaluate the @var{init} expressions.
  13430. Then modify the dynamic bindings for the @var{variables} to the
  13431. values of the @var{init} expressions, and evaluate the @var{body} expressions.
  13432. Return the result of the last expression in @var{body}.
  13433. Before returning, restore the original bindings.
  13434. The temporary bindings are only visible in the current thread, and its
  13435. descendent threads.
  13436. @end deffn
  13437. @deffn Procedure base-uri [node]
  13438. If @var{node} is specified, returns the base-URI property
  13439. of the @var{node}. If the @var{node} does not have the base-URI
  13440. property, returns @code{#f}.
  13441. (The XQuery version returns the empty sequence in that case.)
  13442. In the zero-argument case, returns the "base URI" of the current context.
  13443. By default the base URI is the current working directory (as a URL).
  13444. While a source file is @code{load}ed, the base URI is temporarily
  13445. set to the URL of the document.
  13446. @end deffn
  13447. @deffn Procedure eval expression [environment]
  13448. This procedure evaluates @var{expression} in the environment indicated
  13449. by @var{environment}.
  13450. The default for @var{environment} is the result
  13451. of @code{(interaction-environment)}.
  13452. @example
  13453. (eval ’(* 7 3) (environment '(scheme base)))
  13454. @result{} 21
  13455. (let ((f (eval '(lambda (f x) (f x x))
  13456. (null-environment 5))))
  13457. (f + 10))
  13458. @result{} 20
  13459. (eval '(define foo 32) (environment '(scheme base)))
  13460. @result{} @i{error is signaled}
  13461. @end example
  13462. @end deffn
  13463. @deffn Procedure load path [environment]
  13464. @deffnx Procedure load-relative path [environment]
  13465. The @var{path} can be an (absolute) URL or a filename
  13466. of a source file, which is read and evaluated line-by-line.
  13467. The @var{path} can also be a fully-qualified class name.
  13468. (Mostly acts like the @code{-f} command-line option,
  13469. but with different error handling.)
  13470. Since @code{load} is a run-time function it doesn't know
  13471. about the enclosing lexical environment, and the latter
  13472. can't know about definitions introduced by @code{load}.
  13473. For those reasons it is highly recommended that you use instead use
  13474. @code{@ref{require, require}} or @code{@ref{include, include}}.
  13475. Evaluation is done in the specified @var{environment},
  13476. which defauls to result of @code{(interaction-environment)}.
  13477. The @code{load-relative} procedure is like @code{load},
  13478. except that @var{path} is a
  13479. URI that is relative to the context's current base URI.
  13480. @end deffn
  13481. @menu
  13482. * Locations::
  13483. * Parameter objects::
  13484. @end menu
  13485. @node Locations, Parameter objects, , Eval and Environments
  13486. @section Locations
  13487. A @dfn{location} is a place where a value can be stored.
  13488. An @dfn{lvalue} is an expression that refers to a location.
  13489. (The name "lvalue" refers to the fact that the left operand
  13490. of @code{set!} is an lvalue.)
  13491. The only kind of lvalue in standard Scheme is a @dfn{variable}.
  13492. Kawa also allows @dfn{computed lvalues}. These are procedure
  13493. calls used in "lvalue context", such as the left operand of @code{set!}.
  13494. You can only use procedures that have an associated @dfn{setter}.
  13495. In that case, @code{(set! (f arg ...) value)}
  13496. is equivalent to @code{((setter f) arg ... value)}
  13497. Currently, only a few procedures have associated @code{setter}s,
  13498. and only builtin procedures written in Java can have @code{setter}s.
  13499. For example:
  13500. @example
  13501. (set! (car x) 10)
  13502. @end example
  13503. is equivalent to:
  13504. @example
  13505. ((setter car) x 10)
  13506. @end example
  13507. which is equivalent to:
  13508. @example
  13509. (set-car! x 10)
  13510. @end example
  13511. @deffn Procedure setter procedure
  13512. Gets the "setter procedure" associated with a "getter procedure".
  13513. Equivalent to @code{(procedure-property @var{procedure} 'setter)}.
  13514. By convention, a setter procedure takes the same parameters as
  13515. the "getter" procedure, plus an extra parameter that is the
  13516. new value to be stored in the location specified by the parameters.
  13517. The expectation is that following
  13518. @code{((setter @var{proc}) @var{args} ... @var{value})} then
  13519. the value of @code{(@var{proc} @var{args} ...)} will be @var{value}.
  13520. The @code{setter} of @code{setter} can be used to set the
  13521. @code{setter} property.
  13522. For example the Scheme prologue effectively does the following:
  13523. @example
  13524. (set! (setter vector-set) vector-set!)
  13525. @end example
  13526. @end deffn
  13527. Kawa also gives you access to locations as first-class values:
  13528. @deffn Syntax location lvalue
  13529. Returns a location object for the given @var{lvalue}.
  13530. You can get its value (by applying it, as if it were a procedure),
  13531. and you can set its value (by using @code{set!} on the application).
  13532. The @var{lvalue} can be a local or global variable, or a procedure
  13533. call using a procedure that has a @code{setter}.
  13534. @example
  13535. (define x 100)
  13536. (define lx (location x))
  13537. (set! (lx) (cons 1 2)) ;; set x to (1 . 2)
  13538. (lx) ;; returns (1 . 2)
  13539. (define lc (location (car x)))
  13540. (set! (lc) (+ 10 (lc)))
  13541. ;; x is now (11 . 2)
  13542. @end example
  13543. @end deffn
  13544. @deffn Syntax define-alias variable lvalue
  13545. Define @var{variable} as an alias for @var{lvalue}.
  13546. In other words, makes it so that @code{(location @var{variable})}
  13547. is equivalent to @code{(location @var{lvalue})}.
  13548. This works both top-level and inside a function.
  13549. @end deffn
  13550. @deffn Syntax define-private-alias variable lvalue
  13551. Same as @code{define-alias}, but the @var{variable}
  13552. is local to the current module.
  13553. @end deffn
  13554. Some people might find it helpful to think of a location
  13555. as a settable @dfn{thunk}. Others may find it useful to
  13556. think of the @code{location} syntax as similar to the C @samp{&} operator;
  13557. for the @samp{*} indirection operator, Kawa uses procedure application.
  13558. You can use @code{define-alias} to define a shorter type synonym,
  13559. similar to Java's @code{import TypeName} (single-type-import) declaration:
  13560. @example
  13561. (define-alias StrBuf java.lang.StringBuffer)
  13562. @end example
  13563. @node Parameter objects, , Locations, Eval and Environments
  13564. @section Parameter objects
  13565. A parameter object is a procedure that is bound to a location,
  13566. and may optionally have a conversion procedure.
  13567. The procedure accepts zero or one argument.
  13568. When the procedure is called with zero arguments,
  13569. the content of the location is returned.
  13570. On a call with one argument the content of the location
  13571. is updated with the result of applying the parameter object's conversion
  13572. procedure to the argument.
  13573. Parameter objects are created with the @code{make-parameter} procedure
  13574. which takes one or two arguments. The second argument is a one
  13575. argument conversion procedure. If only one argument is passed to
  13576. make-parameter the identity function is used as a conversion
  13577. procedure.
  13578. A new location is created and asociated with the
  13579. parameter object. The initial content of the location is the
  13580. result of applying the conversion procedure to the first argument of
  13581. make-parameter.
  13582. Note that the conversion procedure can be used for guaranteeing the
  13583. type of the parameter object's binding and/or to perform some
  13584. conversion of the value.
  13585. The @code{parameterize} special form, when given a parameter object
  13586. and a value, binds the parameter
  13587. object to a new location for the dynamic extent of its body.
  13588. The initial content of the location is the result of
  13589. applying the parameter object's conversion procedure to the value. The
  13590. @code{parameterize} special form behaves analogously to @code{let}
  13591. when binding more than one parameter object (that is the order of
  13592. evaluation is unspecified and the new bindings are only visible in the
  13593. body of the parameterize special form).
  13594. When a new thread is created using @code{future} or @code{runnable}
  13595. then the child thread inherits initial values from its parent.
  13596. Once the child is running, changing the value in the child does not
  13597. affect the value in the parent or vice versa.
  13598. (In the past this was not the case: The child would share a location
  13599. with the parent except within a @code{parameterize}.
  13600. This was changed to avoid unsafe and inefficient coupling between threads.)
  13601. Note that @code{parameterize} and @code{fluid-let} have similar
  13602. binding and sharing behavior.
  13603. The difference is that @code{fluid-let} modifies locations
  13604. accessed by name, while @code{make-parameter} and @code{parameterize}
  13605. create anonymous locations accessed by calling a parameter procedure.
  13606. The R5RS procedures @code{current-input-port} and @code{current-output-port}
  13607. are parameter objects.
  13608. @deffn Procedure make-parameter init [converter]
  13609. Returns a new parameter object which is bound in the global dynamic
  13610. environment to a location containing the value returned by the call
  13611. @code{(@var{converter} @var{init})}. If the conversion procedure
  13612. converter is not specified the identity function is used instead.
  13613. The parameter object is a procedure which accepts zero or one
  13614. argument. When it is called with no argument, the content of the
  13615. location bound to this parameter object in the current dynamic
  13616. environment is returned. When it is called with one argument, the
  13617. content of the location is set to the result of the call
  13618. @code{(@var{converter} @var{arg})}, where @var{arg} is the argument
  13619. passed to the parameter object, and an unspecified value is returned.
  13620. @example
  13621. (define radix
  13622. (make-parameter 10))
  13623. (define write-shared
  13624. (make-parameter
  13625. #f
  13626. (lambda (x)
  13627. (if (boolean? x)
  13628. x
  13629. (error "only booleans are accepted by write-shared")))))
  13630. (radix) @result{} 10
  13631. (radix 2)
  13632. (radix) @result{} 2
  13633. (write-shared 0) gives an error
  13634. (define prompt
  13635. (make-parameter
  13636. 123
  13637. (lambda (x)
  13638. (if (string? x)
  13639. x
  13640. (with-output-to-string (lambda () (write x)))))))
  13641. (prompt) @result{} "123"
  13642. (prompt ">")
  13643. (prompt) @result{} ">"
  13644. @end example
  13645. @end deffn
  13646. @anchor{parameterize-syntax}
  13647. @deffn Syntax parameterize ((expr1 expr2) ...) @stxref{body}
  13648. The expressions @var{expr1} and @var{expr2} are evaluated in an
  13649. unspecified order. The value of the @var{expr1} expressions must be
  13650. parameter objects. For each @var{expr1} expression and in an
  13651. unspecified order, the local dynamic environment is extended with a
  13652. binding of the parameter object @var{expr1} to a new location whose
  13653. content is the result of the call @code{(@var{converter} @var{val})},
  13654. where @var{val} is the value of @var{expr2} and @var{converter} is the
  13655. conversion procedure of the parameter object. The resulting dynamic
  13656. environment is then used for the evaluation of @var{body} (which
  13657. refers to the R5RS grammar nonterminal of that name). The result(s) of
  13658. the parameterize form are the result(s) of the @var{body}.
  13659. @example
  13660. (radix) @result{} 2
  13661. (parameterize ((radix 16)) (radix)) @result{} 16
  13662. (radix) @result{} 2
  13663. (define (f n) (number->string n (radix)))
  13664. (f 10) @result{} "1010"
  13665. (parameterize ((radix 8)) (f 10)) @result{} "12"
  13666. (parameterize ((radix 8) (prompt (f 10))) (prompt)) @result{} "1010"
  13667. @end example
  13668. @end deffn
  13669. @node Debugging
  13670. @chapter Debugging
  13671. @deffn Syntax trace procedure
  13672. Cause @var{procedure} to be "traced", that is debugging output will
  13673. be written to the standard error port every time @var{procedure}
  13674. is called, with the parameters and return value.
  13675. Note that Kawa will normally assume that a procedure defined with
  13676. the procedure-defining variant of @code{define} is constant,
  13677. and so it might be inlined:
  13678. @example
  13679. (define (ff x) (list x x))
  13680. (trace ff) ;; probably won't work
  13681. (ff 3) ;; not traced
  13682. @end example
  13683. It works if you specify the @code{--no-inline} flag to Kawa.
  13684. Alternatively, you can use the variable-defining variant of @code{define}:
  13685. @example
  13686. #|kawa:1|# (define ff (lambda (x) name: 'ff (list x x)))
  13687. #|kawa:2|# (trace ff) ;; works
  13688. #|kawa:3|# (ff 3)
  13689. call to ff (3)
  13690. return from ff => (3 3)
  13691. (3 3)
  13692. @end example
  13693. Note the use of the @code{name:} procedure property to give the
  13694. anonymous @code{lambda} a name.
  13695. @end deffn
  13696. @deffn Syntax untrace procedure
  13697. Turn off tracing (debugging output) of @var{procedure}.
  13698. @end deffn
  13699. @deffn Procedure disassemble procedure
  13700. Returns a string representation of the disassembled bytecode
  13701. for @var{procedure}, when known.
  13702. @end deffn
  13703. @node Input-Output
  13704. @chapter Input, output, and file handling
  13705. Kawa has a number of useful tools for controlling input and output:
  13706. A programmable reader.
  13707. A powerful pretty-printer.
  13708. @menu
  13709. * Named output formats::
  13710. * Paths:: Paths - file name, URLs, and URIs
  13711. * Files:: File System Interface
  13712. * Reading and writing whole files::
  13713. * Ports::
  13714. * Format:: Formatted Output (Common-Lisp-style)
  13715. * Pretty-printing::
  13716. * Resources::
  13717. @end menu
  13718. @node Named output formats, Paths, , Input-Output
  13719. @section Named output formats
  13720. The @code{--output-format} (or @code{--format}) command-line switch
  13721. can be used to override the default format for how values are
  13722. printed on the standard output. This format is used for values printed
  13723. by the read-eval-print interactive interface. It is also used to
  13724. control how values are printed when Kawa evaluates a file named on the
  13725. command line (using the @code{-f} flag or just a script name).
  13726. (It also affects applications compiled with the @code{--main} flag.)
  13727. It currently affects how values are printed by a @code{load},
  13728. though that may change.
  13729. The default format depends on the current programming language.
  13730. For Scheme, the default is @code{scheme} for read-eval-print
  13731. interaction, and @code{ignore} for files that are loaded.
  13732. The formats currently supported include the following:
  13733. @table @code
  13734. @item scheme
  13735. Values are printed in a format matching the Scheme programming language,
  13736. as if using @code{display}. "Groups" or "elements" are written as lists.
  13737. @item readable-scheme
  13738. Like @code{scheme}, as if using @code{write}:
  13739. Values are generally printed in a way that they can
  13740. be read back by a Scheme reader. For example, strings have quotation marks,
  13741. and character values are written like @samp{#\A}.
  13742. @item elisp
  13743. Values are printed in a format matching the Emacs Lisp programming language.
  13744. Mostly the same as @code{scheme}.
  13745. @item readable-elisp
  13746. Like @code{elisp}, but values are generally printed in a way that they can
  13747. be read back by an Emacs Lisp reader. For example, strings have quotation
  13748. marks, and character values are written like @samp{?A}.
  13749. @item clisp
  13750. @itemx commonlisp
  13751. Values are printed in a format matching the Common Lisp programming language,
  13752. as if written by @code{princ}.
  13753. Mostly the same as @code{scheme}.
  13754. @item readable-clisp
  13755. @itemx readable-commonlisp
  13756. Like @code{clisp}, but as if written by @code{prin1}: values are generally
  13757. printed in a way that they can be read back by a Common Lisp reader.
  13758. For example, strings have quotation marks, and character values are
  13759. written like @samp{#\A}.
  13760. @item xml
  13761. @itemx xhtml
  13762. @itemx html
  13763. Values are printed in XML, XHTML, or HTML format.
  13764. This is discussed in more detail in @ref{Formatting XML}.
  13765. @item cgi
  13766. The output should follow the CGI standards. I.e. assume that this
  13767. script is invoked by a web server as a CGI script/program, and that the
  13768. output should start with some response header,
  13769. followed by the actual response data.
  13770. To generate the response headers, use the @code{response-header} function.
  13771. If the @code{Content-type} response header has not been specified, and
  13772. it is required by the CGI standard, Kawa will attempt
  13773. to infer an appropriate @code{Content-type} depending on the following value.
  13774. @item ignore
  13775. Top-level values are ignored, instead of printed.
  13776. @end table
  13777. @node Paths
  13778. @section Paths - file name, URLs, and URIs
  13779. A @dfn{Path} is the name of a file or some other @dfn{resource}.
  13780. The path mechanism provides a layer of abstraction, so you can
  13781. use the same functions on either a filename or a URL/URI.
  13782. Functions that in standard Scheme take a filename
  13783. have been generalized to take a path or a path string,
  13784. as if using the @code{path} function below. For example:
  13785. @example
  13786. (open-input-file "http://www.gnu.org/index.html")
  13787. (open-input-file (URI "ftp://ftp.gnu.org/README"))
  13788. @end example
  13789. @deffn Type path
  13790. A general path, which can be a @code{filename} or a @code{URI}.
  13791. It can be either a @code{filename} or a @code{URI}.
  13792. Represented using the abstract Java class @code{gnu.kawa.io.Path}.
  13793. Coercing a value to a @code{Path} is equivalent to
  13794. calling the @code{path} constructor documented below.
  13795. @end deffn
  13796. @deffn Constructor path arg
  13797. Coerces the @var{arg} to a @code{path}.
  13798. If @var{arg} is already a @code{path}, it is returned unchanged.
  13799. If @var{arg} is a @code{java.net.URI}, or a @code{java.net.URL}
  13800. then a @code{URI} value is returned.
  13801. If @var{arg} is a @code{java.io.File}, a @code{filepath} value is returned.
  13802. Otherwise, @var{arg} can be a string.
  13803. A @code{URI} value is returned if the string starts with a URI scheme
  13804. (such as @code{"http:"}),
  13805. and a @code{filepath} value is returned otherwise.
  13806. @end deffn
  13807. @deffn Predicate path? arg
  13808. True if @var{arg} is a @code{path} - i.e. an instance of a @code{gnu.kawa.io.Path}.
  13809. @end deffn
  13810. @deffn Procedure current-path [new-value]
  13811. With no arguments, returns the default directory of the current thread
  13812. as a @code{path}.
  13813. This is used as the base directory for relative pathnames.
  13814. The initial value is that of the @code{user.dir} property
  13815. as returned by @code{(java.lang.System:getProperty "user.dir")}.
  13816. If a @var{new-value} argument is given, sets the default directory:
  13817. @example
  13818. (current-path "/opt/myApp/")
  13819. @end example
  13820. A string value is automatically converted to a @code{path},
  13821. normally a @code{filepath}.
  13822. Alternatively, you can change the default using a setter:
  13823. @example
  13824. (set! (current-path) "/opt/myApp/")
  13825. @end example
  13826. Since @code{current-path} is a @ref{Parameter objects,parameter object}, you can
  13827. locally change the value using @ref{parameterize-syntax,@code{parameterize}}.
  13828. @end deffn
  13829. @deffn Type filepath
  13830. The name of a local file.
  13831. Represented using the Java class @code{gnu.kawa.io.FilePath},
  13832. which is a wrapper around @code{java.io.File}.
  13833. @end deffn
  13834. @deffn Predicate filepath? arg
  13835. True if @var{arg} is a @code{filepath} - i.e. an instance of
  13836. a @code{gnu.kawa.io.FilePath}.
  13837. @end deffn
  13838. @anchor{URI-type}
  13839. @deffn Type URI
  13840. A Uniform Resource Indicator, which is a generalization of
  13841. the more familiar URL. The general format is specified by
  13842. @uref{http://www.ietf.org/rfc/rfc2396.txt,
  13843. RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax}.
  13844. Represented using the Java class @code{gnu.kawa.io.URIPath},
  13845. which is a wrapper around @code{java.net.URI}.
  13846. A URI can be a URL, or it be a relative URI.
  13847. @end deffn
  13848. @deffn Predicate URI? arg
  13849. True if @var{arg} is a @code{URI} - i.e. an instance of
  13850. a @code{gnu.kawa.io.URIPath}.
  13851. @end deffn
  13852. @deffn Type URL
  13853. A Uniform Resource Locator - a subtype of @code{URI}.
  13854. Represented using the Java class @code{gnu.kawa.io.URLPath},
  13855. which is a wrapper around a @code{java.net.URL}, in
  13856. addition to extending @code{gnu.kawa.io.URIPath}.
  13857. @end deffn
  13858. @subsection Extracting Path components
  13859. @deffn Procedure path-scheme arg
  13860. Returns the ``URI scheme'' of @var{arg} (coerced to a @code{path}) if it is
  13861. defined, or @code{#f} otherwise. The URI scheme of a @code{filepath}
  13862. is @code{"file"} if the @code{filepath} is absolute, and @code{#f} otherwise.
  13863. @example
  13864. (path-scheme "http://gnu.org/") @result{} "http"
  13865. @end example
  13866. @end deffn
  13867. @deffn Procedure path-authority arg
  13868. Returns the authority part of @var{arg} (coerced to a @code{path}) if it is
  13869. defined, or @code{#f} otherwise.
  13870. The ``authority'' is usually the hostname, but may also include user-info
  13871. or a port-number.
  13872. @example
  13873. (path-authority "http://me@@localhost:8000/home") @result{} "me@@localhost:8000"
  13874. @end example
  13875. @end deffn
  13876. @deffn Procedure path-host arg
  13877. Returns the name name part of @var{arg} (coerced to a @code{path}) if it is
  13878. defined, or @code{#f} otherwise.
  13879. @example
  13880. (path-host "http://me@@localhost:8000/home") @result{} "localhost"
  13881. @end example
  13882. @end deffn
  13883. @deffn Procedure path-user-info arg
  13884. Returns the ``user info'' of @var{arg} (coerced to a @code{path}) if it is
  13885. specified, or @code{#f} otherwise.
  13886. @example
  13887. (path-host "http://me@@localhost:8000/home") @result{} "me"
  13888. @end example
  13889. @end deffn
  13890. @deffn Procedure path-port arg
  13891. Returns the port number of @var{arg} (coerced to a @code{path}) if it is
  13892. specified, or @code{-1} otherwise. Even if there is a default port
  13893. associated with a URI scheme (such as 80 for @code{http}), the value
  13894. -1 is returned unless the port number is @emph{explictly} specified.
  13895. @example
  13896. (path-host "http://me@@localhost:8000/home") @result{} 8000
  13897. (path-host "http://me@@localhost/home") @result{} -1
  13898. @end example
  13899. @end deffn
  13900. @deffn Procedure path-file arg
  13901. Returns the ``path component'' of the @var{arg}
  13902. (coerced to a @code{path}).
  13903. (The name @code{path-path} might be more logical,
  13904. but it is obviously a bit awkward.)
  13905. The path component of a file name is the file name itself.
  13906. For a URI, it is the main hierarchical part of the URI,
  13907. without schema, authority, query, or fragment.
  13908. @example
  13909. (path-file "http://gnu.org/home/me.html?add-bug#body") @result{} "/home/me.html"
  13910. @end example
  13911. @end deffn
  13912. @deffn Procedure path-directory arg
  13913. If @var{arg} (coerced to a @code{path}) is directory,
  13914. return @var{arg}; otherwise return the ``parent'' path, without the
  13915. final component.
  13916. @example
  13917. (path-directory "http://gnu.org/home/me/index.html#body")
  13918. @result{} (path "http://gnu.org/home/me/")
  13919. (path-directory "http://gnu.org/home/me/")
  13920. @result{} (path "http://gnu.org/home/me/")
  13921. @end example
  13922. @code{(path-directory "./dir")} @code{@result{}} @code{(path "./dir")} if @code{dir} is a directory, and @code{(path ".")} otherwise.
  13923. @end deffn
  13924. @deffn Procedure path-parent arg
  13925. Returns the ``parent directory'' of @var{arg} (coerced to a @code{path}).
  13926. If @var{arg} is not a directory, same as @code{path-directory @var{arg}}.
  13927. @example
  13928. (path-parent "a/b/c") @result{} (path "a/b")
  13929. (path-parent "file:/a/b/c") @result{} (path "file:/a/b/c")
  13930. (path-parent "file:/a/b/c/") @result{} (path "file:/a/b/")
  13931. @end example
  13932. @end deffn
  13933. @deffn Procedure path-last arg
  13934. The last component of path component
  13935. of @var{arg} (coerced to a @code{path}).
  13936. Returns a substring of @code{(path-file @var{arg})}.
  13937. If that string ends with @samp{/} or the path separator,
  13938. that last character is ignored.
  13939. Returns the tail of the path-string, following
  13940. the last (non-final) @samp{/} or path separator.
  13941. @example
  13942. (path-last "http:/a/b/c") @result{} "c"
  13943. (path-last "http:/a/b/c/") @result{} "c"
  13944. (path-last "a/b/c") @result{} "c"
  13945. @end example
  13946. @end deffn
  13947. @deffn Procedure path-extension arg
  13948. Returns the ``extension'' of the @var{arg}
  13949. (coerced to a @code{path}).
  13950. @example
  13951. (path-extension "http://gnu.org/home/me.html?add-bug#body") @result{} "html"
  13952. (path-extension "/home/.init") @result{} #f
  13953. @end example
  13954. @end deffn
  13955. @deffn Procedure path-query arg
  13956. Returns the query part of @var{arg} (coerced to a @code{path}) if it is
  13957. defined, or @code{#f} otherwise. The query part of a URI is the
  13958. part after @samp{?}.
  13959. @example
  13960. (path-query "http://gnu.org/home?add-bug") @result{} "add-bug"
  13961. @end example
  13962. @end deffn
  13963. @deffn Procedure path-fragment arg
  13964. Returns the fragment part of @var{arg} (coerced to a @code{path}) if it is
  13965. defined, or @code{#f} otherwise. The fragment of a URI is the
  13966. part of after @samp{#}.
  13967. @example
  13968. (path-query "http://gnu.org/home#top") @result{} "top"
  13969. @end example
  13970. @end deffn
  13971. @deffn Procedure resolve-uri uri base
  13972. Returns a @var{uri} unchanged if it is an absolute URI.
  13973. Otherwise resolves it against a base URI @var{base},
  13974. which is normally (though not always) absolute.
  13975. This uses the algorithm specifyed by RFC-3986 (assuming @var{base}
  13976. is absolute), unlike the obsolete RFC-2396 algorithm used
  13977. by @code{java.net.URI.resolve}.
  13978. @end deffn
  13979. @node Files
  13980. @section File System Interface
  13981. @deffn Procedure file-exists? filename
  13982. Returns true iff the file named @var{filename} actually exists.
  13983. This function is defined on arbitrary @code{path} values:
  13984. for URI values we open a @code{URLConnection}
  13985. and invoke @code{getLastModified()}.
  13986. @end deffn
  13987. @deffn Procedure file-directory? filename
  13988. Returns true iff the file named @var{filename} actually exists
  13989. and is a directory.
  13990. This function is defined on arbitrary @code{path} values;
  13991. the default implementation for non-file objects is to
  13992. return @code{#t} iff the path string ends with the character @samp{/}.
  13993. @end deffn
  13994. @deffn Procedure file-readable? filename
  13995. Returns true iff the file named @var{filename} actually exists
  13996. and can be read from.
  13997. @end deffn
  13998. @deffn Procedure file-writable? filename
  13999. Returns true iff the file named @var{filename} actually exists
  14000. and can be writen to.
  14001. (Undefined if the @var{filename} does not exist,
  14002. but the file can be created in the directory.)
  14003. @end deffn
  14004. @deffn Procedure delete-file filename
  14005. Delete the file named @var{filename}.
  14006. On failure, throws an exception.
  14007. @end deffn
  14008. @deffn Procedure rename-file oldname newname
  14009. Renames the file named @var{oldname} to @var{newname}.
  14010. @end deffn
  14011. @deffn Procedure copy-file oldname newname-from path-to
  14012. Copy the file named @var{oldname} to @var{newname}.
  14013. The return value is unspecified.
  14014. @end deffn
  14015. @deffn Procedure create-directory dirname
  14016. Create a new directory named @var{dirname}.
  14017. Unspecified what happens on error (such as exiting file with the same name).
  14018. (Currently returns @code{#f} on error, but may change to be more compatible
  14019. with scsh.)
  14020. @end deffn
  14021. @deffn Procedure system-tmpdir
  14022. Return the name of the default directory for temporary files.
  14023. @end deffn
  14024. @deffn Procedure make-temporary-file [format]
  14025. Return a file with a name that does not match any existing file.
  14026. Use @var{format} (which defaults to @code{"kawa~d.tmp"}) to generate
  14027. a unique filename in @code{(system-tmpdir)}.
  14028. The implementation is safe from race conditions,
  14029. and the returned filename will not be reused by this JVM.
  14030. @end deffn
  14031. @node Reading and writing whole files
  14032. @section Reading and writing whole files
  14033. The following procedures and syntax allow you to read and write
  14034. the entire contents of a file, without iterating using a port.
  14035. @subsection Reading a file
  14036. For reading the contents of a file in a single operation,
  14037. you can use the following syntax:
  14038. @display
  14039. @stxlit{&<@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}}
  14040. @end display
  14041. This is equivalent to using the @code{path-data} function (defined below):
  14042. @display
  14043. @stxlit{(path-data} @stxlit{&@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{})}
  14044. @end display
  14045. For example:
  14046. @example
  14047. (define dir "/home/me/")
  14048. (define help-message &<@lbracechar{}&[dir]HELP@rbracechar{})
  14049. @end example
  14050. This binds @code{help-message} to the contents of the file
  14051. named @code{HELP} in the @code{dir} directory.
  14052. @anchor{Blobs}
  14053. @subsection Blobs
  14054. The content of a file is, in general, a sequence of uninterpreted bytes.
  14055. Often these bytes represent text in a locale-dependent encoding,
  14056. but we don't always know this. Sometimes they're images, or videos,
  14057. or word-processor documents. A filename extension or a ``magic number''
  14058. in the file can give you hints, but not certainty as to the type of the data.
  14059. A @dfn{@uref{http://en.wikipedia.org/wiki/Binary_large_object,blob}}
  14060. is a raw uninterpreted sequence of bytes. It is a @code{bytevector}
  14061. that can be automatically converted to other types as needed,
  14062. specifically to a string or a bytevector.
  14063. The @code{&<@lbracechar{}..@rbracechar{}} returns a blob. For example,
  14064. assume the file @code{README} contains (bytes representing)
  14065. the text @code{"Check doc directory.\n"}. Then:
  14066. @example
  14067. #|kawa:1|# (define readme &<@lbracechar{}README@rbracechar{}))
  14068. |kawa:2|# readme:class
  14069. class gnu.lists.Blob
  14070. #|kawa:3|# (write (->string readme))
  14071. "Check doc directory.\n"
  14072. #|kawa:4|# (write (->bytevector readme))
  14073. #u8(67 104 101 99 107 32 100 111 99 32 100 105 114 101 99 116 111 114 121 46 10)
  14074. #|kawa:5|# (->bytevector readme):class
  14075. class gnu.lists.U8Vector
  14076. @end example
  14077. @subsection Writing to a file
  14078. The @code{&<@lbracechar{}..@rbracechar{}} syntax can be used with @code{set!}
  14079. to replace the contents of a file:
  14080. @example
  14081. (set! &<@lbracechar{}README@rbracechar{} "Check example.com\n")
  14082. @end example
  14083. The new contents must be blob-compatible - i.e. a bytevector or a string.
  14084. If you dislike using @code{<} as an output operator, you can instead using the @code{&>@lbracechar{}..@rbracechar{}} operation, which evaluates to a function whose single argument is the new value:
  14085. @example
  14086. (&>@lbracechar{}README@rbracechar{} "Check example.com\n")
  14087. @end example
  14088. In general:
  14089. @example
  14090. @stxlit{&>@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}}
  14091. @end example
  14092. is equivalent to:
  14093. @example
  14094. (lambda (new-contents)
  14095. (set! @stxlit{&<@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}} new-contents))
  14096. @end example
  14097. You can use @code{&>>} to append more data to a file:
  14098. @example
  14099. (&>>@lbracechar{}README@rbracechar{} "or check example2.com\n")
  14100. @end example
  14101. @subsection Functions
  14102. @deffn Procedure path-data path
  14103. Reads the contents of the file specified by @var{path},
  14104. where @var{path} can be a @ref{Paths,path} object, or anything that can
  14105. be converted to a @code{Path}, including a filename string or a URL.
  14106. returning the result as a blob.
  14107. The result is a @emph{blob}, which is a kind of bytevector than can be
  14108. auto-converted to a string or bytevecor as required.
  14109. The function @code{path-data} has a setter, which replaces the contents
  14110. with new contents:
  14111. @example
  14112. (set! &<@lbracechar{}file-name@rbracechar{} new-contents)
  14113. @end example
  14114. @end deffn
  14115. @deffn Procedure path-bytes path
  14116. Reads the contents of the file specified by @var{path}, as
  14117. with the @code{path-data} function, but the result is a plain bytevector,
  14118. rather than a blob. This functtion also has a setter, which you
  14119. can use to replace the file-contents by new bytevector-valued data.
  14120. @end deffn
  14121. @node Ports
  14122. @section Ports
  14123. Ports represent input and output devices.
  14124. An input port is a Scheme object that can deliver data upon
  14125. command, while an output port is a Scheme object that can
  14126. accept data.
  14127. Different @dfn{port types} operate on different data:
  14128. @itemize @bullet
  14129. @item
  14130. A @dfn{textual port} supports reading or writing of individual
  14131. characters from or to a backing store containing characters
  14132. using @code{read-char} and @code{write-char} below, and it supports
  14133. operations defined in terms of characters, such as @code{read} and
  14134. @code{write}.
  14135. @item
  14136. A @dfn{binary port} supports reading or writing of individual
  14137. bytes from or to a backing store containing bytes using
  14138. @code{read-u8} and @code{write-u8} below, as well as operations defined
  14139. in terms of bytes (integers in the range 0 to 255).
  14140. All Kawa binary ports created by procedures documented here
  14141. are also textual ports. Thus you can either read/write
  14142. bytes as described above, or read/write
  14143. characters whose scalar value is in the range 0 to 255
  14144. (i.e. the Latin-1 character set), using @code{read-char} and @code{write-char}.
  14145. A native binary port is a @code{java.io.InputStream}
  14146. or @code{java.io.OutputStream} instance. These are not textual ports.
  14147. You can use methods @code{read-u8} and @code{write-u8},
  14148. @c not true?
  14149. but not @code{read-char} and @code{write-char} on native binary ports.
  14150. (The functions @code{input-port?}, @code{output-port?}, @code{binary-port?},
  14151. and @code{port?} all currently return false on native binary ports,
  14152. but that may change.)
  14153. @end itemize
  14154. @deffn Procedure call-with-port port proc
  14155. The @code{call-with-port} procedure calls @var{proc} with port as an
  14156. argument. If @var{proc} returns, then the port is closed automatically
  14157. and the values yielded by the proc are returned.
  14158. If @var{proc} does not return, then the port must not be closed
  14159. automatically unless it is possible to prove that the port
  14160. will never again be used for a read or write operation.
  14161. As a Kawa extension, @var{port} may be any object
  14162. that implements @code{java.io.Closeable}.
  14163. It is an error if @var{proc} does not accept one argument.
  14164. @c @emph{Rationale}: Because Scheme’s escape procedures have unlimited
  14165. @c extent, it is possible to escape from the current continuation
  14166. @c but later to resume it. If implementations were permitted to
  14167. @c close the port on any escape from the current continuation,
  14168. @c then it would be impossible to write portable code using both
  14169. @c call-with-current-continuation and call-with-port.
  14170. @end deffn
  14171. @deffn Procedure call-with-input-file path proc
  14172. @deffnx Procedure call-with-output-file path proc
  14173. These procedures obtain a textual port obtained by
  14174. opening the named file for input or output as if by
  14175. @code{open-input-file} or @code{open-output-file}. The port and
  14176. @var{proc} are then passed to a procedure equivalent to
  14177. @code{call-with-port}.
  14178. It is an error if @var{proc} does not accept one argument.
  14179. @end deffn
  14180. @deffn Procedure input-port? obj
  14181. @deffnx Procedure output-port? obj
  14182. @deffnx Procedure textual-port? obj
  14183. @deffnx Procedure binary-port? obj
  14184. @deffnx Procedure port? obj
  14185. These procedures return @code{#t} if obj is an input port, output port,
  14186. textual port, binary port, or any kind of port,
  14187. respectively. Otherwise they return @code{#f}.
  14188. These procedures currently return @code{#f} on a native Java streams
  14189. (@code{java.io.InputStream} or @code{java.io.OutputStream}),
  14190. a native reader (a @code{java.io.Reader} that is not an
  14191. @code{gnu.mapping.Inport}), or a native writer (a @code{java.io.Writer}
  14192. that is not an @code{gnu.mapping.Outport}). This may change if
  14193. conversions between native ports and Scheme ports becomes more seamless.
  14194. @end deffn
  14195. @deffn Procedure input-port-open? port
  14196. @deffnx Procedure output-port-open? port
  14197. Returns @code{#t} if @var{port} is still open and capable of performing
  14198. input or output, respectively, and @code{#f} otherwise.
  14199. (Not supported for native binary ports - i.e. @code{java.io.InputStteam}
  14200. or @code{java.io.OutputStream}.)
  14201. @end deffn
  14202. @deffn Procedure current-input-port
  14203. @deffnx Procedure current-output-port
  14204. @deffnx Procedure current-error-port
  14205. Returns the current default input port, output port, or
  14206. error port (an output port), respectively.
  14207. (The error port is the port to which errors and warnings should be sent
  14208. - the @dfn{standard error} in Unix and C terminology.)
  14209. These procedures are @ref{Parameter objects,parameter objects},
  14210. which can be overridden with @ref{parameterize-syntax,@code{parameterize}}.
  14211. The initial bindings for @code{(current-output-port)} and
  14212. @code{(current-error-port)} are hybrid textual/binary
  14213. ports that wrap the values of the corresponding @code{java.lang.System} fields
  14214. @code{out}, and @code{err}. The latter, in turn are bound
  14215. to the standard output and error streams of the JVM process.
  14216. This means you can write binary data to standard output
  14217. using @code{write-bytevector} and @code{write-u8}.
  14218. The initial value @code{(current-input-port)} similarly is a textual port
  14219. that wraps the @code{java.lang.System} field @code{in}, which is bound
  14220. to the standard input stream of the JVM process.
  14221. It is a @emph{hybrid} textual/binary port only if there
  14222. is no console (as determined by @code{(java.lang.System:console)}
  14223. returning @code{#!null}) - i.e. if standard input is not a tty.
  14224. Here is an example that copies standard input to standard output:
  14225. @example
  14226. (let* ((in (current-input-port))
  14227. (out (current-output-port))
  14228. (blen ::int 2048)
  14229. (buf (make-bytevector blen)))
  14230. (let loop ()
  14231. (define n (read-bytevector! buf in))
  14232. (cond ((not (eof-object? n))
  14233. (write-bytevector buf out 0 n)
  14234. (loop)))))
  14235. @end example
  14236. @end deffn
  14237. @deffn Procedure with-input-from-file path thunk
  14238. @deffnx Procedure with-output-to-file path thunk
  14239. The file is opened for input or output as if by
  14240. @code{open-input-file} or @code{open-output-file}, and the new port
  14241. is made to be the value returned by @code{current-input-port}
  14242. or @code{current-output-port} (as used by @code{(read)},
  14243. @code{(write @var{obj})}, and so forth). The thunk is then called with no
  14244. arguments. When the @var{thunk} returns, the port is closed
  14245. and the previous default is restored. It is an error if @var{thunk}
  14246. does not accept zero arguments. Both procedures return
  14247. the values yielded by @var{thunk}. If an escape procedure is used
  14248. to escape from the continuation of these procedures, they
  14249. behave exactly as if the current input or output port had
  14250. been bound dynamically with @code{parameterize}.
  14251. @end deffn
  14252. @deffn Procedure open-input-file path
  14253. @deffnx Procedure open-binary-input-file path
  14254. Takes a @var{path} naming an existing file and returns a textual
  14255. input port or binary input port that is capable of delivering
  14256. data from the file.
  14257. @c If the file does not exist or cannot be
  14258. @c opened, an error that satisfies file-error? is signaled.
  14259. The procedure @code{open-input-file} checks the fluid variable
  14260. @ref{port-char-encoding,@code{port-char-encoding}} to determine how bytes are decoded
  14261. into characters. The procedure @code{open-binary-input-file}
  14262. is equivalent to calling @code{open-input-file} with
  14263. @code{port-char-encoding} set to @code{#f}.
  14264. @end deffn
  14265. @deffn Procedure open-output-file path
  14266. @deffnx Procedure open-binary-output-file path
  14267. Takes a @var{path} naming an output file to be created and returns
  14268. respectively a textual output port or binary output port that is
  14269. capable of writing data to a new file by that name. If a
  14270. file with the given name already exists, the effect is unspecified.
  14271. @c If the file cannot be opened, an error that satisfies
  14272. @c file-error? is signaled.
  14273. The procedure @code{open-output-file} checks the fluid variable
  14274. @ref{port-char-encoding,@code{port-char-encoding}} to determine how characters are
  14275. encoded as bytes. The procedure @code{open-binary-output-file}
  14276. is equivalent to calling @code{open-output-file} with
  14277. @code{port-char-encoding} set to @code{#f}.
  14278. @end deffn
  14279. @deffn Procedure close-port port
  14280. @deffnx Procedure close-input-port port
  14281. @deffnx Procedure close-output-port port
  14282. Closes the resource associated with @var{port}, rendering the port
  14283. incapable of delivering or accepting data. It is an error to
  14284. apply the last two procedures to a port which is not an
  14285. input or output port, respectively.
  14286. (Specifically, @code{close-input-port} requires a @code{java.io.Reader},
  14287. while @code{close-output-port} requires a @code{java.io.Writer}.
  14288. In contrast @code{close-port} accepts any object whose class
  14289. implements @code{java.io.Closeable}.)
  14290. @c Scheme implementations may provide ports which are simultaneously input
  14291. @c and output ports, such as sockets; the close-input-port
  14292. @c and close-output-port procedures can then be used to
  14293. @c close the input and output sides of the port independently.
  14294. These routines have no effect if the port has already been
  14295. closed.
  14296. @end deffn
  14297. @subsection String and bytevector ports
  14298. @deffn Procedure open-input-string string
  14299. Takes a string and returns a text input port that delivers characters
  14300. from the string. The port can be closed by @code{close-input-port},
  14301. though its storage will be reclaimed by the
  14302. garbage collector if it becomes inaccessible.
  14303. @example
  14304. (define p
  14305. (open-input-string "(a . (b c . ())) 34"))
  14306. (input-port? p) @result{} #t
  14307. (read p) @result{} (a b c)
  14308. (read p) @result{} 34
  14309. (eof-object? (peek-char p)) @result{} #t
  14310. @end example
  14311. @end deffn
  14312. @deffn Procedure open-output-string
  14313. Returns an textual output port that will accumulate characters
  14314. for retrieval by @code{get-output-string}.
  14315. The port can be closed by the procedure @code{close-output-port},
  14316. though its storage will be reclaimed by the garbage collector
  14317. if it becomes inaccessible.
  14318. @example
  14319. (let ((q (open-output-string))
  14320. (x '(a b c)))
  14321. (write (car x) q)
  14322. (write (cdr x) q)
  14323. (get-output-string q)) @result{} "a(b c)"
  14324. @end example
  14325. @end deffn
  14326. @deffn Procedure get-output-string output-port
  14327. Given an output port created by @code{open-output-string},
  14328. returns a string consisting of the characters that have been
  14329. output to the port so far in the order they were output.
  14330. If the result string is modified, the effect is unspecified.
  14331. @example
  14332. (parameterize
  14333. ((current-output-port (open-output-string)))
  14334. (display "piece")
  14335. (display " by piece ")
  14336. (display "by piece.")
  14337. (newline)
  14338. (get-output-string (current-output-port)))
  14339. @result{} "piece by piece by piece.\n"
  14340. @end example
  14341. @end deffn
  14342. @deffn Procedure call-with-input-string string proc
  14343. Create an input port that gets its data from @var{string},
  14344. call @var{proc} with that port as its one argument, and return
  14345. the result from the call of @var{proc}
  14346. @end deffn
  14347. @deffn Procedure call-with-output-string proc
  14348. Create an output port that writes its data to a @var{string},
  14349. and call @var{proc} with that port as its one argument.
  14350. Return a string consisting of the data written to the port.
  14351. @end deffn
  14352. @deffn Procedure open-input-bytevector bytevector
  14353. Takes a bytevector and returns a binary input port that
  14354. delivers bytes from the bytevector.
  14355. @end deffn
  14356. @deffn Procedure open-output-bytevector
  14357. Returns a binary output port that will accumulate bytes
  14358. for retrieval by @code{get-output-bytevector}.
  14359. @end deffn
  14360. @deffn Procedure get-output-bytevector port
  14361. Returns a bytevector consisting of the bytes that have been
  14362. output to the port so far in the order they were output.
  14363. It is an error if @var{port} was not created with @code{open-output-bytevector}.
  14364. @end deffn
  14365. @subsection Input
  14366. If @var{port} is omitted from any input procedure, it defaults
  14367. to the value returned by @code{(current-input-port)}. It is an
  14368. error to attempt an input operation on a closed port.
  14369. @deffn Procedure read [port]
  14370. The @code{read} procedure converts external representations of
  14371. Scheme objects into the objects themselves. That is, it is
  14372. a parser for the non-terminal @stxref{datum}.
  14373. It returns the next object parsable from the
  14374. given textual input port, updating port to point to the
  14375. first character past the end of the external representation
  14376. of the object.
  14377. If an end of file is encountered in the input before any
  14378. characters are found that can begin an object, then an
  14379. end-of-file object is returned. The port remains open, and
  14380. further attempts to read will also return an end-of-file object.
  14381. If an end of file is encountered after the beginning of
  14382. an object’s external representation, but the external representation
  14383. is incomplete and therefore not parsable, an error
  14384. that satisfies @code{read-error?} is signaled.
  14385. @end deffn
  14386. @deffn Procedure read-char [port]
  14387. Returns the next character available from the textual input
  14388. @var{port}, updating the port to point to the following character.
  14389. If no more characters are available, an end-of-file value is
  14390. returned.
  14391. The result type is @code{character-or-eof}.
  14392. @end deffn
  14393. @deffn Procedure peek-char [port]
  14394. Returns the next character available from the textual input @var{port},
  14395. but @emph{without} updating the port to point to the
  14396. following character. If no more characters are available, an
  14397. end-of-file value is returned.
  14398. The result type is @code{character-or-eof}.
  14399. @emph{Note:} The value returned by a call to @code{peek-char} is the same as
  14400. the value that would have been returned by a call to @code{read-char}
  14401. with the same @var{port}. The only difference is that the very next call
  14402. to @code{read-char} or @code{peek-char} on that @var{port} will return the
  14403. value returned by the preceding call to @code{peek-char}. In particular, a
  14404. call to @code{peek-char} on an interactive port will hang waiting for
  14405. input whenever a call to @code{read-char} would have hung.
  14406. @end deffn
  14407. @deffn Procedure read-line [port [handle-newline]]
  14408. Reads a line of input from the textual input @var{port}.
  14409. The @var{handle-newline} parameter determines what is done with
  14410. terminating end-of-line delimiter.
  14411. The default, @code{'trim}, ignores the delimiter;
  14412. @code{'peek} leaves the delimiter in the input stream;
  14413. @code{'concat} appends the delimiter to the returned value;
  14414. and @code{'split} returns the delimiter as a second value.
  14415. You can use the last three options to tell if the string was
  14416. terminated by end-or-line or by end-of-file.
  14417. If an end of file is encountered before any end of
  14418. line is read, but some characters have been read, a string
  14419. containing those characters is returned.
  14420. (In this case, @code{'trim}, @code{'peek}, and @code{'concat}
  14421. have the same result and effect. The @code{'split} case returns two
  14422. values: The characters read, and the delimiter is an empty string.)
  14423. If an end of file is encountered before any characters are read,
  14424. an end-of-file object is returned.
  14425. For the purpose of this procedure, an
  14426. end of line consists of either a linefeed character, a carriage
  14427. return character, or a sequence of a carriage return character
  14428. followed by a linefeed character.
  14429. @end deffn
  14430. @deffn Procedure eof-object? obj
  14431. Returns @code{#t} if @var{obj} is an end-of-file object,
  14432. otherwise returns @code{#f}.
  14433. @code{Performance note}: If @var{obj} has type @code{character-or-eof},
  14434. this is compiled as an @code{int} comparison with -1.
  14435. @end deffn
  14436. @deffn Procedure eof-object
  14437. Returns an end-of-file object.
  14438. @end deffn
  14439. @deffn Procedure char-ready? [port]
  14440. Returns @code{#t} if a character is ready on the textual input
  14441. @var{port} and returns @code{#f} otherwise. If char-ready returns @code{#t}
  14442. then the next @code{read-char} operation on the given @var{port} is
  14443. guaranteed not to hang. If the port is at end of file then
  14444. @code{char-ready?} returns @code{#t}.
  14445. @emph{Rationale:} The @code{char-ready?} procedure exists to make it
  14446. possible for a program to accept characters from interactive ports
  14447. without getting stuck waiting for input. Any input editors as-
  14448. sociated with such ports must ensure that characters whose
  14449. existence has been asserted by @code{char-ready?} cannot be removed
  14450. from the input. If @code{char-ready?} were to return @code{#f} at end of
  14451. file, a port at end-of-file would be indistinguishable from an
  14452. interactive port that has no ready characters.
  14453. @end deffn
  14454. @deffn Procedure read-string k [port]
  14455. Reads the next @var{k} characters, or as many as are available
  14456. before the end of file, from the textual input @var{port} into a
  14457. newly allocated string in left-to-right order and returns the
  14458. string. If no characters are available before the end of file,
  14459. an end-of-file object is returned.
  14460. @end deffn
  14461. @deffn Procedure read-u8 [port]
  14462. Returns the next byte available from the binary input @var{port},
  14463. updating the @var{port} to point to the following byte. If no more
  14464. bytes are available, an end-of-file object is returned.
  14465. @end deffn
  14466. @deffn Procedure peek-u8 [port]
  14467. Returns the next byte available from the binary input @var{port},
  14468. but @emph{without} updating the @var{port} to point to the following byte.
  14469. If no more bytes are available, an end-of-file object is returned.
  14470. @end deffn
  14471. @deffn Procedure u8-ready? [port]
  14472. Returns @code{#t} if a byte is ready on the binary input @var{port} and
  14473. returns @code{#f} otherwise. If @code{u8-ready?} returns @code{#t} then the
  14474. next @code{read-u8} operation on the given port is guaranteed
  14475. not to hang. If the port is at end of file then @code{u8-ready?}
  14476. returns @code{#t}.
  14477. @end deffn
  14478. @deffn Procedure read-bytevector k [port]
  14479. Reads the next @var{k} bytes, or as many as are available before
  14480. the end of file, from the binary input @var{port} into a newly
  14481. allocated bytevector in left-to-right order and returns the
  14482. bytevector. If no bytes are available before the end of file,
  14483. an end-of-file object is returned.
  14484. @end deffn
  14485. @deffn Procedure read-bytevector! bytevector [port [start [end]]]
  14486. Reads the next @var{end} − @var{start} bytes, or as many as are
  14487. available before the end of file, from the binary input @var{port}
  14488. into @var{bytevector} in left-to-right order beginning at the @var{start}
  14489. position. If @var{end} is not supplied, reads until the end of
  14490. @var{bytevector} has been reached. If @var{start} is not supplied, reads
  14491. beginning at position 0. Returns the number of bytes read.
  14492. If no bytes are available, an end-of-file object is returned.
  14493. @end deffn
  14494. @subsection Output
  14495. If @var{port} is omitted from any output procedure, it defaults
  14496. to the value returned by @code{(current-output-port)}. It is an
  14497. error to attempt an output operation on a closed port.
  14498. The return type of these methods is @code{void}.
  14499. @deffn Procedure write obj [port]
  14500. Writes a representation of @var{obj} to the given textual output
  14501. @var{port}. Strings that appear in the written representation
  14502. are enclosed in quotation marks, and within those strings
  14503. backslash and quotation mark characters are escaped by
  14504. backslashes.
  14505. Symbols that contain non-ASCII characters
  14506. are escaped with vertical lines.
  14507. Character objects are written using the @code{#\} notation.
  14508. If @var{obj} contains cycles which would cause an infinite loop
  14509. using the normal written representation, then at least the
  14510. objects that form part of the cycle must be represented
  14511. using @ref{datum labels}. Datum
  14512. labels must not be used if there are no cycles.
  14513. @end deffn
  14514. @deffn Procedure write-shared obj [port]
  14515. The @code{write-shared} procedure is the same as @code{write}, except
  14516. that shared structure must be represented using datum
  14517. labels for all pairs and vectors that appear more than once
  14518. in the output.
  14519. @end deffn
  14520. @deffn Procedure write-simple obj [port]
  14521. The @code{write-simple} procedure is the same as @code{write}, except
  14522. that shared structure is never represented using datum labels.
  14523. This can cause write-simple not to terminate if @var{obj}
  14524. contains circular structure.
  14525. @end deffn
  14526. @deffn Procedure display obj [port]
  14527. Writes a representation of @var{obj} to the given textual output
  14528. port. Strings that appear in the written representation
  14529. are output as if by @code{write-string} instead of by @code{write}.
  14530. Symbols are not escaped. Character objects appear in the
  14531. representation as if written by @code{write-char} instead of by
  14532. @code{write}.
  14533. The @code{display} representation of other objects is unspecified.
  14534. @c However, display must always terminate. Thus if the normal write
  14535. @c representation is used, datum labels are needed
  14536. @c to represent cycles as in write.
  14537. @end deffn
  14538. @deffn Procedure newline [port]
  14539. Writes an end of line to textual output @var{port}.
  14540. This is done using the @code{println} method
  14541. of the Java class @code{java.io.PrintWriter}.
  14542. @end deffn
  14543. @deffn Procedure write-char char [port]
  14544. Writes the character @var{char} (not an external representation
  14545. of the character) to the given textual output @var{port}.
  14546. @end deffn
  14547. @deffn Procedure write-string string [port [start [end]]]
  14548. Writes the characters of @var{string} from @var{start} to @var{end}
  14549. in left-to-right order to the textual output @var{port}.
  14550. @end deffn
  14551. @deffn Procedure write-u8 byte [port]
  14552. Writes the @var{byte} to the given binary output port.
  14553. @end deffn
  14554. @deffn Procedure write-bytevector bytevector [port [start [end]]]
  14555. Writes the bytes of @var{bytevector} from @var{start} to @var{end}
  14556. in left-to-right order to the binary output @var{port}.
  14557. @end deffn
  14558. @deffn Procedure flush-output-port [port]
  14559. @deffnx Procedure force-output [port]
  14560. Forces any pending output on @var{port} to be delivered to the output file or
  14561. device and returns an unspecified value. If the @var{port} argument is
  14562. omitted it defaults to the value returned by @code{(current-output-port)}.
  14563. (The name @code{force-output} is older,
  14564. while R6RS added @code{flush-output-port}. They have the same effect.)
  14565. @end deffn
  14566. @anchor{Prompts}
  14567. @cindex prompts
  14568. @subsection Prompts for interactive consoles (REPLs)
  14569. When an interactive input port is used for a read-eval-print-loop (REPL
  14570. or console) it is traditional for the REPL to print a short
  14571. @dfn{prompt} string to signal that the user is expected to type
  14572. an expression. These prompt strings can be customized.
  14573. @anchor{input-prompt1}
  14574. @defvar input-prompt1
  14575. @defvarx input-prompt2
  14576. These are fluid variable whose values are string templates
  14577. with placeholders similar to @code{printf}-style format.
  14578. The placeholders are expanded (depending on the current state),
  14579. and the resulting string printed in front of the input line.
  14580. The @code{input-prompt1} is used normally. For multi-line input commands
  14581. (for example if the first line is incomplete), @code{input-prompt1}
  14582. is used for the first line of each command, while @code{input-prompt2} is
  14583. used for subsequent ``continuation'' lines.
  14584. The following placeholders are handled:
  14585. @table @asis
  14586. @item @stxlit{%%}
  14587. A literal @samp{%}.
  14588. @item @stxlit{%N}
  14589. The current line number. This is @code{(+ 1 (port-line @var{port}))}.
  14590. @item @stxlit{%}@var{n}@stxlit{P}@var{c}
  14591. Insert padding at this possion, repeating the following
  14592. character @code{@var{c}} as needed to bring the total number of columns
  14593. of the prompt to that specified by the digits @code{@var{n}}.
  14594. @item @stxlit{%P}@var{c}
  14595. Same as @code{%@var{n}P@var{c}}, but @code{@var{n}} defaults to the number
  14596. of columns in the initial prompt from the expansion of @code{input-prompt1}.
  14597. This is only meaningful when expanding @code{input-prompt2} for
  14598. continuation lines.
  14599. @item @stxlit{%}@stxlitlbrace{}@var{hidden}@stxlit{%@}}
  14600. Same as @var{hidden}, but the characters of @var{hidden}
  14601. are assumed to have zero visible width. Can be used for
  14602. @uref{https://en.wikipedia.org/wiki/ANSI_escape_code,ANSI escape sequences}
  14603. to change color or style:
  14604. @example
  14605. (set! input-prompt1 "%@{\e[48;5;51m%@}@{Kawa:%N@} %@{\e[0m%@}")
  14606. @end example
  14607. The above changes both the text and the background color
  14608. (to a pale blue).
  14609. @item @stxlit{%H}@var{c}@var{d}
  14610. If running under DomTerm, use the characters @var{c} and @var{d} as a clickable
  14611. mini-button to hide/show (fold) the command and its output.
  14612. (When output is visible @var{c} is displayed; clicking on it hides the output.
  14613. When output is hidden @var{d} is displayed; clicking on it shows the output.)
  14614. Ignored if not running under DomTerm.
  14615. @item @stxlit{%M}
  14616. Insert a ``message'' string.
  14617. Not normally used by Kawa, but supported by JLine.
  14618. @end table
  14619. These variables can be initialized by the command-line
  14620. arguments @code{console:prompt1=@var{prompt1}} and
  14621. @code{console:prompt2=@var{prompt2}}, respectively. If these are
  14622. not specified, languages-specific defaults are used.
  14623. For example for Scheme the default value of @code{input-prompt1}
  14624. is @code{"#|%H▼▶kawa:%N|# "} and @code{input-prompt2} is @code{"#|%P.%N| "}.
  14625. These have the form of Scheme comments, to make it easier to cut-and-paste.
  14626. If @code{input-prompt1} (respectively @code{input-prompt2}) does not contain
  14627. an escape sequence (either @code{"%@{} or the escape character @code{"\e"})
  14628. then ANSI escape sequences are added to to highlight the prompt.
  14629. (Under DomTerm this sets the @code{prompt} style, which can be customised
  14630. with CSS but defaults to a light green background;
  14631. if using JLine the background is set to light green.)
  14632. @end defvar
  14633. For greater flexibility, you can also set a prompter procedure.
  14634. @deffn Procedure set-input-port-prompter! port prompter
  14635. Set the prompt procedure associated with @var{port} to @var{prompter},
  14636. which must be a one-argument procedure taking an input port,
  14637. and returning a string.
  14638. The procedure is called before reading the first line of a command;
  14639. its return value is used as the first-line prompt.
  14640. The prompt procedure can have side effects.
  14641. In Bash shell terms: It combines the features of @code{PROMPT_COMMAND}
  14642. and @code{PS1}.
  14643. The initial @var{prompter} is @code{default-prompter},
  14644. which returns the expansion of @code{input-prompt1}.
  14645. @end deffn
  14646. @deffn Procedure input-port-prompter port
  14647. Get the prompt procedure associated with @var{port}.
  14648. @end deffn
  14649. @deffn Procedure default-prompter port
  14650. The default prompt procedure.
  14651. Normally (i.e. when @code{input-port-read-state} is a space)
  14652. returns @code{input-prompt1} after expanding the @code{%}-placeholders.
  14653. Can also expand @code{input-prompt2} when @code{input-port-read-state}
  14654. is not whitespace.
  14655. @end deffn
  14656. @subsection Line numbers and other input port properties
  14657. @deffn Function port-column input-port
  14658. @deffnx Function port-line input-port
  14659. Return the current column number or line number of @var{input-port},
  14660. using the current input port if none is specified.
  14661. If the number is unknown, the result is @code{#f}. Otherwise,
  14662. the result is a 0-origin integer - i.e. the first character
  14663. of the first line is line 0, column 0. (However, when you
  14664. display a file position, for example in an error message,
  14665. we recommend you add 1 to get 1-origin integers. This is
  14666. because lines and column numbers traditionally start with
  14667. 1, and that is what non-programmers will find most natural.)
  14668. @end deffn
  14669. @deffn Procedure set-port-line! port line
  14670. Set (0-origin) line number of the current line of @var{port} to @var{num}.
  14671. @end deffn
  14672. @deffn Procedure input-port-line-number port
  14673. Get the line number of the current line of @var{port},
  14674. which must be a (non-binary) input port.
  14675. The initial line is line 1.
  14676. Deprecated; replaced by @code{(+ 1 (port-line @var{port}))}.
  14677. @end deffn
  14678. @deffn Procedure set-input-port-line-number! port num
  14679. Set line number of the current line of @var{port} to @var{num}.
  14680. Deprecated; replaced by @code{(set-port-line! @var{port} (- @var{num} 1))}.
  14681. @end deffn
  14682. @deffn Procedure input-port-column-number port
  14683. Get the column number of the current line of @var{port},
  14684. which must be a (non-binary) input port.
  14685. The initial column is column 1.
  14686. Deprecated; replaced by @code{(+ 1 (port-column @var{port}))}.
  14687. @end deffn
  14688. @deffn Procedure input-port-read-state port
  14689. Returns a character indicating the current @code{read} state of the @var{port}.
  14690. Returns @code{#\Return} if not current doing a @var{read},
  14691. @code{#\"} if reading a string; @code{#\|} if reading a comment; @code{#\(}
  14692. if inside a list; and @code{#\Space} when otherwise in a @code{read}.
  14693. The result is intended for use by prompt prcedures, and is not necessarily
  14694. correct except when reading a new-line.
  14695. @end deffn
  14696. @defvar symbol-read-case
  14697. A symbol that controls how @code{read} handles letters when reading a symbol.
  14698. If the first letter is @samp{U}, then letters in symbols are upper-cased.
  14699. If the first letter is @samp{D} or @samp{L}, then letters
  14700. in symbols are down-cased.
  14701. If the first letter is @samp{I}, then the case of letters in symbols
  14702. is inverted.
  14703. Otherwise (the default), the letter is not changed.
  14704. (Letters following a @samp{\} are always unchanged.)
  14705. The value of @code{symbol-read-case} only checked
  14706. when a reader is created, not each time a symbol is read.
  14707. @end defvar
  14708. @subsection Miscellaneous
  14709. @anchor{port-char-encoding}
  14710. @defvar port-char-encoding
  14711. Controls how bytes in external files are converted to/from internal
  14712. Unicode characters. Can be either a symbol or a boolean.
  14713. If @code{port-char-encoding} is @code{#f}, the file is assumed
  14714. to be a binary file and no conversion is done.
  14715. Otherwise, the file is a text file. The default is @code{#t}, which
  14716. uses a locale-dependent conversion. If @code{port-char-encoding}
  14717. is a symbol, it must be the name of a character encoding known to Java.
  14718. For all text files (that is if @code{port-char-encoding} is not @code{#f}),
  14719. on input a @code{#\Return} character or
  14720. a @code{#\Return} followed by @code{#\Newline}
  14721. are converted into plain @code{#\Newline}.
  14722. This variable is checked when the file is opened; not when actually
  14723. reading or writing. Here is an example of how you can safely
  14724. change the encoding temporarily:
  14725. @example
  14726. (define (open-binary-input-file name)
  14727. (fluid-let ((port-char-encoding #f)) (open-input-file name)))
  14728. @end example
  14729. @end defvar
  14730. @defvar *print-base*
  14731. The number base (radix) to use by default when printing rational numbers.
  14732. Must be an integer between 2 and 36, and the default is of course 10.
  14733. For example setting @code{*print-base*} to 16 produces hexadecimal output.
  14734. @end defvar
  14735. @defvar *print-radix*
  14736. If true, prints an indicator of the radix used when printing rational numbers.
  14737. If @code{*print-base*} is respectively 2, 8, or 16, then
  14738. @code{#b}, @code{#o} or @code{#x} is written before the number;
  14739. otherwise @code{#@var{N}r} is written, where @code{@var{N}} is the base.
  14740. An exception is when @code{*print-base*} is 10, in which case a period
  14741. is written @emph{after} the number, to match Common Lisp; this may
  14742. be inappropriate for Scheme, so is likely to change.
  14743. @end defvar
  14744. @defvar *print-right-margin*
  14745. The right margin (or line width) to use when pretty-printing.
  14746. @end defvar
  14747. @defvar *print-miser-width*
  14748. If this an integer, and the available width is less or equal to this value,
  14749. then the pretty printer switch to the more @dfn{miser} compact style.
  14750. @end defvar
  14751. @defvar *print-xml-indent*
  14752. When writing to XML, controls pretty-printing and indentation.
  14753. If the value is @code{'always} or @code{'yes} force each element to
  14754. start on a new suitably-indented line.
  14755. If the value is @code{'pretty} only force new lines for elements that
  14756. won't fit completely on a line.
  14757. The the value is @code{'no} or unset, don't add extra whitespace.
  14758. @end defvar
  14759. @node Format, , Ports, Input-Output
  14760. @section Formatted Output (Common-Lisp-style)
  14761. @deffn Procedure format destination fmt . arguments
  14762. An almost complete implementation of Common LISP format description
  14763. according to the CL reference book @cite{Common LISP} from Guy L.
  14764. Steele, Digital Press. Backward compatible to most of the available
  14765. Scheme format implementations.
  14766. Returns @code{#t}, @code{#f} or a string; has side effect of printing
  14767. according to @var{fmt}. If @var{destination} is @code{#t},
  14768. the output is to the current output port and @code{#!void} is returned. If
  14769. @var{destination} is @code{#f}, a formatted string is returned as the
  14770. result of the call. If @var{destination} is a string,
  14771. @var{destination} is regarded as the format string; @var{fmt} is
  14772. then the first argument and the output is returned as a string. If
  14773. @var{destination} is a number, the output is to the current error port
  14774. if available by the implementation. Otherwise @var{destination} must be
  14775. an output port and @code{#!void} is returned.@refill
  14776. @var{fmt} must be a string or an instance of @code{gnu.text.MessageFormat}
  14777. or @code{java.text.MessageFormat}. If @var{fmt} is a string,
  14778. it is parsed as if by @code{parse-format}.
  14779. @end deffn
  14780. @deffn Procedure parse-format format-string
  14781. Parses @code{format-string}, which is a string of the form of a Common LISP
  14782. format description. Returns an instance of @code{gnu.text.ReportFormat},
  14783. which can be passed to the @code{format} function.
  14784. @end deffn
  14785. A format string passed to @code{format} or @code{parse-format}
  14786. consists of format directives (that start with @samp{~}),
  14787. and regular characters (that are written directly to the destination).
  14788. Most of the Common Lisp (and Slib) format directives are implemented.
  14789. Neither justification, nor pretty-printing are supported yet.
  14790. Plus of course, we need documentation for @code{format}!
  14791. @subsection Implemented CL Format Control Directives
  14792. Documentation syntax: Uppercase characters represent the corresponding
  14793. control directive characters. Lowercase characters represent control
  14794. directive parameter descriptions.
  14795. @table @asis
  14796. @cindex ~a
  14797. @item @code{~A}
  14798. Any (print as @code{display} does).
  14799. @table @asis
  14800. @item @code{~@@A}
  14801. left pad.
  14802. @item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}A}
  14803. full padding.
  14804. @end table
  14805. @cindex ~s
  14806. @item @code{~S}
  14807. S-expression (print as @code{write} does).
  14808. @table @asis
  14809. @item @code{~@@S}
  14810. left pad.
  14811. @item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}S}
  14812. full padding.
  14813. @end table
  14814. @cindex ~c
  14815. @item @code{~C}
  14816. Character.
  14817. @table @asis
  14818. @item @code{~@@C}
  14819. prints a character as the reader can understand it (i.e. @code{#\} prefixing).
  14820. @item @code{~:C}
  14821. prints a character as emacs does (eg. @code{^C} for ASCII 03).
  14822. @end table
  14823. @end table
  14824. @subsection Formatting Integers
  14825. @table @asis
  14826. @cindex ~d
  14827. @item @code{~D}
  14828. Decimal.
  14829. @table @asis
  14830. @item @code{~@@D}
  14831. print number sign always.
  14832. @item @code{~:D}
  14833. print comma separated.
  14834. @item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}D}
  14835. padding.
  14836. @end table
  14837. @cindex ~x
  14838. @item @code{~X}
  14839. Hexadecimal.
  14840. @table @asis
  14841. @item @code{~@@X}
  14842. print number sign always.
  14843. @item @code{~:X}
  14844. print comma separated.
  14845. @item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}X}
  14846. padding.
  14847. @end table
  14848. @cindex ~o
  14849. @item @code{~O}
  14850. Octal.
  14851. @table @asis
  14852. @item @code{~@@O}
  14853. print number sign always.
  14854. @item @code{~:O}
  14855. print comma separated.
  14856. @item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}O}
  14857. padding.
  14858. @end table
  14859. @cindex ~b
  14860. @item @code{~B}
  14861. Binary.
  14862. @table @asis
  14863. @item @code{~@@B}
  14864. print number sign always.
  14865. @item @code{~:B}
  14866. print comma separated.
  14867. @item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}B}
  14868. padding.
  14869. @end table
  14870. @cindex ~r
  14871. @item @code{~@var{n}R}
  14872. Radix @var{n}.
  14873. @table @asis
  14874. @item @code{~@var{n},@var{mincol},@var{padchar},@var{commachar},@var{commawidth}R}
  14875. padding.
  14876. @end table
  14877. @item @code{~@@R}
  14878. print a number as a Roman numeral.
  14879. @item @code{~:@@R}
  14880. print a number as an ``old fashioned'' Roman numeral.
  14881. @item @code{~:R}
  14882. print a number as an ordinal English number.
  14883. @item @code{~R}
  14884. print a number as a cardinal English number.
  14885. @cindex ~p
  14886. @item @code{~P}
  14887. Plural.
  14888. @table @asis
  14889. @item @code{~@@P}
  14890. prints @code{y} and @code{ies}.
  14891. @item @code{~:P}
  14892. as @code{~P but jumps 1 argument backward.}
  14893. @item @code{~:@@P}
  14894. as @code{~@@P but jumps 1 argument backward.}
  14895. @end table
  14896. @end table
  14897. @var{commawidth} is the number of characters between two comma characters.
  14898. @subsection Formatting real numbers
  14899. @table @asis
  14900. @cindex ~f
  14901. @item @code{~F}
  14902. Fixed-format floating-point (prints a flonum like @var{mmm.nnn}).
  14903. @table @asis
  14904. @item @code{~@var{width},@var{digits},@var{scale},@var{overflowchar},@var{padchar}F}
  14905. @item @code{~@@F}
  14906. If the number is positive a plus sign is printed.
  14907. @end table
  14908. @end table
  14909. @table @asis
  14910. @cindex ~e
  14911. @item @code{~E}
  14912. Exponential floating-point (prints a flonum like @var{mmm.nnn}@code{E}@var{ee})
  14913. @table @asis
  14914. @item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}E}
  14915. @item @code{~@@E}
  14916. If the number is positive a plus sign is printed.
  14917. @end table
  14918. @end table
  14919. @table @asis
  14920. @cindex ~g
  14921. @item @code{~G}
  14922. General floating-point (prints a flonum either fixed or exponential).
  14923. @table @asis
  14924. @item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}G}
  14925. @item @code{~@@G}
  14926. If the number is positive a plus sign is printed.
  14927. @end table
  14928. A slight difference from Common Lisp: If the number is printed
  14929. in fixed form and the fraction is zero,
  14930. then a zero digit is printed for the fraction, if allowed by the @var{width}
  14931. and @var{digits} is unspecified.
  14932. @end table
  14933. @table @asis
  14934. @cindex ~$
  14935. @item @code{~$}
  14936. Dollars floating-point (prints a flonum in fixed with signs separated).
  14937. @table @asis
  14938. @item @code{~@var{digits},@var{scale},@var{width},@var{padchar}$}
  14939. @item @code{~@@$}
  14940. If the number is positive a plus sign is printed.
  14941. @item @code{~:@@$}
  14942. A sign is always printed and appears before the padding.
  14943. @item @code{~:$}
  14944. The sign appears before the padding.
  14945. @end table
  14946. @end table
  14947. @subsection Miscellaneous formatting operators
  14948. @table @asis
  14949. @cindex ~%
  14950. @item @code{~%}
  14951. Newline.
  14952. @table @asis
  14953. @item @code{~@var{n}%}
  14954. print @var{n} newlines.
  14955. @end table
  14956. @cindex ~&
  14957. @item @code{~&}
  14958. print newline if not at the beginning of the output line.
  14959. @table @asis
  14960. @item @code{~@var{n}&}
  14961. prints @code{~&} and then @var{n-1} newlines.
  14962. @end table
  14963. @cindex ~|
  14964. @item @code{~|}
  14965. Page Separator.
  14966. @table @asis
  14967. @item @code{~@var{n}|}
  14968. print @var{n} page separators.
  14969. @end table
  14970. @cindex ~~
  14971. @item @code{~~}
  14972. Tilde.
  14973. @table @asis
  14974. @item @code{~@var{n}~}
  14975. print @var{n} tildes.
  14976. @end table
  14977. @cindex ~@i{newline}
  14978. @item @code{~}<newline>
  14979. Continuation Line.
  14980. @table @asis
  14981. @item @code{~:}<newline>
  14982. newline is ignored, white space left.
  14983. @item @code{~@@}<newline>
  14984. newline is left, white space ignored.
  14985. @end table
  14986. @cindex ~t
  14987. @item @code{~T}
  14988. Tabulation.
  14989. @table @asis
  14990. @item @code{~@@T}
  14991. relative tabulation.
  14992. @item @code{~@var{colnum},@var{colinc}T}
  14993. full tabulation.
  14994. @end table
  14995. @cindex ~?
  14996. @item @code{~?}
  14997. Indirection (expects indirect arguments as a list).
  14998. @table @asis
  14999. @item @code{~@@?}
  15000. extracts indirect arguments from format arguments.
  15001. @end table
  15002. @cindex ~(
  15003. @item @code{~(@var{str}~)}
  15004. Case conversion (converts by @code{string-downcase}).
  15005. @table @asis
  15006. @item @code{~:(@var{str}~)}
  15007. converts by @code{string-capitalize}.
  15008. @item @code{~@@(@var{str}~)}
  15009. converts by @code{string-capitalize-first}.
  15010. @item @code{~:@@(@var{str}~)}
  15011. converts by @code{string-upcase}.
  15012. @end table
  15013. @cindex ~*
  15014. @item @code{~*}
  15015. Argument Jumping (jumps 1 argument forward).
  15016. @table @asis
  15017. @item @code{~@var{n}*}
  15018. jumps @var{n} arguments forward.
  15019. @item @code{~:*}
  15020. jumps 1 argument backward.
  15021. @item @code{~@var{n}:*}
  15022. jumps @var{n} arguments backward.
  15023. @item @code{~@@*}
  15024. jumps to the 0th argument.
  15025. @item @code{~@var{n}@@*}
  15026. jumps to the @var{n}th argument (beginning from 0)
  15027. @end table
  15028. @item @code{~[@var{str0}~;@var{str1}~;...~;@var{strn}~]}
  15029. Conditional Expression (numerical clause conditional).
  15030. @table @asis
  15031. @cindex ~[
  15032. @item @code{~@var{n}[}
  15033. take argument from @var{n}.
  15034. @item @code{~@@[}
  15035. true test conditional.
  15036. @item @code{~:[}
  15037. if-else-then conditional.
  15038. @cindex ~;
  15039. @item @code{~;}
  15040. clause separator.
  15041. @item @code{~:;}
  15042. default clause follows.
  15043. @end table
  15044. @item @code{~@{@var{str}~@}}
  15045. Iteration (args come from the next argument (a list)).
  15046. @table @asis
  15047. @item @code{~@var{n}@{}
  15048. at most @var{n} iterations.
  15049. @cindex ~@{
  15050. @item @code{~:@{}
  15051. args from next arg (a list of lists).
  15052. @item @code{~@@@{}
  15053. args from the rest of arguments.
  15054. @item @code{~:@@@{}
  15055. args from the rest args (lists).
  15056. @end table
  15057. @cindex ~^
  15058. @item @code{~^}
  15059. Up and out.
  15060. @table @asis
  15061. @item @code{~@var{n}^}
  15062. aborts if @var{n} = 0
  15063. @item @code{~@var{n},@var{m}^}
  15064. aborts if @var{n} = @var{m}
  15065. @item @code{~@var{n},@var{m},@var{k}^}
  15066. aborts if @var{n} <= @var{m} <= @var{k}
  15067. @end table
  15068. @end table
  15069. @subsection Unimplemented CL Format Control Directives
  15070. @table @asis
  15071. @item @code{~:A}
  15072. print @code{#f} as an empty list (see below).
  15073. @item @code{~:S}
  15074. print @code{#f} as an empty list (see below).
  15075. @item @code{~<~>}
  15076. Justification.
  15077. @item @code{~:^}
  15078. @end table
  15079. @subsection Extended, Replaced and Additional Control Directives
  15080. These are not necesasrily implemented in Kawa!
  15081. @table @asis
  15082. @item @code{~I}
  15083. print a R4RS complex number as @code{~F~@@Fi} with passed parameters for
  15084. @code{~F}.
  15085. @item @code{~Y}
  15086. Pretty print formatting of an argument for scheme code lists.
  15087. @item @code{~K}
  15088. Same as @code{~?.}
  15089. @item @code{~!}
  15090. Flushes the output if format @var{destination} is a port.
  15091. @item @code{~_}
  15092. Print a @code{#\space} character
  15093. @table @asis
  15094. @item @code{~@var{n}_}
  15095. print @var{n} @code{#\space} characters.
  15096. @end table
  15097. @item @code{~@var{n}C}
  15098. Takes @var{n} as an integer representation for a character. No arguments
  15099. are consumed. @var{n} is converted to a character by
  15100. @code{integer->char}. @var{n} must be a positive decimal number.@refill
  15101. @item @code{~:S}
  15102. Print out readproof. Prints out internal objects represented as
  15103. @code{#<...>} as strings @code{"#<...>"} so that the format output can always
  15104. be processed by @code{read}.
  15105. @refill
  15106. @item @code{~:A}
  15107. Print out readproof. Prints out internal objects represented as
  15108. @code{#<...>} as strings @code{"#<...>"} so that the format output can always
  15109. be processed by @code{read}.
  15110. @refill
  15111. @item @code{~F, ~E, ~G, ~$}
  15112. may also print number strings, i.e. passing a number as a string and
  15113. format it accordingly.
  15114. @end table
  15115. @node Pretty-printing
  15116. @section Pretty-printing
  15117. Pretty-printing is displaying a data structure as text,
  15118. by adding line-breaks and indenttaion so that the visual
  15119. structure of the output corresponds to the logical structure of
  15120. data structure. This makes it easier to read and understand.
  15121. Pretty-printing takes into account the column width of the output
  15122. so as to avoid using more lines than needed.
  15123. Pretty-printing of standard sequences types such as lists and
  15124. vectors is done by default. For example:
  15125. @example
  15126. #|kawa:11|# @kbd{(set! *print-right-margin* 50)}
  15127. #|kawa:12|# @kbd{'(ABCDEF (aa bb cc dd) (x123456789}
  15128. #|.....13|# @kbd{y123456789 z123456789) ABCDEFG HIJKL)}
  15129. (ABCDEF (aa bb cc dd)
  15130. (x123456789 y123456789 z123456789) ABCDEFG HIJK)
  15131. @end example
  15132. Setting @code{*print-right-margin*} to 50
  15133. causes output to be limited to 50 columns.
  15134. Notice the top-level list has to be split,
  15135. but sub-lists @code{(aa bb cc dd)}
  15136. and @code{(x123456789 y123456789 z123456789)}
  15137. don't need to be split.
  15138. When outputting to a DomTerm REPL,
  15139. then @code{*print-right-margin*} is ignored,
  15140. and the line-breaking is actually handled by DomTerm.
  15141. If you change the window width, DomTerm will dynamically
  15142. re-calculate the line-breaks of previous pretten output.
  15143. This works even in the case of a session saved to an HTML
  15144. file, as long as JavaScript is enabled.
  15145. The concepts and terminology are
  15146. based on those of @uref{https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node253.html,Common Lisp}.
  15147. @subsection Pretty-printing Scheme forms
  15148. Scheme and Lisp code is traditionally pretty-printed
  15149. slightly differently than plain lists.
  15150. The @code{pprint} procedure assumes the argument
  15151. is a Scheme form, and prints its accordingly.
  15152. For example the special form @code{(let ...)} is printed
  15153. differently from a regular function call @code{(list ...)}.
  15154. @deffn Procedure pprint obj [out]
  15155. Assume @var{obj} is a Scheme form, and pretty-print it
  15156. in traditional Scheme format. For example:
  15157. @example
  15158. #|kawa:1|# @kbd{(import (kawa pprint))}
  15159. #|kawa:2|# @kbd{(define fib-form}
  15160. #|.....3|# @kbd{ '(define (fibonacci n)}
  15161. #|.....4|# @kbd{ (let loop ((i0 0) (i1 1) (n n))}
  15162. #|.....5|# @kbd{ (if (<= n 0) i0}
  15163. #|.....6|# @kbd{ (loop i1 (+ i0 i1) (- n 1))))))}
  15164. #|kawa:7|# @kbd{(set! *print-right-margin* 80)}
  15165. #|kawa:8|# @kbd{(pprint fib-form)}
  15166. (define (fibonacci n)
  15167. (let loop ((i0 0) (i1 1) (n n)) (if (<= n 0) i0 (loop i1 (+ i0 i1) (- n 1)))))
  15168. #|kawa:9|# @kbd{(set! *print-right-margin* 40)}
  15169. #|kawa:10|# @kbd{(pprint fib-form)}
  15170. (define (fibonacci n)
  15171. (let loop ((i0 0) (i1 1) (n n))
  15172. (if (<= n 0)
  15173. i0
  15174. (loop i1 (+ i0 i1) (- n 1)))))
  15175. @end example
  15176. The @code{pprint} special-cases forms that start with
  15177. @code{define}, @code{if}, @code{lambda}, @code{let},
  15178. and a few more, and formats them with ``traditional'' indentation.
  15179. However, it is not as complete or polished as it should be.
  15180. (It should also use a programmable dispatch table,
  15181. rather than having these special cases hard-wired.
  15182. That is an improvemet for another day.)
  15183. @end deffn
  15184. @subsection Generic pretty-printing functions
  15185. The following procedures are used to indicate logical blocks,
  15186. and optional newlines.
  15187. To access them do:
  15188. @example
  15189. (import (kawa pprint))
  15190. @end example
  15191. In the following, @var{out} is the output port, which
  15192. defaults to @code{(current-output-port)}.
  15193. @deffn Syntax pprint-logical-block @var{options} @arbno{@stxref{statement}}
  15194. Evaluate the @var{statement}s within the context of a new ``logical block''.
  15195. The @var{options} are one or more of the following:
  15196. @table @asis
  15197. @item @stxlit{prefix:} @var{prefix}
  15198. @itemx @stxlit{per-line:} @var{per-line-prefix}
  15199. Emit @var{prefix} or @var{per-line-prefix} (only one of them can be specified) before the start of the logical block.
  15200. If @var{per-line-prefix} is provided, it is also print for each
  15201. line within the logical block, indented the same.
  15202. These are strings and default to @code{""}.
  15203. @item @stxlit{suffix:} @var{suffix}
  15204. Emit @var{suffix} after the end of the logical block.
  15205. @item @stxlit{out:} @var{out}
  15206. The output file.
  15207. @end table
  15208. For example to print a list you might do:
  15209. @example
  15210. (pprint-logical-block prefix: "(" suffix: ")"
  15211. @i{print contents of list})
  15212. @end example
  15213. This macro is equivalent to:
  15214. @example
  15215. (pprint-start-logical-block @var{prefix} @var{is-per-line} @var{suffix} @var{out})
  15216. (try-finally
  15217. (begin @arbno{@var{statement}})
  15218. (pprint-end-logical-block @var{suffix} @var{out}))
  15219. @end example
  15220. @end deffn
  15221. @deffn Procedure pprint-start-logical-block prefix is-per-line suffix out
  15222. Start a logical block.
  15223. The @var{is-per-line} argument is a boolean to specifiy
  15224. of @var{prefix} is a per-line-prefix or a plain prefix.
  15225. @end deffn
  15226. @deffn Procedure pprint-end-logical-block suffix out
  15227. End a logical block.
  15228. @end deffn
  15229. @deffn Procedure pprint-newline kind [out]
  15230. Print a conditional newline, where @var{kind} is one of the
  15231. symbols @code{'fill}, @code{'linear}, @code{'mandatory},
  15232. or @code{'miser}.
  15233. Usually follows printing of a space, as nothing is printed
  15234. if the line is not broken here.
  15235. @end deffn
  15236. @deffn Procedure pprint-ident mode amount [out]
  15237. Change how much following lines are indented
  15238. (with the current logical block).
  15239. The @var{amount} is the size of the indentation, in characters.
  15240. The @var{mode} is either @code{'current} (if the
  15241. @var{amount} is relative to the current position),
  15242. or @code{'block} (if the @var{amount} is relative to the
  15243. start (after any @var{prefix}) of the current logical block).
  15244. @end deffn
  15245. @node Resources
  15246. @section Resources
  15247. A resource is a file or other fixed data that an application may access.
  15248. Resources are part of the application and are shipped with it, but are
  15249. stored in external files. Examples are images, sounds,
  15250. and translation (localization) of messages.
  15251. In the Java world a resource is commonly bundled in the same jar file
  15252. as the application itself.
  15253. @deffn Syntax resource-url resource-name
  15254. Returns a @code{URLPath} you can use as a @code{URL}, or
  15255. you can pass to it @code{open-input-file} to read the resource data.
  15256. The @var{resource-name} is a string which is passed to the
  15257. @code{ClassLoader} of the containing module.
  15258. If the module class is in a jar file, things will magically
  15259. work if the resource is in the same jar file, and @var{resource-name}
  15260. is a filename relative to the module class in the jar.
  15261. If the module is immediately evaluated, the @var{resource-name} is resolved
  15262. against the location of the module source file.
  15263. @end deffn
  15264. @deffn Syntax module-uri
  15265. Evaluates to a special URI that can be used to access resources
  15266. relative to the class of the containing module.
  15267. The URI has the form @code{"class-resource://@var{CurrentClass}/"}
  15268. in compiled code, to allow moving the classes/jars.
  15269. The current @code{ClassLoader} is associated with the URI, so accessing
  15270. resources using the URI will use that @code{ClassLoader}.
  15271. Therefore you should not create a @code{"class-resource:"} URI
  15272. except by using this function or @code{resolve-uri},
  15273. since that might try to use the wrong @code{ClassLoader}.
  15274. The macro @code{resource-url} works by using @code{module-uri}
  15275. and resolving that to a normal @code{URL}.
  15276. @end deffn
  15277. @deffn Syntax module-class
  15278. Evaluates to the containing module class, as a @code{java.lang.Class} instance.
  15279. @end deffn
  15280. @node Types, Objects Classes and Modules, Input-Output, Top
  15281. @chapter Types
  15282. A @dfn{type} is a set of values, plus an associated set of operations
  15283. valid on those values.
  15284. Types are useful for catching errors ("type-checking"), documenting
  15285. the programmer's intent, and to help the compiler generate better code.
  15286. Types in some languages (such as C) appear in programs,
  15287. but do not exist at run-time. In such languages, all type-checking
  15288. is done at compile-time. Other languages (such as standard Scheme)
  15289. do not have types as such, but they have @dfn{predicates}, which
  15290. allow you to check if a value is a member of certain sets; also,
  15291. the primitive functions will check at run-time if the arguments
  15292. are members of the allowed sets. Other languages, including Java
  15293. and Common Lisp, provide a combination: Types may be used as specifiers
  15294. to guide the compiler, but also exist as actual run-time values.
  15295. In Java, for each class, there is a corresponding @code{java.lang.Class}
  15296. run-time object, as well as an associated type (the set of values
  15297. of that class, plus its sub-classes, plus @code{null}).
  15298. Kawa, like Java, has first-class types, that is types exist as
  15299. objects you can pass around at run-time. The most used types
  15300. correspond to Java classes and primitive types,
  15301. but Kawa also has other non-Java types.
  15302. Type specifiers have a @dfn{type expressions}, and a type expression
  15303. is conceptually an expression that is evaluated to yield a type value.
  15304. The current Kawa compiler
  15305. is rather simple-minded, and in many places only allows simple
  15306. types that the compiler can evaluate at compile-time.
  15307. More specifically, it only allows simple @dfn{type names}
  15308. that map to primitive Java types or Java classes.
  15309. @display
  15310. @stxdef{type} @stxref{expression}
  15311. @stxdef{opt-type-specifier} [@stxlit{::} @stxref{type}]
  15312. @end display
  15313. Various Kawa constructs require or allow a type to be specified.
  15314. You can use a type specifier most places where you
  15315. @ref{Variables and Patterns,define a variable or match a pattern}.
  15316. Types specifiers can appear in other placess, such as procedure return
  15317. type specifiers. For example in this procedure definition,
  15318. @code{::vector} is an argument type specifier
  15319. (and @code{vec::vector} is a pattern),
  15320. while @code{::boolean} is a return type specifier.
  15321. @example
  15322. (define (vector-even? vec::vector)::boolean
  15323. (not (odd? (vector-length vec))))
  15324. (vector-even? #(3 4 5)) @result{} #f
  15325. (vector-even? (list 3 4 5 6)) @result{} @i{error}
  15326. @end example
  15327. @menu
  15328. * Standard Types::
  15329. * Parameterized Types::
  15330. * Type tests and conversions::
  15331. @end menu
  15332. @node Standard Types
  15333. @section Standard Types
  15334. These types are predefined with the following names.
  15335. Instead of plain @code{@var{typename}} you can also use
  15336. the syntax @code{<@var{typename}>} with angle brackets,
  15337. but that syntax is no longer recommended, because it doesn't
  15338. ``fit'' as well with some ways type names are used.
  15339. To find which Java classes these types map into, look in
  15340. @code{kawa/standard/Scheme.java}.
  15341. Note that the value of these variables are instances
  15342. of @code{gnu.bytecode.Type},
  15343. not (as you might at first expect) @code{java.lang.Class}.
  15344. The numeric types (@code{number}, @code{quantity},
  15345. @code{complex}, @code{real}, @code{rational}, @code{integer},
  15346. @code{long}, @code{int}, @code{short}, @code{byte}
  15347. @code{ulong}, @code{uint}, @code{ushort}, @code{ubyte},
  15348. @code{double}, @code{float})
  15349. are discussed in @ref{Numerical types}.
  15350. The types @code{character} and @code{char}
  15351. are discussed in @ref{Characters}.
  15352. @defvar Object
  15353. An arbitrary Scheme value - and hence an arbitrary Java object.
  15354. @end defvar
  15355. @defvar symbol
  15356. The type of Scheme symbols.
  15357. (Implemented using the Java class @code{gnu.mapping.Symbol}.)
  15358. (@CompatibilityNote{} Previous versions of Kawa implemented
  15359. a simple Scheme symbol using an interned @code{java.lang.String}.)
  15360. @end defvar
  15361. @defvar keyword
  15362. The type of keyword values. @xref{Keywords}.
  15363. @end defvar
  15364. @defvar list
  15365. The type of Scheme lists (pure and impure, including the empty list).
  15366. @end defvar
  15367. @defvar pair
  15368. The type of Scheme pairs. This is a sub-type of @code{list}.
  15369. @end defvar
  15370. @defvar string
  15371. The type of Scheme strings.
  15372. (Implemented using @code{gnu.lists.IString} or @code{java.lang.String}
  15373. for immutable strings,
  15374. and @code{gnu.lists.FString} for mutable strings.
  15375. These all implement the interface @code{java.lang.CharSequence}.
  15376. (@CompatibilityNote{} Previous versions of Kawa
  15377. always used @code{gnu.lists.FString}.)
  15378. @end defvar
  15379. @defvar character
  15380. The type of Scheme character values. This is a sub-type of
  15381. @code{Object}, in contrast to type @code{char}, which is the
  15382. primitive Java @code{char} type.
  15383. @end defvar
  15384. @defvar vector
  15385. The type of Scheme vectors.
  15386. @end defvar
  15387. @defvar procedure
  15388. The type of Scheme procedures.
  15389. @end defvar
  15390. @defvar input-port
  15391. The type of Scheme input ports.
  15392. @end defvar
  15393. @defvar output-port
  15394. The type of Scheme output ports.
  15395. @end defvar
  15396. @defvar String
  15397. This type name is a special case. It specifies the class
  15398. @code{java.lang.String}.
  15399. However, coercing a value to @code{String} is done by
  15400. invoking the @code{toString} method on the value to be coerced.
  15401. Thus it "works" for all objects.
  15402. It also works for @code{#!null}.
  15403. When Scheme code invokes a Java method, any parameter
  15404. whose type is @code{java.lang.String} is converted
  15405. as if it was declared as a @code{String}.
  15406. @end defvar
  15407. @defvar parameter
  15408. A parameter object, as created by @code{make-parameter}.
  15409. This type can take a type parameter (sic):
  15410. @example
  15411. (define-constant client ::parameter[Client] (make-parameter #!null))
  15412. @end example
  15413. This lets Kawa know that reading the parameter (as in @code{(client)})
  15414. returns a value of the specified type (in this case @code{Client}).
  15415. @end defvar
  15416. More will be added later.
  15417. A type specifier can also be one of the primitive Java types.
  15418. The numeric types @code{long}, @code{int}, @code{short},
  15419. @code{byte}, @code{float}, and @code{double} are converted from the
  15420. corresponding Scheme number classes. Similarly, @code{char}
  15421. can be converted to and from Scheme characters. The type
  15422. @code{boolean} matches any object, and the result is @code{false}
  15423. if and only if the actual argument is @code{#f}.
  15424. (The value @code{#f} is identical to @code{Boolean.FALSE},
  15425. and @code{#t} is identical to @code{Boolean.TRUE}.)
  15426. The return type @code{void} indicates that no value is returned.
  15427. A type specifier can also be a fully-qualified Java class name
  15428. (for example @code{java.lang.StringBuffer}). In that case,
  15429. the actual argument is cast at run time to the named class.
  15430. Also, @code{java.lang.StringBuffer[]} represents
  15431. an array of references to @code{java.lang.StringBuffer} objects.
  15432. @anchor{dynamic-type}
  15433. @defvar dynamic
  15434. Used to specify that the type is unknown, and is likely to change
  15435. at run-time.
  15436. Warnings about unknown member names are supressed
  15437. (a run-time name lookup is formed).
  15438. An expression of type @code{dynamic} is (statically) compatible with
  15439. any type.
  15440. @end defvar
  15441. @node Parameterized Types
  15442. @section Parameterized Types
  15443. Kawa has some basic support for parameterized (generic) types.
  15444. The syntax:
  15445. @example
  15446. Type[Arg1 Arg2 ... ArgN]
  15447. @end example
  15448. is more-or-less equivalent to Java's:
  15449. @example
  15450. Type<Arg1, Arg2, ..., ArgN>
  15451. @end example
  15452. This is a work-in-progress. You can use this syntax with
  15453. fully-qualified class names, and also type aliases:
  15454. @example
  15455. (define v1 ::gnu.lists.FVector[gnu.math.IntNum] [4 5 6])
  15456. (define-alias fv gnu.lists.FVector)
  15457. (define v2 ::fv[integer] [5 6 7])
  15458. (define-alias fvi fv[integer])
  15459. (define v3 ::fvi [6 7 8])
  15460. @end example
  15461. @node Type tests and conversions
  15462. @section Type tests and conversions
  15463. Scheme defines a number of standard type testing predicates.
  15464. For example @code{(vector? x)} is @code{#t} if and only if
  15465. @code{x} is a vector.
  15466. Kawa generalizes this to arbitrary type names:
  15467. If @var{T} is a type-name (that is in scope at compile-time),
  15468. then @code{@var{T}?} is a one-argument function that returns
  15469. @code{#t} if the argument is an instance of the type @code{@var{T}},
  15470. and @code{#f} otherwise:
  15471. @example
  15472. (gnu.lists.FVector? #(123)) @result{} #t
  15473. (let ((iarr (int[] 10))) (int[]? iarr)) @result{} #t
  15474. @end example
  15475. To convert (coerce) the result of an expression @var{value} to a
  15476. type @var{T} use the syntax: @code{(->@var{T} @var{value})}.
  15477. @example
  15478. (->float 12) @result{} 12.0f0
  15479. @end example
  15480. In general:
  15481. @example
  15482. (@var{T}? @var{x}) @result{} (instance? @var{x} @var{T})
  15483. (->@var{T} @var{x}) @result{} (as @var{T} @var{x})
  15484. @end example
  15485. @deffn Procedure instance? value type
  15486. Returns @code{#t} iff @var{value} is an instance of type @var{type}.
  15487. (Undefined if @var{type} is a primitive type, such as @code{int}.)
  15488. @end deffn
  15489. @deffn Procedure as type value
  15490. Converts or coerces @var{value} to a value of type @var{type}.
  15491. Throws an exception if that cannot be done.
  15492. Not supported for @var{type} to be a primitive type such as @code{int}.
  15493. @end deffn
  15494. @node Objects Classes and Modules, XML tools, Types, Top
  15495. @chapter Object, Classes and Modules
  15496. Kawa provides various ways to define, create, and access Java objects.
  15497. Here are the currently supported features.
  15498. The Kawa module system is based on the features of the Java class system.
  15499. @menu
  15500. * Defining new classes::
  15501. * Anonymous classes::
  15502. * Enumerations:: Enumeration types
  15503. * Annotations::
  15504. * Module classes:: Modules and how they are compiled to classes
  15505. * Importing:: Importing from a library
  15506. * Record types:: Defining Record Types
  15507. * Dynamic records:: Creating New Record Types On-the-fly
  15508. * Method operations:: Calling Java methods from Scheme
  15509. * Allocating objects::
  15510. * Field operations:: Accessing fields of Java objects
  15511. * Mangling:: Mapping Scheme names to Java names
  15512. * Scheme types in Java::
  15513. * Array operations:: Using Java arrays
  15514. * Loading Java functions into Scheme::
  15515. * Evaluating Scheme expressions from Java::
  15516. @end menu
  15517. @deffn Syntax this
  15518. Returns the "this object" - the current instance of the current class.
  15519. The current implementation is incomplete, not robust, and not
  15520. well defined. However, it will have to do for now.
  15521. Note: "@code{this}" is a macro, not a variable, so you have to write
  15522. it using parentheses: @samp{(this)}. A planned extension will
  15523. allow an optional class specifier (needed for nested clases).
  15524. @end deffn
  15525. @node Defining new classes
  15526. @section Defining new classes
  15527. Kawa provides various mechanisms for defining new classes.
  15528. The @code{define-class} and @code{define-simple-class} forms
  15529. will usually be the preferred mechanisms. They have basically
  15530. the same syntax, but have a couple of differences.
  15531. @code{define-class} allows multiple inheritance as well as true nested
  15532. (first-class) class objects. However, the implementation
  15533. is more complex: code using it is slightly slower, and the mapping to
  15534. Java classes is a little less obvious. (Each Scheme class is implemented
  15535. as a pair of an interface and an implementation class.)
  15536. A class defined by @code{define-simple-class} is slightly more
  15537. efficient, and it is easier to access it from Java code.
  15538. The syntax of @code{define-class} are mostly compatible with that
  15539. in the Guile and Stk dialects of Scheme.
  15540. @deffn Syntax define-class @stxref{class-name} @stxlit{(}supers ...@stxlit{)} @arbno{(@stxref{annotation}|@stxref{option-pair})} @stxref{field-or-method-decl} ...
  15541. @deffnx Syntax define-simple-class @stxref{class-name} @stxlit{(}supers ...@stxlit{)} @arbno{(@stxref{annotation}|@stxref{option-pair})} @stxref{field-or-method-decl} ...
  15542. Defines a new class named @var{class-name}. If @code{define-simple-class} is
  15543. used, creates a normal Java class named @var{class-name} in the current package.
  15544. (If @var{class-name} has the form @code{<xyz>} the Java implementation
  15545. type is named @code{xyz}.) For @code{define-class} the implementation is
  15546. unspecified. In most cases, the compiler creates a class pair,
  15547. consisting of a Java interface and a Java implementation class.
  15548. @end deffn
  15549. @display
  15550. @stxdef{class-name} @stxref{identifier}
  15551. @stxdef{option-pair} @var{option-keyword} @var{option-value}
  15552. @stxdef{field-or-method-decl} @stxref{field-decl} | @stxref{method-decl}
  15553. @end display
  15554. @subsection General class properties
  15555. The class inherits from the classes and interfaces listed in @var{supers}.
  15556. This is a list of names of classes that are in scope (perhaps imported
  15557. using @code{require}), or names for existing classes or interfaces
  15558. optionally surrounded by @code{<>}, such as @code{<gnu.lists.Sequence>}.
  15559. If @code{define-simple-class} is used, at most one of these may be
  15560. the name of a normal Java class or classes defined using
  15561. @code{define-simple-class}; the rest must be interfaces or classes
  15562. defined using @code{define-class}.
  15563. If @code{define-class} is used, @emph{all} of the classes listed
  15564. in @var{supers} should be interfaces or classes defined using
  15565. @code{define-class}.
  15566. @table @asis
  15567. @item @stxlit{interface:} @var{make-interface}
  15568. Specifies whether Kawa generates a Java class, interface, or both.
  15569. If @var{make-interface} is @code{#t}, then a Java interface is generated.
  15570. In that case all the supertypes must be interfaces, and
  15571. all the declared methods must be abstract.
  15572. If @var{make-interface} is @code{#f}, then a Java class is generated.
  15573. If @code{interface:} is unspecified, the default is @code{#f}
  15574. for @code{define-simple-class}. For @code{define-class} the default
  15575. is to generate an interface, and in addition (if needed) a helper
  15576. class that implements the interface. (In that case any non-abstract methods
  15577. are compiled to static methods. The methods that implement the interface
  15578. are just wrapper methods that call the real static methods. This
  15579. allows Kawa to implement true multiple inheritance.)
  15580. @item @stxlit{access:} @var{kind}
  15581. Specifies the Java access permission on the class.
  15582. Can be one of @code{'public} (which is the default in Kawa),
  15583. @code{'package} (which the default "unnamed" permission in Java code),
  15584. @code{'protected}, @code{'private},
  15585. @code{'volatile}, or @code{'transient}.
  15586. Can also be used to specify @code{final}, @code{abstract}, or @code{enum}, as in Java.
  15587. (You don't need to explicitly specify the class is @code{abstract}
  15588. if any @var{method-body} is @code{#!abstract},
  15589. or you specify @code{interface: #t}.)
  15590. The @var{kind} can also be a list, as for example:
  15591. @example
  15592. access: '(protected volatile)
  15593. @end example
  15594. @item @stxlit{class-name:} @code{"}@var{cname}@code{"}
  15595. Specifies the Java name of the created class.
  15596. The @var{name} specified after @code{define-class}
  15597. or @code{define-simple-class} is the @emph{Scheme name},
  15598. i.e. the name of a Scheme variable that is bound to the class.
  15599. The Java name is by default derived from the Scheme name,
  15600. but you can override the default with a @code{class-name:} specifier.
  15601. If the @var{cname} has no periods, then it is a name in
  15602. the package of the main (module) class.
  15603. If the @var{cname} starts with a period,
  15604. then you get a class nested within the module class.
  15605. In this case the actual class name is @var{moduleClass}@code{$}@var{rname},
  15606. where @var{rname} is @var{cname} without the initial period.
  15607. To force a class in the top-level (unnamed) package (something
  15608. not recommended) write a period at the end of the @var{cname}.
  15609. @end table
  15610. @subsection Declaring fields
  15611. @display
  15612. @stxdef{field-decl} @stxlit{(}@stxref{field-name} (@stxref{annotation} | @stxref{opt-type-specifier} | @stxref{field-option})*@stxlit{)}
  15613. @stxdef{field-name} @stxref{identifier}
  15614. @stxdef{field-option} @stxref{keyword} @stxref{expression}
  15615. @end display
  15616. As a matter of style the following order is suggested, though this not enforced:
  15617. @display
  15618. @stxlit{(}@stxref{field-name} @stxref{annotation}* @stxref{opt-type-specifier} @stxref{field-option}*@stxlit{)}
  15619. @end display
  15620. Each @var{field-decl} declares a instance "slot" (field)
  15621. with the given @var{field-name}.
  15622. By default it is publicly visible, but you can specify
  15623. a different visiblity with the @code{access:} specifier.
  15624. The following @var{field-option} @var{keyword}s are implemented:
  15625. @table @asis
  15626. @item @stxlit{type:} @stxref{type}
  15627. Specifies that @var{type} is the type of (the values of) the field.
  15628. Equivalent to @samp{:: @var{type}}.
  15629. @item @stxlit{allocation:} @var{kind}
  15630. If @var{kind} is @code{'class} or @code{'static} a single slot is shared
  15631. between all instances of the class (and its sub-classes).
  15632. Not yet implemented for @code{define-class},
  15633. only for @code{define-simple-class}.
  15634. In Java terms this is a @code{static} field.
  15635. If @var{kind} is @code{'instance} then
  15636. each instance has a separate value "slot", and they
  15637. are not shared. In Java terms, this is a non-@code{static} field.
  15638. This is the default.
  15639. @c You can use a keyword like @code{class:} or a string like @code{"class"}
  15640. @c if you prefer instead of a quoted symbol like @code{'class};
  15641. @c the latter is recommended.
  15642. @item @stxlit{access:} @var{kind}
  15643. Specifies the Java access permission on the field.
  15644. Can be one of @code{'private}, @code{'protected},
  15645. @code{'public} (which is the default in Kawa),
  15646. or @code{'package} (which the default "unnamed" permission
  15647. in Java code).
  15648. Can also be used to specify @code{volatile}, @code{transient},
  15649. @code{enum}, or @code{final}, as in Java,
  15650. or a quoted list with these symbols.
  15651. @item @stxlit{init:} @var{expr}
  15652. An expression used to initialize the slot.
  15653. The expression is evaluated in a scope that includes the field and
  15654. method names of the current class.
  15655. @item @stxlit{init-form:} @var{expr}
  15656. An expression used to initialize the slot.
  15657. The lexical environment of the @var{expr} is that of the @code{define-class};
  15658. it does @emph{not} include the field and method names of the current class.
  15659. or @code{define-simple-class}.
  15660. @item @stxlit{init-value:} @var{value}
  15661. A value expression used to initialize the slot.
  15662. For now this is synonymous with @var{init-form:}, but that may change
  15663. (depending on what other implementation do), so to be safe only use
  15664. @code{init-value:} with a literal.
  15665. @item @stxlit{init-keyword:} @code{@var{name}:}
  15666. A keyword that that can be used to initialize instance in @code{make} calls.
  15667. For now, this is ignored, and @var{name} should be the same as the
  15668. field's @var{field-name}.
  15669. @end table
  15670. The @var{field-name} can be left out. That indicates a "dummy slot",
  15671. which is useful for initialization not tied to a specific field.
  15672. In Java terms this is an instance or static initializer, i.e., a
  15673. block of code executed when a new instance is created or the class is loaded.
  15674. In this example, @code{x} is the only actual field. It is first
  15675. initialized to 10, but if @code{(some-condition)} is true
  15676. then its value is doubled.
  15677. @example
  15678. (define-simple-class <my-class> ()
  15679. (allocation: 'class
  15680. init: (perform-actions-when-the-class-is-initizalized))
  15681. (x init: 10)
  15682. (init: (if (some-condition) (set! x (* x 2)))))
  15683. @end example
  15684. @subsection Declaring methods
  15685. @display
  15686. @stxdef{method-decl} @stxlit{((}@stxref{method-name} @stxref{formal-arguments}@stxlit{)}
  15687. @arbno{@stxref{method-option}} [@stxref{deprecated-return-specifier}] @stxref{method-body}@stxlit{)}
  15688. @stxdef{method-name} @stxref{identifier}
  15689. @stxdef{method-option} @stxref{annotation} | @stxref{opt-return-type} | @stxref{option-pair}
  15690. @stxdef{method-body} @stxref{body} | @stxlit{#!abstract} | @stxlit{#!native}
  15691. @stxdef{deprecated-return-specifier} @stxref{identifier}
  15692. @end display
  15693. Each @var{method-decl} declares a method,
  15694. which is by default public and non-static, and whose name is @var{method-name}.
  15695. (If @var{method-name} is not a valid
  15696. Java method name, it is mapped to something reasonable.
  15697. For example @code{foo-bar?} is mapped to @code{isFooBar}.)
  15698. The types of the method arguments can be specified in the
  15699. @var{formal-arguments}. The return type can be specified by
  15700. a @var{opt-return-type}, @var{deprecated-return-specifier},
  15701. or is otherwise the type of the @var{body}.
  15702. Currently, the @var{formal-arguments} cannot contain optional, rest,
  15703. or keyword parameters. (The plan is to allow optional parameters,
  15704. implemented using multiple overloaded methods.)
  15705. A @var{method-decl} in a @code{define-simple-class}
  15706. can have the following @var{option-keyword}s:
  15707. @table @asis
  15708. @item @stxlit{access:} @var{kind}
  15709. Specifies the Java access permission on the method.
  15710. Can be one of @code{'private}, @code{'protected},
  15711. @code{'public}, or @code{'package}.
  15712. Can also be @code{'synchronized}, @code{'final}, @code{'strictfp},
  15713. or a quoted list.
  15714. @item @stxlit{allocation:} @var{kind}
  15715. If @var{kind} is @code{'class} or @code{'static} creates a static method.
  15716. @item @stxlit{throws:} ( @var{exception-class-name} ... )
  15717. Specifies a list of checked exception that the method may throw.
  15718. Equivalent to a @code{throws} specification in Java code.
  15719. For example:
  15720. @example
  15721. (define-simple-class T
  15722. (prefix)
  15723. ((lookup name) throws: (java.io.FileNotFoundException)
  15724. (make java.io.FileReader (string-append prefix name))))
  15725. @end example
  15726. @end table
  15727. The scope of the @var{body} of a method includes the @var{field-decl}s
  15728. and @var{method-decl}s of the class, including those inherited from
  15729. superclasses and implemented interfaces.
  15730. If the @var{method-body} is the special form @code{#!abstract},
  15731. then the method is abstract. This means the method must
  15732. be overridden in a subclass, and you're not allowed to
  15733. create an instance of the enclosing class.
  15734. @example
  15735. (define-simple-class Searchable () interface: #t
  15736. ((search value) :: boolean #!abstract))
  15737. @end example
  15738. If the @var{method-body} is the special form @code{#!native},
  15739. then the method is native, implemented using @uref{http://en.wikipedia.org/wiki/Java_Native_Interface,JNI}.
  15740. The special @var{method-name} @samp{*init*} can be used to name
  15741. a non-default constructor (only if @var{make-interface} discussed above
  15742. is @code{#f}).
  15743. It can be used to initialize a freshly-allocated instance
  15744. using passed-in parameters.
  15745. You can call a superclass or a sibling constructor using
  15746. the @code{invoke-special} special function.
  15747. (This is general but admittedly a bit verbose; a more compact
  15748. form may be added in the future.)
  15749. See the example below.
  15750. @subsection Example
  15751. In the following example we define a simple class @code{2d-vector}
  15752. and a class @code{3d-vector} that extends it. (This is for illustration
  15753. only - defining 3-dimensional points as an extension
  15754. of 2-dimensional points does not really make sense.)
  15755. @example
  15756. (define-simple-class 2d-vector ()
  15757. (x ::double init-keyword: x:)
  15758. ;; Alternative type-specification syntax.
  15759. (y type: double init-keyword: y:)
  15760. (zero-2d :: 2d-vector allocation: 'static
  15761. init-value: (2d-vector 0))
  15762. ;; An object initializer (constructor) method.
  15763. ((*init* (x0 ::double) (y0 ::double))
  15764. (set! x x0)
  15765. (set! y y0))
  15766. ((*init* (xy0 ::double))
  15767. ;; Call above 2-argument constructor.
  15768. (invoke-special 2d-vector (this) '*init* xy0 xy0))
  15769. ;; Need a default constructor as well.
  15770. ((*init*) #!void)
  15771. ((add (other ::2d-vector)) ::2d-vector
  15772. ;; Kawa compiles this using primitive Java types!
  15773. (2d-vector
  15774. x: (+ x other:x)
  15775. y: (+ y other:y)))
  15776. ((scale (factor ::double)) ::2d-vector
  15777. (2d-vector x: (* factor x) y: (* factor y))))
  15778. (define-simple-class 3d-vector (2d-vector)
  15779. (z type: double init-value: 0.0 init-keyword: z:)
  15780. ;; A constructor which calls the superclass constructor.
  15781. ((*init* (x0 ::double) (y0 ::double) (z0 ::double))
  15782. (invoke-special 2d-vector (this) '*init* x0 y0)
  15783. (set! z z0))
  15784. ;; Need a default constructor.
  15785. ((*init*) #!void)
  15786. ((scale (factor ::double)) ::2d-vector
  15787. ;; Note we cannot override the return type to 3d-vector
  15788. ;; because Kawa doesn't yet support covariant return types.
  15789. (3d-vector
  15790. x: (* factor x)
  15791. y: (* factor (this):y) ;; Alternative syntax.
  15792. z: (* factor z))))
  15793. @end example
  15794. Note we define both explicit non-default constructor methods,
  15795. and we associate fields with keywords, so they can be named
  15796. when allocating an object. Using keywords requires a default constructor,
  15797. and since having non-default constructors suppresses
  15798. the implicit default constructor we have to explicitly define it.
  15799. Using both styles of constructors is rather redundant, though.
  15800. @node Anonymous classes
  15801. @section Anonymous classes
  15802. @deffn Syntax object @stxlit{(}supers ...@stxlit{)} field-or-method-decl ...
  15803. Returns a new instance of an anonymous (inner) class.
  15804. The syntax is similar to @code{define-class}.
  15805. @display
  15806. @stxdef{object-field-or-method-decl} @stxref{object-field-decl} | @stxref{method-decl}
  15807. @stxdef{object-field-decl} @stxlit{(}@stxref{field-name} (@stxref{annotation} | @stxref{opt-type-specifier} | @stxref{field-option})* [@stxref{object-init}] @stxlit{)}
  15808. @stxdef{object-init} @stxref{expression}
  15809. @end display
  15810. Returns a new instance of a unique (anonymous) class.
  15811. The class inherits from the list of @var{supers}, where at most one of the
  15812. elements should be the base class being extended from, and the rest
  15813. are interfaces.
  15814. This is roughly equivalent to:
  15815. @example
  15816. (begin
  15817. (define-simple-class @var{hname} (@var{supers} ...) @var{field-or-method-decl} ...)
  15818. (make @var{hname}))
  15819. @end example
  15820. A @var{field-decl} is as for @code{define-class}, except
  15821. that we also allow an abbreviated syntax.
  15822. Each @var{field-decl} declares a public instance field.
  15823. If @var{object-finit} is given, it is an expression whose value
  15824. becomes the initial value of the field.
  15825. The @var{object-init} is evaluated at the same time as the @code{object}
  15826. expression is evaluated,
  15827. in a scope where all the @var{field-name}s are visible.
  15828. A @var{method-decl} is as for @code{define-class}.
  15829. @end deffn
  15830. @anchor{SAM-conversion}
  15831. @subsection Lambda as shorthand for anonymous class
  15832. An anonymous class is commonly used in the Java platform where a
  15833. function language would use a lambda expression.
  15834. Examples are call-back handlers, events handlers, and @code{run} methods.
  15835. In these cases Kawa lets you use a lambda expression as a short-hand
  15836. for an anonymous class. For example:
  15837. @example
  15838. (button:addActionListener
  15839. (lambda (e) (do-something)))
  15840. @end example
  15841. is equivalent to:
  15842. @example
  15843. (button:addActionListener
  15844. (object (java.awt.event.ActionListener)
  15845. ((actionPerformed (e ::java.awt.event.ActionEvent))::void
  15846. (do-something))))
  15847. @end example
  15848. This is possible when the required type is an interface or
  15849. abstract class with a Single (exactly one) Abstract Methods.
  15850. Such a class is sometimes called a @dfn{SAM-type}, and the
  15851. conversion from a lambda expression to an anonymous class
  15852. is sometimes called @dfn{SAM-conversion}.
  15853. Note that Kawa can also infer the parameter and return types
  15854. of a method that overrides a method in a super-class.
  15855. @node Enumerations
  15856. @section Enumeration types
  15857. An enumeration type is a set of named atomic enumeration values
  15858. that are distinct from other values. You define the type
  15859. using @code{define-enum}, and you reference enumeration values
  15860. using colon notation:
  15861. @example
  15862. (define-enum colors (red blue green))
  15863. (define favorite-color colors:green)
  15864. @end example
  15865. Displaying an enum just prints the enum name,
  15866. but readable output using @code{write} (or the @code{~s} @code{format}
  15867. specifier) prepends the type name:
  15868. @example
  15869. (format "~a" favorite-color) @result{} "green"
  15870. (format "~s" favorite-color) @result{} "colors:green"
  15871. @end example
  15872. The static @code{values} method returns a Java array of the enumeration
  15873. values, in declaration order, while @code{ordinal} yields the index
  15874. of an enumeration value:
  15875. @example
  15876. (colors:values) @result{} [red blue green]
  15877. ((colors:values) 1) @result{} blue
  15878. (favorite-color:ordinal) @result{} 2
  15879. @end example
  15880. If you invoke the enumeration type as a function,
  15881. it will map the name (as a string) to the corresponding value.
  15882. (This uses the @code{valueOf} method.)
  15883. @example
  15884. (colors "red") @result{} red
  15885. (colors "RED") @result{} throws IllegalArgumentException
  15886. (eq? favorite-color (colors:valueOf "green")) @result{} #t
  15887. @end example
  15888. Kawa enumerations are based on Java enumerations.
  15889. Thus the above is similar to a Java5 @code{enum} declaration,
  15890. and the type @code{colors} above extends @code{java.lang.Enum}.
  15891. @deffn Syntax define-enum enum-type-name @var{option-pair}... @stxlit{(}enum-value-name ...@stxlit{)} @var{field-or-method-decl}...
  15892. This declares a new enumeration type @var{enum-type-name},
  15893. whose enumerations values are the @var{enum-value-name} list.
  15894. You can specify extra options and members using
  15895. @var{option-pair} and @var{field-or-method-decl},
  15896. which are as in @code{define-simple-class}.
  15897. (The @var{define-enum} syntax is similar to a
  15898. @code{define-simple-class} that extends @code{java.lang.Enum}.)
  15899. @end deffn
  15900. (Note that R6RS has a separate Enumerations library @code{(rnrs enum)}.
  15901. Unfortunately, this is not compatible with standard Java enums.
  15902. R6RS enums are simple symbols, which means you cannot distinguish
  15903. two enum values from different enumeration types if they have the
  15904. same value, nor from a vanilla symbol. That makes them less useful.)
  15905. @node Annotations
  15906. @section Annotations of declarations
  15907. The Java platform lets you associate with each declaration zero or more
  15908. @uref{http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html, annotations}.
  15909. They provide an extensible mechanism to associate properties
  15910. with declarations.
  15911. Kawa support for annotations is not complete (the most important
  15912. functionality missing is being able to declare annotation types),
  15913. but is fairly functional.
  15914. Here is a simple example illustrating use of
  15915. @uref{http://jcp.org/en/jsr/detail?id=222,JAXB annotations}:
  15916. an @code{XmlRootElement} annotation on a class,
  15917. and an @code{XmlElement} annotation on a field:
  15918. @example
  15919. (import (class javax.xml.bind.annotation XmlRootElement XmlElement))
  15920. (define-simple-class Bib ( ) (@@XmlRootElement name: "bib")
  15921. (books (@@XmlElement name: "book" type: Book) ::java.util.ArrayList))
  15922. (define-simple-class Book () ...)
  15923. @end example
  15924. @uref{http://per.bothner.com/blog/2011/Using-JAXB-annotations, This tutorial}
  15925. explains the JAXB example in depth.
  15926. Here is the syntax:
  15927. @display
  15928. @stxdef{annotation} @stxlit{(@@}@stxref{annotation-typename} @stxref{annotations-element-values}@stxlit{)}
  15929. @stxdef{annotations-element-values} @stxref{annotation-element-value}
  15930. | @stxref{annotation-element-pair} ...
  15931. @stxdef{annotation-element-pair} @stxref{keyword} @stxref{annotation-element-value}
  15932. @stxdef{annotation-element-value} @stxref{expression}
  15933. @stxdef{annotation-typename} @stxref{expression}
  15934. @end display
  15935. An @var{annotations-element-values} consisting of just
  15936. a single @var{annotation-element-value} is equivalent to an
  15937. @var{annotation-element-pair} with a @code{value:} keyword.
  15938. Each @var{keyword} must correspond to the name of
  15939. an element (a zero-argument method) in the annotation type.
  15940. The corresponding @var{annotation-element-value} must be compatible with the
  15941. element type (return type of the method) of the annotation type.
  15942. Allowed element types are of the following kinds:
  15943. @itemize @bullet
  15944. @item
  15945. Primitive types, where the @var{annotation-element-value} must
  15946. be number or boolean coercible to the element type.
  15947. @item
  15948. Strings, where the @var{annotation-element-value} is normally a string literal.
  15949. @item
  15950. Classes, where the @var{annotation-element-value} is normally
  15951. a classname.
  15952. @item
  15953. Enumeration types. The value usually has the form @code{@var{ClassName}:@var{enumFieldname}}.
  15954. @item
  15955. Nested annotation types, where the @var{annotation-element-value} must
  15956. be a compatible @var{annotation} value.
  15957. @item
  15958. An array of one of the allowable types.
  15959. An array constructor expression works, but using the
  15960. square bracket syntax is recommended.
  15961. @end itemize
  15962. Annotations are usually used in declarations,
  15963. where they are required to be ``constant-folded'' to compile-time
  15964. constant annotation values.
  15965. This is so they can be written to class files.
  15966. However, in other contexts an annotation can be used as an expression
  15967. with general sub-expressions evaluated at run-time:
  15968. @example
  15969. (define bk-name "book")
  15970. (define be (@@XmlElement name: bk-name type: Book))
  15971. (be:name) @result{} "book"
  15972. @end example
  15973. (This may have limited usefulness: There are some bugs, including
  15974. lack of support for default values for annotation elements.
  15975. These bugs can be fixed if someone reports a need for
  15976. runtime construction of annotation values.)
  15977. @node Module classes
  15978. @section Modules and how they are compiled to classes
  15979. Modules provide a way to organize Scheme into
  15980. reusable parts with explicitly defined interfaces to the rest
  15981. of the program.
  15982. A @dfn{module} is a set of definitions that the module @dfn{exports},
  15983. as well as some @dfn{actions} (expressions evaluated for their side effect).
  15984. The top-level forms in a Scheme source file compile a module;
  15985. the source file is the @dfn{module source}.
  15986. When Kawa compiles the module source, the result is the
  15987. @dfn{module class}. Each exported definition is translated to
  15988. a public field in the module class.
  15989. @subsection Name visibility
  15990. The definitions that a module exports are accessible to other modules.
  15991. These are the "public" definitions, to use Java terminology.
  15992. By default, all the identifiers declared at the top-level of a module
  15993. are exported, except those defined using @code{define-private}.
  15994. (If compiling with the @code{--main} flag,
  15995. then by default no identifiers are exported.)
  15996. However, a major purpose of using modules is to control the set of
  15997. names exported. One reason is to reduce the chance of accidental
  15998. name conflicts between separately developed modules. An even more
  15999. important reason is to enforce an interface: Client modules should
  16000. only use the names that are part of a documented interface, and should
  16001. not use internal implementation procedures (since those may change).
  16002. If there is a @code{module-export} (or @code{export})
  16003. declaration in the module, then only those names listed are exported.
  16004. There can be more than one @code{module-export}, and they can be
  16005. anywhere in the Scheme file. The recommended style has
  16006. a single @code{module-export} near the beginning of the file.
  16007. @anchor{meta-export-declaration}
  16008. @deffn Syntax module-export @arbno{@stxref{export-spec}}
  16009. @deffnx Syntax export @arbno{@stxref{export-spec}}
  16010. The forms @code{export} and @code{module-export} are equivalent.
  16011. (The older Kawa name is @code{module-export};
  16012. @code{export} comes from R7RS.)
  16013. Either form specifies a list of identifiers which
  16014. can be made visible to other libraries or programs.
  16015. @display
  16016. @stxdef{export-spec} @var{identifier}
  16017. | @stxlit{(rename} @stxref{identifier}@sub{1} @stxref{identifier}@sub{2}@stxlit{)}
  16018. @end display
  16019. In the former variant, an @var{identifier} names a single binding
  16020. defined within or imported into the library, where the
  16021. external name for the export is the same as the name of
  16022. the binding within the library.
  16023. A @code{rename} spec exports the
  16024. binding defined within or imported into the library and
  16025. named by @var{identifier}@sub{1},
  16026. using @var{identifier}@sub{2} as the external name.
  16027. Note that it is an error if there is no definition for @var{identifier}
  16028. (or @var{identifier}@sub{1})
  16029. in the current module, or if it is defined using @code{define-private}.
  16030. As a matter of style, @code{export} or @code{module-export} should
  16031. appear after @code{module-name} but @emph{before} other commands
  16032. (including @code{import} or @code{require}).
  16033. (This is a requirement if there are any cycles.)
  16034. @end deffn
  16035. In this module, @code{fact} is public and @code{worker} is private:
  16036. @example
  16037. (module-export fact)
  16038. (define (worker x) ...)
  16039. (define (fact x) ...)
  16040. @end example
  16041. Alternatively, you can write:
  16042. @example
  16043. (define-private (worker x) ...)
  16044. (define (fact x) ...)
  16045. @end example
  16046. @subsection R7RS explicit library modules
  16047. A R7RS @code{define-library} form is another way to create a module.
  16048. The R7RS term @dfn{library} is roughly the same as a Kawa module.
  16049. In Kawa, each source file is a @ref{implicit library,@dfn{implicit module}},
  16050. which may contain zero or more explicit sub-modules (in
  16051. the form of @code{define-library}) optionally followed by
  16052. the definitions and expressions of the implicit (file-level) module.
  16053. @anchor{meta-library-definition}
  16054. @findex @i{library-definition}
  16055. @deffn Syntax define-library @stxref{library-name} @arbno{@stxref{library-declaration}}
  16056. @end deffn
  16057. @display
  16058. @stxdef{library-name} @stxlit{(} @stxref{library-name-parts} @stxlit{)}
  16059. @stxdef{library-name-parts} @atleastone{@var{identifier}}
  16060. @end display
  16061. A @meta{library-name} is a list whose members are identifiers and
  16062. exact non-negative integers. It is used to identify the library
  16063. uniquely when importing from other programs or
  16064. libraries. Libraries whose first identifier is @code{scheme} are
  16065. reserved for use by the R7RS report and future versions of that
  16066. report. Libraries whose first identifier is @code{srfi} are reserved
  16067. for libraries implementing @uref{http://srfi.schemer.org/,Scheme Requests for Implementation}.
  16068. It is inadvisable, but not an error, for identifiers
  16069. in library names to contain any of the characters @code{|} @code{\} @code{?}
  16070. @code{*} @code{<} @code{"} @code{:} @code{>} @code{+} @code{[} @code{]}
  16071. @code{/} @code {.} or control characters after escapes are
  16072. expanded.
  16073. See @ref{module-name} for how a @meta{library-name} is
  16074. mapped to a class name.
  16075. @display
  16076. @stxdef{library-declaration}
  16077. @stxref{export-declaration}
  16078. | @stxref{import-declaration}
  16079. | @stxlit{(begin} @arbno{@stxref{statement}} @stxlit{)}
  16080. | @stxlit{(include} @atleastone{@meta{filename}}@stxlit{)}
  16081. | @stxlit{(include-ci} @atleastone{@meta{filename}}@stxlit{)}
  16082. | @stxlit{(include-library-declarations} @atleastone{@meta{filename}}@stxlit{)}
  16083. | @stxlit{(cond-expand} @arbno{@stxref{cond-expand-clause}} [@stxlit{(else} command-or-definition*@stxlit{)}]@stxlit{)}
  16084. | @stxref{statement}
  16085. @end display
  16086. The @code{begin}, @code{include}, and @code{include-ci} declarations are
  16087. used to specify the body of the library. They have the
  16088. same syntax and semantics as the corresponding expression types.
  16089. This form of @code{begin} is analogous to, but not the
  16090. same as regular @code{begin}.
  16091. A plain @meta{statement} (which is allowed as a Kawa extension)
  16092. is also part of the body of the library,
  16093. as if it were wrapped in a @code{begin}).
  16094. The @code{include-library-declarations} declaration is similar
  16095. to @code{include} except that the contents of the file are
  16096. spliced directly into the current library definition. This
  16097. can be used, for example, to share the same @code{export} declaration
  16098. among multiple libraries as a simple form of library interface.
  16099. The @code{cond-expand} declaration has the same syntax and semantics
  16100. as the @code{cond-expand} expression type, except that
  16101. it expands to spliced-in library declarations rather than
  16102. expressions enclosed in @code{begin}.
  16103. When a library is loaded, its expressions are executed in
  16104. textual order. If a library’s definitions are referenced in
  16105. the expanded form of a program or library body, then that
  16106. library must be loaded before the expanded program or
  16107. library body is evaluated. This rule applies transitively. If
  16108. a library is imported by more than one program or library,
  16109. it may possibly be loaded additional times.
  16110. Similarly, during the expansion of a library @code{(foo)}, if any
  16111. syntax keywords imported from another library @code{(bar)} are
  16112. needed to expand the library, then the library @code{(bar)} must
  16113. be expanded and its syntax definitions evaluated before the
  16114. expansion of @code{(foo)}.
  16115. Regardless of the number of times that a library is loaded,
  16116. each program or library that imports bindings from a library must
  16117. do so from a single loading of that library, regardless
  16118. of the number of import declarations in which it
  16119. appears. That is, @code{(import (only (foo) a})) followed by
  16120. @code{(import (only (foo) b))} has the same effect as
  16121. @code{(import (only (foo) a b))}.
  16122. @subsection How a module becomes a class
  16123. If you want to just use a Scheme module as a module (i.e. @code{load}
  16124. or @code{require} it), you don't care how it gets translated
  16125. into a module class. However, Kawa gives you some control over how this
  16126. is done, and you can use a Scheme module to define a class which
  16127. you can use with other Java classes. This style of class definition
  16128. is an alternative to @code{define-class},
  16129. which lets you define classes and instances fairly conveniently.
  16130. The default name of the module class is the main part of the
  16131. filename of the Scheme source file (with directories and extensions
  16132. stripped off). That can be overridden by the @code{-T} Kawa
  16133. command-line flag. The package-prefix specified by the @code{-P}
  16134. flag is prepended to give the fully-qualified class name.
  16135. @anchor{module-name}
  16136. @deffn Syntax module-name name
  16137. @deffnx Syntax module-name <name>
  16138. @deffnx Syntax module-name @stxref{library-name}
  16139. Sets the name of the generated class, overriding the default.
  16140. If there is no @samp{.} in the @var{name}, the package-prefix
  16141. (specified by the @code{-P} Kawa command-line flag) is prepended.
  16142. If the form @meta{library-name} is used,
  16143. then the class name is the result of taking
  16144. each @meta{identifier} in the @meta{library-name-parts},
  16145. @ref{Mangling,mangling} if needed, and concatenating them
  16146. separated by periods.
  16147. For example @code{(org example doc-utils)} becomes
  16148. @code{org.example.doc-utils}. (You can't reference the class name
  16149. @code{doc-utils} directly in Java, but the JVM has no problems with it.
  16150. In Java you can use reflection to access classes with such names.)
  16151. As a matter of style, @code{module-name} should be the first
  16152. command in a file (after possible comments). It must appear
  16153. before a @code{require} or @code{import}, in case of cycles.
  16154. @end deffn
  16155. By default, the base class of the generated module class is unspecified;
  16156. you cannot count on it being more specific than @code{Object}.
  16157. However, you can override it with @code{module-extends}.
  16158. @deffn Syntax module-extends class
  16159. Specifies that the class generated from the immediately surrounding
  16160. module should extend (be a sub-class of) the class @code{@var{class}}.
  16161. @end deffn
  16162. @deffn Syntax module-implements interface ...
  16163. Specifies that the class generated from the immediately surrounding
  16164. module should implement the interfaces listed.
  16165. @end deffn
  16166. Note that the compiler does @emph{not} currently check that all the
  16167. abstract methods requires by the base class or implemented interfaces
  16168. are actually provided, and have the correct signatures. This will
  16169. hopefully be fixed, but for now, if you are forgot a method, you will
  16170. probably get a verifier error
  16171. For each top-level exported definition the compiler creates a
  16172. corresponding public field with a similar (mangled) name.
  16173. By default, there is some indirection: The value of the Scheme variable
  16174. is not that of the field itself. Instead, the field is a
  16175. @code{gnu.mapping.Location} object, and the value Scheme variable is
  16176. defined to be the value stored in the @code{Location}.
  16177. Howewer, if you specify an explicit type, then the field will
  16178. have the specified type, instead of being a @code{Location}.
  16179. The indirection using @code{Location} is also avoided if you use
  16180. @code{define-constant}.
  16181. If the Scheme definition defines a procedure (which is not re-assigned
  16182. in the module), then the compiler assumes the variable as bound as a
  16183. constant procedure. The compiler generates one or more methods
  16184. corresponding to the body of the Scheme procedure. It also generates
  16185. a public field with the same name; the value of the field is an
  16186. instance of a subclass of @code{<gnu.mapping.Procedure>} which when
  16187. applied will execute the correct method (depending on the actual arguments).
  16188. The field is used when the procedure used as a value (such as being passed
  16189. as an argument to @code{map}), but when the compiler is able to do so,
  16190. it will generate code to call the correct method directly.
  16191. You can control the signature of the generated method by declaring
  16192. the parameter types and the return type of the method. See the
  16193. applet (@pxref{Applet compilation}) example for how this can be done.
  16194. If the procedures has optional parameters, then the compiler will
  16195. generate multiple methods, one for each argument list length.
  16196. (In rare cases the default expression may be such that this is
  16197. not possible, in which case an "variable argument list" method
  16198. is generated instead. This only happens when there is a nested
  16199. scope @emph{inside} the default expression, which is very contrived.)
  16200. If there are @code{#!keyword} or @code{#!rest} arguments, the compiler
  16201. generate a "variable argument list" method. This is a method whose
  16202. last parameter is either an array or a @code{<list>}, and whose
  16203. name has @code{$V} appended to indicate the last parameter is a list.
  16204. Top-leval macros (defined using either @code{define-syntax}
  16205. or @code{defmacro}) create a field whose type is currently a sub-class of
  16206. @code{kawa.lang.Syntax}; this allows importing modules to detect
  16207. that the field is a macro and apply the macro at compile time.
  16208. Unfortunately, the Java class verifier does not allow fields to have
  16209. arbitrary names. Therefore, the name of a field that represents a
  16210. Scheme variable is "mangled" (@pxref{Mangling}) into an acceptable Java name.
  16211. The implementation can recover the original name of a field @code{X}
  16212. as @code{((gnu.mapping.Named) X).getName()} because all the standard
  16213. compiler-generated field types implement the @code{Named} interface.
  16214. @anchor{dual-purpose-class}
  16215. @subsection Same class for module and defined class
  16216. You can declare a class using @code{define-simple-class}
  16217. with the same name as the module class, for example the
  16218. following in a file named @code{foo.scm}:
  16219. @example
  16220. (define-simple-class foo ...)
  16221. @end example
  16222. In this case the defined class will serve dual-purpose as the module class.
  16223. To avoid confusion, in this case you must not specify
  16224. @code{module-extends}, @code{module-implements}, or @code{(module-static #t)}.
  16225. Also, the defined class should not have public static members.
  16226. In that case it works out pretty well: public static members
  16227. represent bindings exported by the module; other non-private members
  16228. ``belong'' to the defined class.
  16229. In this case @code{(module-static 'init-run)} is implied.
  16230. @anchor{static-or-non-modules}
  16231. @subsection Static vs non-static modules
  16232. There are two kinds of module class:
  16233. A @dfn{static module} is a class (or gets compiled to a class)
  16234. all of whose public fields are static, and that does not have a
  16235. public constructor. A JVM can only have a single global instance of
  16236. a static module.
  16237. An @dfn{instance module} has a public default constructor,
  16238. and usually has at least one non-static public field.
  16239. There can be multiple instances
  16240. of an instance module; each instance is called a @dfn{module instance}.
  16241. However, only a single instance of a module can be @dfn{registered}
  16242. in an environment, so in most cases there is only a single
  16243. instance of instance modules. Registering an instance in an environment
  16244. means creating a binding mapping a magic name (derived from the class name)
  16245. to the instance.
  16246. In fact, any Java class class that has the properties of either
  16247. an instance module or a static module, is a module, and can be
  16248. loaded or imported as such; the class need not have written
  16249. using Scheme.
  16250. You can control whether a module is compiled to a static or
  16251. a non-static class using either a command-line flag to the compiler,
  16252. or using the @code{module-static} special form.
  16253. @table @code
  16254. @item --module-static
  16255. Generate a static module
  16256. (as if @code{(module-static #t)} were specified).
  16257. This is (now) the default.
  16258. @item --module-nonstatic
  16259. @itemx --no-module-static
  16260. Generate a non-static module
  16261. (as if @code{(module-static #f)} were specified).
  16262. This used to be the default.
  16263. @item --module-static-run
  16264. Generate a static module
  16265. (as if @code{(module-static 'init-run)} were specified).
  16266. @end table
  16267. @deffn Syntax module-static name ...
  16268. @deffnx Syntax module-static @code{#t}
  16269. @deffnx Syntax module-static @code{#f}
  16270. @deffnx Syntax module-static @code{'init-run}
  16271. Control whether the generated fields and methods are static.
  16272. If @code{#t} or @code{'init-run} is specified, then the module will be a
  16273. static module, @emph{all} definitions will be static.
  16274. If @code{'init-run} is specified, in addition the module body
  16275. is evaluated in the class's static initializer.
  16276. (Otherwise, it is run the first time it is @code{require}'d.)
  16277. Otherwise, the module is an instance module. If there is a non-empty
  16278. list of @var{name}s then the module is an instance module, but the @var{name}s
  16279. that are explicitly listed will be compiled to static fields and methods.
  16280. If @code{#f} is specified, then all exported names will
  16281. be compiled to non-static (instance) fields and methods.
  16282. By default, if no @code{module-static} is specified:
  16283. @enumerate
  16284. @item
  16285. If there is a @code{module-extends} or @code{module-implements}
  16286. declaration, or one of the @code{--applet} or @code{--servlet}
  16287. command-line flags was specified, then @code{(module-static #f)} is implied.
  16288. @item
  16289. If one of the command-line flags
  16290. @code{--no-module-static}, @code{--module-nonstatic},
  16291. @code{--module-static}, or @code{--module-static-run} was specified,
  16292. then the default is @code{#f}, @code{#f}, @code{#t}, or @code{'init-run},
  16293. respectively.
  16294. @item
  16295. If the module class is @ref{dual-purpose-class,dual-purpose}
  16296. then @code{(module-static 'init-run)} is implied.
  16297. @item
  16298. Otherwise the default is @code{(module-static #t)}.
  16299. (It used to be @code{(module-static #f)} in older Kawa versions.)
  16300. @end enumerate
  16301. The default is @code{(module-static #t)}. It usually produces more efficient
  16302. code, and is recommended if a module contains only procedure or macro
  16303. definitions. However, a static module means that all environments in a JVM
  16304. share the same bindings, which you may not want if you use
  16305. multiple top-level environments.
  16306. @end deffn
  16307. The top-level actions of a module will get compiled to a @code{run}
  16308. method. If there is an explicit @code{method-extends}, then the
  16309. module class will also automatically implement @code{java.lang.Runnable}.
  16310. (Otherwise, the class does not implement @code{Runnable}, since in that
  16311. case the @code{run} method return an @code{Object} rather than @code{void}.
  16312. This will likely change.)
  16313. @subsection Module options
  16314. Certain compilation options can be be specified @emph{either}
  16315. on the command-line when compiling, or in the module itself.
  16316. @deffn Syntax module-compile-options [key@stxlit{:} value] ...
  16317. This sets the value of the @code{key} option to @code{value}
  16318. for the current module (source file). It takes effect as
  16319. soon it is seen during the first macro-expansion pass,
  16320. and is active thereafter (unless overridden by @code{with-compile-options}).
  16321. The @var{key:} is one of the supported option names
  16322. (The ending colon makes it a Kawa keyword). Valid
  16323. option keys are:
  16324. @itemize @bullet
  16325. @item
  16326. @stxlit{main:} - Generate an application, with a main method.
  16327. @end itemize
  16328. @itemize @bullet
  16329. @item
  16330. @stxlit{full-tailcalls:} - Use a calling convention that supports proper tail recursion.
  16331. @end itemize
  16332. @itemize @bullet
  16333. @item
  16334. @stxlit{warn-undefined-variable:} - Warn if no compiler-visible binding for a variable.
  16335. @item
  16336. @stxlit{warn-unknown-member:} - Warn if referencing an unknown method or field.
  16337. @item
  16338. @stxlit{warn-invoke-unknown-method:} - Warn if invoke calls an unknown method (subsumed by warn-unknown-member).
  16339. @item
  16340. @stxlit{warn-unused:} - Warn if a variable is usused or code never executed.
  16341. @item
  16342. @stxlit{warn-uninitialized:} - Warn if accessing an uninitialized variable.
  16343. @item
  16344. @stxlit{warn-unreachable:} - Warn if this code can never be executed.
  16345. @item
  16346. @stxlit{warn-void-used:} - Warn if an expression depends on the value of a void sub-expression (one that never returns a value).
  16347. @item
  16348. @stxlit{warn-as-error:} - Treat a compilation warning as if it were an error.
  16349. @end itemize
  16350. The @var{value} must be a literal value: either a boolean
  16351. (@code{#t} or @code{#f}), a number, or a string,
  16352. depending on the @var{key}.
  16353. (All the options so far are boolean options.)
  16354. @example
  16355. (module-compile-options warn-undefined-variable: #t)
  16356. ;; This causes a warning message that y is unknown.
  16357. (define (func x) (list x y))
  16358. @end example
  16359. @end deffn
  16360. @deffn Syntax with-compile-options [key: value] ... body
  16361. Similar to @code{module-compile-options}, but the option
  16362. is only active within @var{body}.
  16363. The module option key @code{main:} has no effect when applied
  16364. to a particular body via the @code{with-compile-options} syntax.
  16365. @example
  16366. (define (func x)
  16367. (with-compile-options warn-invoke-unknown-method: #f
  16368. (invoke x 'size)))
  16369. @end example
  16370. @end deffn
  16371. @node Importing
  16372. @section Importing from a library
  16373. @anchor{require}
  16374. You can import a module into the current namespace with @code{import} or @code{require}. This adds the exported bindings (or a subset of them) to the
  16375. current lexical scope. It follows that these bindings (which are said
  16376. to be imported) are determined at compile-time.
  16377. @anchor{meta-import-declaration}
  16378. @deffn Syntax import @arbno{@stxref{import-set}}
  16379. An @code{import} declaration provides a way to import identifiers
  16380. exported by a library (module). Each @meta{import-set} names a set of
  16381. bindings from a library and possibly specifies local names
  16382. for the imported bindings.
  16383. @display
  16384. @stxdef{import-set}
  16385. @meta{classname}
  16386. | @stxref{library-reference}
  16387. | @stxlit{(library} @stxref{library-reference} @stxlit{)}
  16388. | @stxlit{(class} @var{class-prefix} @arbno{@var{import-only-name}}@stxlit{)}
  16389. | @stxlit{(only} @stxref{import-set} @arbno{@var{import-only-name}}@stxlit{)}
  16390. | @stxlit{(except} @stxref{import-set} @arbno{@var{identifier}}@stxlit{)}
  16391. | @stxlit{(prefix} @stxref{import-set} @var{identifier} @stxlit{)}
  16392. | @stxlit{(rename} @stxref{import-set} @arbno{@stxref{rename-pair}}@stxlit{)}
  16393. @stxdef{library-reference} @stxlit{(} @stxref{library-name-parts} [@stxref{explicit-source-name}]@stxlit{)}
  16394. @stxdef{import-only-name} @var{identifier}|@stxref{rename-pair}
  16395. @stxdef{explicit-source-name} @stxref{string}
  16396. @stxdef{rename-pair} @stxlit{(} @var{identifier}@sub{1} @var{identifier}@sub{2}@stxlit{)}
  16397. @end display
  16398. A @var{library-reference} is mapped to a class name by concatenating
  16399. all the identifiers, separated by dots.
  16400. For example:
  16401. @example
  16402. (import (gnu kawa slib srfi37))
  16403. @end example
  16404. is equivalent to:
  16405. @example
  16406. (import gnu.kawa.slib.srfi37)
  16407. @end example
  16408. as well as to:
  16409. @example
  16410. (require gnu.kawa.slib.srfi37)
  16411. @end example
  16412. By default, all of an imported library's exported bindings are made
  16413. visible within an importing library using the names given to the
  16414. bindings by the imported library. The precise set of bindings to be
  16415. imported and the names of those bindings can be adjusted with the
  16416. @code{only}, @code{except}, @code{prefix}, and @code{ rename} forms as
  16417. described below.
  16418. @itemize
  16419. @item
  16420. An @code{only} form produces a subset of the bindings from another
  16421. @meta{import-set}, including only the listed @meta{identifier}s. The
  16422. included @meta{identifier}s must be in the original @meta{import-set}.
  16423. If a @var{rename-pair} is used, then the @code{@var{identifier}@sub{1}}
  16424. must be in the original @meta{import-set},
  16425. and is renamed to @code{@var{identifier}@sub{2}}. For example:
  16426. @example
  16427. (import (only (kawa example) A (B1 B2) C (D1 D2)))
  16428. @end example
  16429. is equivalent to:
  16430. @example
  16431. (import (rename (only (kawa example) A B1 C D1)
  16432. (B1 B2) (D1 D2)))
  16433. @end example
  16434. The names @code{A}, @code{B1}, @code{C}, and @code{D1} must
  16435. exist in the library @code{(kawa example)}. The bindings are
  16436. accessible using the names @code{A}, @code{B2}, @code{C}, and @code{D2}.
  16437. @item
  16438. An @code{except} form produces a subset of the bindings from another
  16439. @meta{import-set}, including all but the listed @meta{identifier}s. All
  16440. of the excluded @meta{identifier}s must be in the original @meta{import-set}.
  16441. @item
  16442. A @code{prefix} form adds the @meta{identifier} prefix to each name from
  16443. another @meta{import-set}.
  16444. @item
  16445. A @code{rename} form:
  16446. @example
  16447. (rename (@var{identifier}@sub{1} @var{identifier}@sub{2}) @dots{})
  16448. @end example
  16449. @noindent
  16450. removes the bindings for @code{@var{identifier}@sub{1} @dots{}} to form an
  16451. intermediate @meta{import-set}, then adds the bindings back for the
  16452. corresponding @code{@var{identifier}@sub{2} @dots{}} to form the final
  16453. @meta{import-set}. Each @code{@var{identifier}@sub{1}} must be in the original
  16454. @meta{import-set}, each @var{identifier}@sub{2} must not be in the
  16455. intermediate @meta{import-set}, and the @var{identifier}@sub{2}s must be
  16456. distinct.
  16457. @end itemize
  16458. A @code{class} form is a convenient way to define abbreviations
  16459. for class names; it may be more convenient than @code{define-alias}.
  16460. The @var{class-prefix} is concatenated with each @meta{identifier}
  16461. (with a period in between) to produce a classname.
  16462. Each @meta{identifier} becomes an alias for the class.
  16463. For example:
  16464. @example
  16465. (import (class java.util Map (HashMap HMap)))
  16466. @end example
  16467. This defines @code{Map} as an alias for @code{java.util.Map},
  16468. and @code{HMap} as an alias for @code{java.util.HashMap}.
  16469. (You can think of the @code{class} form as similar to a @code{only} form,
  16470. where the @var{class-prefix} names a special kind of
  16471. library represented of a Java package, and whose exported
  16472. bindings are the classes in the package.)
  16473. You can combine the @code{class} form with
  16474. @code{only}, @code{except}, @code{rename}, and @code{prefix},
  16475. though only @code{prefix} is likely to be useful. For example:
  16476. @example
  16477. (import (prefix (class java.lang Long Short) jl-))
  16478. @end example
  16479. is equivalent to
  16480. @example
  16481. (import (class java.lang (Long jl-Long) (Short jl-Short)))
  16482. @end example
  16483. which is equivalent to:
  16484. @example
  16485. (define-private-alias jl-Short java.lang.Short)
  16486. (define-private-alias jl-Long java.lang.Long)
  16487. @end example
  16488. @end deffn
  16489. @deffn Syntax require @stxlit{'}featureName
  16490. @deffnx Syntax require classname [@stxref{explicit-source-name}]
  16491. @deffnx Syntax require @stxref{explicit-source-name}]
  16492. Search for a matching module (class), and add the names
  16493. exported by that module to the current set of visible names.
  16494. Normally, the module is specified using @var{classname}.
  16495. The form @code{require} has similar functionality as @code{import},
  16496. but with a different syntax, and without options like @code{rename}.
  16497. If a @code{@stxlit{"}@var{sourcepath}@stxlit{"}} is specified then
  16498. that is used to locate the source file for the module, and if necessary,
  16499. compile it.
  16500. If a @code{'@var{featurename}} is specified then the
  16501. @var{featurename} is looked up (at compile time) in the "feature table"
  16502. which yields the implementing @var{classname}.
  16503. @end deffn
  16504. @deffn Syntax provide @stxlit{'}featurename
  16505. Declare that @code{'@var{featurename}} is available.
  16506. A following @code{cond-expand} in this scope will match @var{featurename}.
  16507. @end deffn
  16508. Using @code{require} and @code{provide} with @var{featurename}s is
  16509. similar to the same-named macros in SLib, Emacs, and Common Lisp.
  16510. However, in Kawa these are not functions, but instead they
  16511. are syntax forms that are processed at compile time. That is
  16512. why only quoted @var{featurename}s are supported.
  16513. This is consistent with Kawa emphasis on compilation and
  16514. static binding.
  16515. For some examples, you may want to look in the @code{gnu/kawa/slib}
  16516. directory.
  16517. @subsection Searching for modules
  16518. When Kawa sees a @code{import} or @code{require} it searches for
  16519. either a matching source file or a previously-compiled class with a
  16520. matching name.
  16521. For @code{import} we generate a classname by converting it in the same
  16522. way @code{module-name} does: taking each identifier in the
  16523. @meta{library-name-parts}, mangling if needed, and concatenating the parts
  16524. separated by periods.
  16525. If there is a matching module in any @meta{program-unit} that is
  16526. in the process of being compiled, we use that. This may be
  16527. a file requested to be compiled with the @code{-C} command-line switch,
  16528. or an extra @meta{library-definition} in a file already parsed.
  16529. Kawa will attempt to finish compiling the module and load the class,
  16530. but if there are circular dependencies it will use the uncompiled definitions.
  16531. Next Kawa looks for a matching class in the context classpath.
  16532. (There is special handling if the library-name starts with @code{srfi},
  16533. and certain builtin classes will have @code{kawa.lib.} prepended.)
  16534. Kawa also searches for a matching source file, described below.
  16535. It uses the implicit source name (formed by concatenating the
  16536. library-name parts, separated by @code{"/"}), as well as
  16537. any @meta{explicit-source-name}. The source file is parsed as
  16538. a @stxref{program-unit}. It is an error if the @meta{program-unit}
  16539. does not declare a library (explicit or implicit) with the
  16540. matching name.
  16541. If Kawa finds both a matching source file and a class, it will pick one
  16542. based on which is newer.
  16543. @subsection Searching for source files
  16544. The Java property @code{kawa.import.path} controls how @code{import}
  16545. and @code{require} search for a suitable source file. Example usage:
  16546. @example
  16547. $ kawa -Dkawa.import.path=".:<foo fo>/opt/fo-libs/*.scm:/usr/local/kawa"
  16548. @end example
  16549. The value of the @code{kawa.import.path} property is a list of
  16550. path elements, separated by @code{":"}.
  16551. Each path element is combined with either the explicit source name
  16552. or the implicit source name to produce a filename.
  16553. If a matching file exists, then we have found a source file.
  16554. If a path element contains a @code{"*"} then the @code{"*"}
  16555. is replaced by the implicit source name (without an extension).
  16556. (Any explicit source name is ignored in this case.)
  16557. For example, for @code{(import (foo bar))} or @code{(require foo.bar)}
  16558. the implicit source name is @code{"foo/bar"}. If the path element is
  16559. @code{"/opt/kawa/*.sc"} then the resulting filename is @code{"/opt/kawa/foo/bar.sc"}.
  16560. If there is no @code{"*"} in the path element, and there is an
  16561. explicit source, then it is appended to the path element
  16562. (or replaces the path element if the explicit source is absolute).
  16563. Otherwise we use the implicit source, followed by the default file extension.
  16564. (The default file extension is that of the current source if that is a
  16565. named file; otherwise the default for the current language, which
  16566. is @code{".scm"} for Scheme.)
  16567. A path element that starts with a selector of the
  16568. form @code{"<@stxref{library-name-parts}>"} is only applicable if a prefix
  16569. of the requested module name matches the @meta{library-name-parts}. If there
  16570. is @code{"*"} in the path element, that is replaced by the corresponding rest
  16571. of the implicit source name. For example if importing @code{(fee fo foo fum})
  16572. and the path element is @code{"<fee fo>/opt/fo-libs/*.scm"} then the
  16573. resulting filename is @code{"/opt/fo-libs/foo/fum.scm"}.
  16574. If there is a selector but no @code{"*"}, then the rest of the path element
  16575. following the selector is combined with the explicit or implicit source
  16576. as if there were no selector (assuming of course that the selector matches).
  16577. If the resulting filename is relative, then it is resolved
  16578. relative to the @dfn{current root}. For example the source to
  16579. a library with the name @code{(x y)} that compiles to
  16580. a class @code{x.y} might be a file named @code{/a/b/x/y.scm}.
  16581. Then the current root would be @code{/a/b/}
  16582. - that is the directory that results from removing the library name
  16583. suffix from the file name.
  16584. More generally: assume the current module has @math{N} name components.
  16585. For example the name @code{(x y)}
  16586. (with the class name @code{x.y}) has 2 components.
  16587. The current root is what you get when you take the current file name
  16588. (say @code{"/a/b/c/d.scm"}), and remove everything after
  16589. the @math{N}'th slash (@code{"/"}) from the end (say @code{"c/d.scm"};
  16590. what remains (e.g. @code{"/a/b/"} is the current root.
  16591. (If the current input source is not a named file,
  16592. use the value of @code{(current-path)} with a @code{"/"} appended.)
  16593. The default search path is @code{"."} - i.e. just search relative
  16594. to the current root.
  16595. @subsection Builtin libraries
  16596. The following libraries are bundled with Kawa:
  16597. @table @code
  16598. @item (scheme base)
  16599. @itemx (scheme case-lambda)
  16600. @itemx (scheme char)
  16601. @itemx (scheme complex)
  16602. @itemx (scheme cxr)
  16603. @itemx (scheme cxr)
  16604. @itemx (scheme eval)
  16605. @itemx (scheme inexact)
  16606. @itemx (scheme lazy)
  16607. @itemx (scheme load)
  16608. @itemx (scheme process-context)
  16609. @itemx (scheme read)
  16610. @itemx (scheme repl)
  16611. @itemx (scheme time)
  16612. @itemx (scheme write)
  16613. @itemx (scheme r5rs)
  16614. The above are standard libraries as defined by R7RS.
  16615. @item (rnrs arithmetic bitwise)
  16616. @itemx (rnrs hashtables)
  16617. @itemx (rnrs lists)
  16618. @itemx (rnrs programs)
  16619. @itemx (rnrs sorting)
  16620. @itemx (rnrs unicode)
  16621. The above are standard libraries as defined by R6RS.
  16622. @item (kawa reflect)
  16623. Defines procedures and syntax for acessing Java objects and members:
  16624. @code{as}
  16625. @code{field}
  16626. @code{instance?}
  16627. @code{invoke}
  16628. @code{invoke-static}
  16629. @code{invoke-special}
  16630. @code{make}
  16631. @code{primitive-throw}
  16632. @code{set-field!}
  16633. @code{set-static-field!}
  16634. @code{static-field}
  16635. @item (kawa expressions)
  16636. @itemx (kawa hashtable)
  16637. @itemx (kawa quaternions)
  16638. @itemx (kawa rotations)
  16639. @itemx (kawa regex)
  16640. @itemx (kawa string-cursors)
  16641. Various Kawa libraries @i{add details}.
  16642. @item (kawa base)
  16643. All the bindings by default available to the kawa top-level.
  16644. @end table
  16645. @subsection Importing a SRFI library
  16646. Importing a supported SRFI numbered @var{N} is conventionally
  16647. doing using a @code{(import (srfi @var{N}))}
  16648. or the older R6RS syntax @code{(import (srfi :@var{N}))} (with a colon, for historical reasons). You can also give it
  16649. a name, as specified by @uref{http://srfi.schemers.org/srfi-95/srfi-95.html,SRFI 95}. For example, any of these work:
  16650. @example
  16651. (import (srfi 95))
  16652. (import (srfi 95 sorting-and-merging))
  16653. (import (srfi :95))
  16654. (import (srfi :95 sorting-and-merging))
  16655. @end example
  16656. You can also use @code{(require 'srfi-@var{N})}:
  16657. @example
  16658. (require 'srfi-95)
  16659. @end example
  16660. @subsection Importing from a plain class
  16661. Note you can import from many classes, even if they weren't
  16662. compiled from a library-definition. The set of @code{public} fields
  16663. in a class are considered as the set of exported definitions,
  16664. with the names demangled as needed.
  16665. The module can be static module (all public fields must be static),
  16666. or an instance module (it has a public default constructor).
  16667. If an imported definition is a non-static field and if no module
  16668. instance for that class
  16669. has been registered in the current environment, then a new instance
  16670. is created and registered (using a "magic" identifier).
  16671. If the module class either inherits from @code{gnu.expr.ModuleBody}
  16672. or implements @code{java.lang.Runnable} then the corresponding @code{run}
  16673. method is executed. (This is done @emph{after} the instance is
  16674. registered so that cycles can be handled.) These actions (creating,
  16675. registering, and running the module instance) are done both at compile
  16676. time and at run time, if necessary.
  16677. All the imported fields of the module class are then incorporated
  16678. in the current set of local visible names in the current module.
  16679. (This is for both instance and static modules.)
  16680. This is done at compile time - no new bindings are created at run-time
  16681. (except for the magic binding used to register the module instance),
  16682. and the imported bindings are private to the current module.
  16683. References to the imported bindings will be compiled as field
  16684. references, using the module instance (except for static fields).
  16685. @node Record types
  16686. @section Record types
  16687. The @code{define-record-type} form can be used for creating new data
  16688. types, called record types. A predicate, constructor, and field
  16689. accessors and modifiers are defined for each record type.
  16690. The @code{define-record-type} feature is specified
  16691. by @uref{http://srfi.schemers.org/srfi-9/srfi-9.html,SRFI-9},
  16692. which is implemented by many modern Scheme implementations.
  16693. @deffn Syntax define-record-type @var{type-name} (@var{constructor-name} @var{field-tag} ...) @var{predicate-name} (@var{field-tag} @var{accessor-name} [@var{modifier-name}]) ...
  16694. The form @code{define-record-type} is generative: each use creates a new
  16695. record type that is distinct from all existing types, including other
  16696. record types and Scheme's predefined types. Record-type definitions may
  16697. only occur at top-level (there are two possible semantics for `internal'
  16698. record-type definitions, generative and nongenerative, and no consensus
  16699. as to which is better).
  16700. An instance of @code{define-record-type} is equivalent to the following definitions:
  16701. @itemize
  16702. @item
  16703. The @var{type-name} is bound to a representation of the record type
  16704. itself.
  16705. @item
  16706. The @var{constructor-name} is bound to a procedure that takes
  16707. as many arguments as there are @var{field-tag}s in the
  16708. @code{(@var{constructor-name} ...)} subform and returns
  16709. a new @var{type-name} record. Fields whose tags are listed with
  16710. @var{constructor-name} have the corresponding argument as their initial
  16711. value. The initial values of all other fields are unspecified.
  16712. @item
  16713. The @var{predicate-name} is a predicate that returns @code{#t}
  16714. when given a value returned by @var{constructor-name}
  16715. and @code{#f} for everything else.
  16716. @item
  16717. Each @var{accessor-name} is a procedure that takes a record of
  16718. type @var{type-name} and returns the current value of the corresponding field.
  16719. It is an error to pass an accessor a value which is not a record of the
  16720. appropriate type.
  16721. @item
  16722. Each @var{modifier-name} is a procedure that takes a record of
  16723. type @var{type-name} and a value which becomes the new value of
  16724. the corresponding field.
  16725. The result (in Kawa) is the empty value @code{#!void}.
  16726. It is an error to pass a
  16727. modifier a first argument which is not a record of the appropriate type.
  16728. @end itemize
  16729. Set!ing the value of any of these identifiers has no effect on the
  16730. behavior of any of their original values.
  16731. @end deffn
  16732. Here is an example of how you can define a record type named @code{pare}
  16733. with two fields @code{x} and @code{y}:
  16734. @example
  16735. (define-record-type pare
  16736. (kons x y)
  16737. pare?
  16738. (x kar set-kar!)
  16739. (y kdr))
  16740. @end example
  16741. The above defines @code{kons} to be a constructor,
  16742. @code{kar} and @code{kdr} to be accessors,
  16743. @code{set-kar!} to be a modifier,
  16744. and @code{pare?} to be a predicate for @code{pare}s.
  16745. @example
  16746. (pare? (kons 1 2)) @result{} #t
  16747. (pare? (cons 1 2)) @result{} #f
  16748. (kar (kons 1 2)) @result{} 1
  16749. (kdr (kons 1 2)) @result{} 2
  16750. (let ((k (kons 1 2)))
  16751. (set-kar! k 3)
  16752. (kar k)) @result{} 3
  16753. @end example
  16754. Kawa compiles the record type into a nested class.
  16755. If the @code{define-record-type} appears at module level,
  16756. the result is a class that is a member of the module class.
  16757. For example if the above @code{pare} class is define in a
  16758. module @code{parelib}, then the result is a class
  16759. named @code{pare} with the internal JVM name @code{parelib$pare}.
  16760. The @code{define-record-type} can appear inside a procedure,
  16761. in which case the result is an inner class.
  16762. The nested class has a name derived from
  16763. the @var{type-name}. If the @var{type-name} is valid Java class name,
  16764. that becomes the name of the Java class. If the @var{type-name} has
  16765. the form @code{<@var{name}>} (for example @code{<pare>}), then @var{name}
  16766. is used, if possible, for the Java class name. Otherwise, the name
  16767. of the Java class is derived by "mangling" the @var{type-name}.
  16768. In any case, the package is the same as that of the surrounding module.
  16769. Kawa generates efficient code for the resulting functions,
  16770. without needing to use run-time reflection.
  16771. @node Dynamic records, Method operations, Record types, Objects Classes and Modules
  16772. @section Creating New Record Types On-the-fly
  16773. Calling the @code{make-record-type} procedure creates a new record data
  16774. type at run-time, without any compile-time support.
  16775. It is primarily provided for compatibility; in most cases it is better
  16776. to use the @code{define-record-type} form (@pxref{Record types}).
  16777. @deffn Procedure make-record-type type-name field-names
  16778. Returns a @dfn{record-type descriptor}, a value representing a new data
  16779. type disjoint from all others. The @var{type-name} argument must be a
  16780. string, but is only used for debugging purposes (such as the printed
  16781. representation of a record of the new type). The @var{field-names}
  16782. argument is a list of symbols naming the @dfn{fields} of a record of the
  16783. new type. It is an error if the list contains any duplicates.
  16784. @end deffn
  16785. @c @deffn Procedure make-record-sub-type type-name field-names rtd
  16786. @c Returns a @dfn{record-type descriptor}, a value representing a new data
  16787. @c type, disjoint from all others. The @var{type-name} argument must be a
  16788. @c string. The @var{field-names} argument is a list of symbols naming the
  16789. @c additional @dfn{fields} to be appended to @var{field-names} of
  16790. @c @var{rtd}. It is an error if the combinded list contains any
  16791. @c duplicates.@refill
  16792. @c
  16793. @c Record-modifiers and record-accessors for @var{rtd} work for the new
  16794. @c record-sub-type as well. But record-modifiers and record-accessors for
  16795. @c the new record-sub-type will not neccessarily work for @var{rtd}.@refill
  16796. @c @end deffn
  16797. @deffn Procedure record-constructor rtd [field-names]
  16798. Returns a procedure for constructing new members of the type represented
  16799. by @var{rtd}. The returned procedure accepts exactly as many arguments
  16800. as there are symbols in the given list, @var{field-names}; these are
  16801. used, in order, as the initial values of those fields in a new record,
  16802. which is returned by the constructor procedure. The values of any
  16803. fields not named in that list are unspecified. The @var{field-names}
  16804. argument defaults to the list of field names in the call to
  16805. @code{make-record-type} that created the type represented by @var{rtd};
  16806. if the @var{field-names} argument is provided, it is an error if it
  16807. contains any duplicates or any symbols not in the default list.
  16808. @c In Kawa, @var{rtd} may be any @code{Class} that has a public default
  16809. @c constructor, as long as the @var{field-names} are public instance
  16810. @c fields. (The fields should have type @code{Object} -- unless you
  16811. @c know what you are doing!)
  16812. @end deffn
  16813. @deffn Procedure record-predicate rtd
  16814. Returns a procedure for testing membership in the type represented by
  16815. @var{rtd}. The returned procedure accepts exactly one argument and
  16816. returns a true value if the argument is a member of the indicated record
  16817. type; it returns a false value otherwise.
  16818. @c In Kawa, the returned procedure checks if the argument is an instance
  16819. @c of @var{rtd} or one of its sub-classes.
  16820. @end deffn
  16821. @c @deffn Procedure record-sub-predicate rtd
  16822. @c Returns a procedure for testing membership in the type represented by
  16823. @c @var{rtd} or its parents. The returned procedure accepts exactly one
  16824. @c argument and returns a true value if the argument is a member of the
  16825. @c indicated record type or its parents; it returns a false value
  16826. @c otherwise.@refill
  16827. @c @end deffn
  16828. @deffn Procedure record-accessor rtd field-name
  16829. Returns a procedure for reading the value of a particular field of a
  16830. member of the type represented by @var{rtd}. The returned procedure
  16831. accepts exactly one argument which must be a record of the appropriate
  16832. type; it returns the current value of the field named by the symbol
  16833. @var{field-name} in that record. The symbol @var{field-name} must be a
  16834. member of the list of field-names in the call to @code{make-record-type}
  16835. that created the type represented by @var{rtd}.
  16836. @end deffn
  16837. @deffn Procedure record-modifier rtd field-name
  16838. Returns a procedure for writing the value of a particular field of a
  16839. member of the type represented by @var{rtd}. The returned procedure
  16840. accepts exactly two arguments: first, a record of the appropriate type,
  16841. and second, an arbitrary Scheme value; it modifies the field named by
  16842. the symbol @var{field-name} in that record to contain the given value.
  16843. The returned value of the modifier procedure is unspecified. The symbol
  16844. @var{field-name} must be a member of the list of field-names in the call
  16845. to @code{make-record-type} that created the type represented by @var{rtd}.
  16846. @end deffn
  16847. @deffn Procedure record? obj
  16848. Returns a true value if @var{obj} is a record of any type and a false
  16849. value otherwise.
  16850. @end deffn
  16851. @deffn Procedure record-type-descriptor record
  16852. Returns a record-type descriptor representing the type of the given
  16853. record. That is, for example, if the returned descriptor were passed to
  16854. @code{record-predicate}, the resulting predicate would return a true
  16855. value when passed the given record.
  16856. @end deffn
  16857. @deffn Procedure record-type-name rtd
  16858. Returns the type-name associated with the type represented by rtd. The
  16859. returned value is @code{eqv?} to the @var{type-name} argument given in
  16860. the call to @code{make-record-type} that created the type represented by
  16861. @var{rtd}.@refill
  16862. @end deffn
  16863. @deffn Procedure record-type-field-names rtd
  16864. Returns a list of the symbols naming the fields in members of the type
  16865. represented by @var{rtd}. The returned value is @code{equal?} to the
  16866. field-names argument given in the call to @code{make-record-type} that
  16867. created the type represented by @var{rtd}.@refill
  16868. @end deffn
  16869. Records are extensions of the class @code{Record}.
  16870. These procedures use the Java 1.1 reflection facility.
  16871. @node Method operations, Allocating objects, Dynamic records, Objects Classes and Modules
  16872. @section Calling Java methods from Scheme
  16873. You can call a Java method as if it were a Scheme procedure
  16874. using various mechanisms.
  16875. @subsection Calling static methods using colon notation
  16876. The easiest way to invoke a static method is to use
  16877. @ref{Colon notation, colon notation}, specifically:
  16878. @display
  16879. @stxlit{(}@var{class-expression}@stxlit{:}@var{method-name} @var{argument} ...@stxlit{)}
  16880. @end display
  16881. The @var{class-expression} can be a class in the current lexical
  16882. scope, such as a class defined using @code{define-simple-class}:
  16883. @example
  16884. (define-simple-class MyClass ()
  16885. ((add2 x y) allocation: 'static (+ x y)))
  16886. (MyClass:add2 3 4) @result{} 7
  16887. @end example
  16888. Often @var{class-expression} is a fully-qualified class name:
  16889. @example
  16890. (java.lang.Math:sqrt 9.0) @result{} 3.0
  16891. @end example
  16892. This is only allowed when the name is of a class that exists
  16893. and is accessible both at compile-time and run-time,
  16894. and the name is not otherwise lexically bound.
  16895. You can also use a defined alias:
  16896. @example
  16897. (define-alias jlMath java.lang.Math)
  16898. (jlMath:sqrt 16.0) @result{} 4.0
  16899. @end example
  16900. You can even evaluate @var{class-expression} at run-time
  16901. (in which case Kawa may have to use slower reflection):
  16902. @example
  16903. (let ((math java.lang.Math)) (math:sqrt 9.0)) @result{} 3.0
  16904. @end example
  16905. Here @code{java.lang.Math} evaluates to a @code{java.lang.Class}
  16906. instance for the named class (like Java's @code{java.lang.Class.class},
  16907. again assuming the class exists and is accessible both at compile-time and
  16908. run-time, and the name is not otherwise lexically bound.
  16909. @subsection Calling instance methods using colon notation
  16910. The syntax is:
  16911. @display
  16912. @stxlit{(}@var{instance}@stxlit{:}@var{method-name} @var{argument} ...@stxlit{)}
  16913. @end display
  16914. This invokes the method named @var{method-name}
  16915. with the evaluated @var{instance} as the target object
  16916. and the evaluated @var{argument}s as the method arguments.
  16917. For example:
  16918. @example
  16919. ((list 9 8 7):toString) @result{} "(9 8 7)"
  16920. ([5 6 7]:get 2) @result{} 7
  16921. @end example
  16922. This older syntax is also available:
  16923. @display
  16924. @stxlit{(*:}@var{method-name} @var{instance} @var{argument} ...@stxlit{)}
  16925. @end display
  16926. For example:
  16927. @example
  16928. (*:toString (list 9 8 7))
  16929. @end example
  16930. You can also name the class explicitly:
  16931. @display
  16932. @stxlit{(}@var{class-expression}@stxlit{:}@var{method-name} @var{instance} @var{argument} ...@stxlit{)}
  16933. @end display
  16934. For example:
  16935. @example
  16936. (java.util.List:get [5 6 7] 2) @result{} 7
  16937. @end example
  16938. Using an explicit class is like coercing the @var{instance}:
  16939. @display
  16940. @stxlit{(*:}@var{method-name} @stxlit{(as }@var{class-expression} @var{instance} @stxlit{)}@var{argument} ...@stxlit{)}
  16941. @end display
  16942. Note that for some special values,
  16943. including @code{java.lang.Class} instances, you can't
  16944. use the compact form of @ref{Colon notation, colon notation}
  16945. where the @var{instance} is before the comma:
  16946. @example
  16947. (java.lang.Integer:getDeclaredField "MAX_VALUE") @result{} @i{error}
  16948. @end example
  16949. This is because in this case we look for a static member
  16950. of @code{java.lang.Integer}
  16951. (at least as currently defined and implemented),
  16952. while we want an instance member of @code{java.lang.Class}.
  16953. In those cases you can use one of
  16954. these alternative forms, which all return the same
  16955. @code{java.lang.reflect.Field} result:
  16956. @example
  16957. (*:getDeclaredField java.lang.Integer "MAX_VALUE")
  16958. (java.lang.Class:getDeclaredField java.lang.Integer "MAX_VALUE")
  16959. (invoke java.lang.Integer 'getDeclaredField "MAX_VALUE")
  16960. @end example
  16961. @subsection Method names
  16962. The method to invoke is selected using the specified
  16963. method name and argments. If specified name is not a Java name,
  16964. it is "mangled" (@pxref{Mangling}) into a valid Java name.
  16965. All accessible methods whose names match are considered.
  16966. Methods that match after appending @code{$V} or @code{$X} or @code{$V$X}
  16967. are also considered. A @code{$V} suffix matches a variable
  16968. number of arguments: any excess arguments are collect into an
  16969. @code{gnu.lists.LList} or a Java array (depending on the final parameter type).
  16970. A @code{$X} specifies that the method expects an extra implicit
  16971. @code{CallContext} parameter. In that case the method's result is written
  16972. to the @code{CallContext}, so the method result type must be @code{void}.
  16973. (Kawa may compile a procedure with a @code{#!rest} or keyword args
  16974. whose name is @code{@var{fn}} to a method named @code{@var{fn}$V}.
  16975. It adds an implicit parameter for the extra arguments.
  16976. By default this extra extra parameter is a Scheme list.
  16977. You can specify a Java array type instead, in which case the method is
  16978. named @code{@var{fn}} without the @code{$V},
  16979. and instead it is marked as a Java-5 varargs method.
  16980. The array element type must be compatible with all the extra arguments.)
  16981. @subsection Invoking a method with the @code{invoke} function
  16982. If you prefer, you can instead use the following functions.
  16983. (There is also an older deprecated lower-level interface
  16984. (@pxref{Low-level Method invocation}.)
  16985. @deffn Procedure invoke-static class name args ...
  16986. The @var{class} can be a @code{java.lang.Class}, a
  16987. @code{gnu.bytecode.ClassType}, or a @code{symbol} or @code{string}
  16988. that names a Java class. The @var{name} can be @code{symbol} or
  16989. @code{string} that names one or more methods in the Java class.
  16990. Any accessible methods (static or instance) in the specified @var{class}
  16991. (or its super-classes) that match "@var{name}" or "@var{name}$V" collectively
  16992. form a generic procedure. When the procedure is applied to the argument list,
  16993. the most specific applicable method is chosen depending on the
  16994. argument list; that method is then
  16995. called with the given arguments. Iff the method is an instance method,
  16996. the first actual argument is used as the @code{this} argument. If there are
  16997. no applicable methods (or no methods at all!), or there is no "best"
  16998. method, @code{WrongType} is thrown.
  16999. An example:
  17000. @example
  17001. (invoke-static java.lang.Thread 'sleep 100)
  17002. @end example
  17003. The behavior of interpreted code and compiled code is not
  17004. identical, though you should get the same result either way
  17005. unless you have designed the classes rather strangely. The
  17006. details will be nailed down later, but the basic idea is that
  17007. the compiler will "inline" the @code{invoke-static} call
  17008. if it can pick a single "best" matching method.
  17009. @end deffn
  17010. @deffn Procedure invoke object name args ...
  17011. The @var{name} can be @code{<symbol>} or
  17012. @code{<string>} that names one or more methods in the Java class.
  17013. Any accessible methods (static or instance) in the specified @var{class}
  17014. (or its super-classes) that match "@var{name}" or "@var{name}$V" collectively
  17015. form a generic procedure. When the procedure is applied to the argument list,
  17016. the most specific applicable method is chosen depending on the
  17017. argument list; that method is then
  17018. called with the given arguments. Iff the method is an instance method,
  17019. the @var{object} is used as the @code{this} argument;
  17020. otherwise @var{object} is prepended to the @var{args} list. If there are
  17021. no applicable methods (or no methods at all!), or there is no "best"
  17022. method, @code{WrongType} is thrown.
  17023. The behavior of interpreted code and compiled code is not
  17024. indentical, though you should get the same result either way
  17025. unless you have designed the classes rather strangely. The
  17026. details will be nailed down later, but the basic idea is that
  17027. the compiler will "inline" the @code{invoke-static} call
  17028. if it can pick a single "best" matching method.
  17029. If the compiler cannot determine the method to call (assuming
  17030. the method name is constant), the compiler has to generate code
  17031. at run-time to find the correct method. This is much slower,
  17032. so the compiler will print a warning. To avoid a waning, you can
  17033. use a type declaration, or insert a cast:
  17034. @example
  17035. (invoke (as java.util.Date my-date) 'setDate cur-date)
  17036. @end example
  17037. or
  17038. @example
  17039. (let ((my-date ::java.util.Date (calculate-date))
  17040. (cur-date ::int (get-cur-date)))
  17041. (invoke my-date 'setDate cur-date))
  17042. @end example
  17043. @end deffn
  17044. @deffn Procedure invoke-special class receiver-object name arg ...
  17045. The @var{class} can be a @code{java.lang.Class}, a
  17046. @code{gnu.bytecode.ClassType}, or a @code{symbol} or @code{string}
  17047. that names a Java class.
  17048. The @var{name} can be @code{symbol} or
  17049. @code{string} that names one or more methods in the Java class.
  17050. This procedure is very similar to @code{invoke} and @code{invoke-static}
  17051. and invokes the specified method, ignoring any methods in subclasses
  17052. that might overide it. One interesting use is to invoke a method in
  17053. your super-class like the Java language @code{super} keyword.
  17054. Any methods in the specified @var{class} that match "@var{name}" or
  17055. "@var{name}$V" collectively form a generic procedure. That generic
  17056. procedure is then applied as in @code{invoke} using the
  17057. @code{receiver-object} and the arguments (if any).
  17058. The compiler must be able to inline this procedure (because you cannot
  17059. force a specific method to be called using reflection). Therefore the
  17060. @var{class} and @var{name} must resolve at compile-time to a specific
  17061. method.
  17062. @example
  17063. (define-simple-class <MyClass> (<java.util.Date>)
  17064. ((get-year) :: <int>
  17065. (+ (invoke-special <java.util.Date> (this) 'get-year)) 1900)
  17066. ((set-year (year :: <int>)) :: <void>
  17067. (invoke-special <java.util.Date> (this) 'set-year (- year 1900))))
  17068. @end example
  17069. @end deffn
  17070. @deffn Procedure class-methods class name
  17071. Return a generic function containing those methods of @var{class}
  17072. that match the name @var{name}, in the sense of @code{invoke-static}.
  17073. Same as:
  17074. @example
  17075. (lambda args (apply invoke-static (cons class (cons name args))))
  17076. @end example
  17077. @end deffn
  17078. Some examples using these functions are @samp{vectors.scm}
  17079. and @samp{characters.scm} the directory @samp{kawa/lib} in
  17080. the Kawa sources.
  17081. @subsection Using a namespace prefix
  17082. @emph{This way of invoking a method is deprecated.}
  17083. You can use @code{define-namespace} to define an alias for a Java class:
  17084. @example
  17085. (define-namespace Int32 "class:java.lang.Integer")
  17086. @end example
  17087. In this example the name @code{Int32} is a @dfn{namespace alias}
  17088. for the namespace whose full name is @code{"class:java.lang.Integer"}.
  17089. The full name should be the 6 characters @code{"class:"} followed
  17090. by the fully-qualified name of a Java class.
  17091. Instead of a @var{vamespace-uri} you can use a variable that names
  17092. a class, usually of the form @code{<@var{classname}>}.
  17093. The following is equivalent to the above:
  17094. @example
  17095. (define-namespace Int32 <java.lang.Integer>)
  17096. @end example
  17097. However, there is one important difference: The @code{<@var{classname}>}
  17098. is first searched in the lexical scope.
  17099. It may resolve to a class defined in the current compilation unit
  17100. (perhaps defined using @code{define-simple-class}),
  17101. or imported from another module,
  17102. or an alias (such as from @code{define-alias}).
  17103. Only if @code{<@var{classname}>} is @emph{not} found in the current
  17104. scope is it tried as the class name @var{classname}.
  17105. You can name a method using a @dfn{qualified name} containing a colon.
  17106. The part of the name before the colon is a namespace alias (in
  17107. this case @code{Int32}), and the part of the name after the colon is the
  17108. method name. For example:
  17109. @example
  17110. (Int32:toHexString 255) @result{} "ff"
  17111. @end example
  17112. This invokes the static method @code{toHexString} in the
  17113. Java class @code{java.lang.Integer}, passing it the argument @code{255},
  17114. and returning the String @code{"ff"}.
  17115. The general syntax is
  17116. @example
  17117. (@var{prefix}:@var{method-name} @var{arg} ...)
  17118. @end example
  17119. This invokes the method named @var{method-name} in the class corresponding
  17120. to @var{prefix}, and the @var{arg}s are the method arguments.
  17121. You can use the method name @code{new} to construct new objects:
  17122. @example
  17123. (Int32:new '|255|)
  17124. @end example
  17125. This is equivalent to the Java expression @code{new Integer("255")}.
  17126. You can also write:
  17127. @example
  17128. (Int32:new "255")
  17129. @end example
  17130. You can also call instance methods using a namespace prefix:
  17131. @example
  17132. (Int32:doubleValue (Int32:new "00255"))
  17133. @end example
  17134. This returns the @code{double} value @code{255.0}.
  17135. As a shorthand, you can use the name of a Java class instead of a
  17136. namespace alias:
  17137. @example
  17138. (java.lang.Integer:toHexString 255)
  17139. (java.lang.Object:toString some-value)
  17140. @end example
  17141. If Kawa sees a qualified name with a prefix that is not defined @emph{and}
  17142. that matches the name of a known class, then Kawa will automatically
  17143. treat the prefix
  17144. as a nickname for namespace uri like @code{class:java.lang.Integer}.
  17145. Both conditions should be true at both compile-time and run-time.
  17146. However, using an explicit @code{define-namespace} is recommended.
  17147. As a final shorthand you can use an identifier in handle brackets,
  17148. such as an existing type alias like @code{<list>}.
  17149. The following are all equivalent:
  17150. @example
  17151. (<list>:list3 'a 'b 'c)
  17152. @end example
  17153. This is equivalent to:
  17154. @example
  17155. (define-namespace @var{prefix} <list>
  17156. (@var{prefix}:list3 'a 'b 'c)
  17157. @end example
  17158. for some otherwise-unused @var{prefix}.
  17159. @node Allocating objects, Field operations, Method operations, Objects Classes and Modules
  17160. @section Allocating objects
  17161. The recommended way to create an instance of a type @var{T}
  17162. is to ``call'' @var{T} as if it were a function, with the
  17163. arguments used to initialize the object.
  17164. If @code{T} is a class and @code{T} has a matching constructor,
  17165. then the arguments will used for constructor arguments:
  17166. @example
  17167. (java.util.StringTokenizer "this/is/a/test" "/")
  17168. @end example
  17169. (You can think of the type @var{T} as being
  17170. coerced to an instance-constructor function.)
  17171. If @code{T} is a container or collection type,
  17172. then typically the arguments will be used to specify
  17173. the child or component values.
  17174. Many standard Scheme procedures fit this convention.
  17175. For example in Kawa @code{list} and @code{vector} evaluate to
  17176. types, rather than procedures as in standard Scheme,
  17177. but because types can be used as constructor functions it just works:
  17178. @example
  17179. (list 'a (+ 3 4) 'c) @result{} (a 7 c)
  17180. (vector 'a 'b 'c) @result{} #(a b c)
  17181. @end example
  17182. Any class @code{T} that has a default constructor
  17183. and an @code{add} method can be initialized this way.
  17184. Examples are @code{java.util} collection classes,
  17185. and @code{jawa.awt} and @code{javax.swing} containers.
  17186. @example
  17187. (java.util.ArrayList 11 22 33) @result{} [11, 22, 333]
  17188. @end example
  17189. The above expression is equivalent to:
  17190. @example
  17191. (let ((tmp (java.util.ArrayList)))
  17192. (tmp:add 11)
  17193. (tmp:add 22)
  17194. (tmp:add 33)
  17195. tmp)
  17196. @end example
  17197. Allocating Java arrays (@pxref{Creating-new-Java-arrays}) uses a
  17198. similar pattern:
  17199. @example
  17200. (int[] 2 3 5 7 11)
  17201. @end example
  17202. Sometimes you want to set some named property to an initial value.
  17203. You can do that using a keyword argument. For example:
  17204. @example
  17205. (javax.swing.JButton text: "Do it!" tool-tip-text: "do it")
  17206. @end example
  17207. This is equivalent to using @dfn{setter methods}:
  17208. @example
  17209. (let ((tmp (javax.swing.JButton)))
  17210. (tmp:setText "Do it!")
  17211. (tmp:setToolTipText "do it")
  17212. tmp)
  17213. @end example
  17214. A keyword argument @code{@var{key-name}}@stxlit{:} can
  17215. can translated to either a @code{@stxlit{set}@var{KeyName}@stxlit{:}}
  17216. or a @code{@stxlit{add}@var{KeyName}@stxlit{:}} method.
  17217. The latter makes it convenient to add listeners:
  17218. @example
  17219. (javax.swing.JButton
  17220. text: "Do it!"
  17221. action-listener:
  17222. (object (java.awt.event.ActionListener)
  17223. ((actionPerformed e) (do-the-action))))
  17224. @end example
  17225. This is equivalent to:
  17226. @example
  17227. (let ((tmp (javax.swing.JButton)))
  17228. (tmp:setText "Do it!")
  17229. (tmp:addActionListener
  17230. (object (java.awt.event.ActionListener)
  17231. ((actionPerformed e) (do-the-action))))
  17232. tmp)
  17233. @end example
  17234. Making use of so-called ``SAM-conversion'' (@pxref{SAM-conversion})
  17235. makes it even more convenient:
  17236. @example
  17237. (javax.swing.JButton
  17238. text: "Do it!"
  17239. action-listener:
  17240. (lambda (e) (do-the-action)))
  17241. @end example
  17242. The general case allows for a mix of
  17243. constructor arguments, property keywords, and child values:
  17244. @display
  17245. @var{class-type} @stxref{constructor-value}... @stxref{property-initializer}... @stxref{child-value}...
  17246. @stxdef{constructor-value} @stxref{expression}
  17247. @stxdef{property-initializer} @stxref{keyword} @stxref{expression}
  17248. @stxdef{child-value} @stxref{expression}
  17249. @end display
  17250. First an object is constructed with the @var{constructor-value} arguments
  17251. (if any) passed to the object constructor;
  17252. then named properties (if any) are used to initialize named properties;
  17253. and then remaining arguments are used to add child values.
  17254. There is an ambiguity if there is no @var{property-initializer} -
  17255. we can't distinguish between a @var{constructor-value}
  17256. and a @var{child-value}.
  17257. In that case, if there is a matching constructor method, then all of the
  17258. arguments are constructor arguments;
  17259. otherwise, there must a default constructor, and all
  17260. of the arguments are @var{child-value} arguments.
  17261. There is a trick you can you if you need both
  17262. @var{constructor-value} and @var{child-value} arguments:
  17263. separate them with an ``empty keyword'' @code{||:}.
  17264. This matches a method named @code{add}, which means that
  17265. the next argument effectively a @var{child-value} - as do
  17266. all the remaining arguments. Example:
  17267. @example
  17268. (let ((vec #(1 2 3)))
  17269. (java.util.ArrayList vec ||: 4 5 6))
  17270. @result{} [1, 2, 3, 4, 5, 6]
  17271. @end example
  17272. The compiler rewrites these allocations expression
  17273. to generated efficient bytecode, assuming that the ``function''
  17274. being applied is a type known by the compiler.
  17275. Most of the above expressions also work if the type is applied
  17276. at run-time, in which case Kawa has to use slower reflection:
  17277. @example
  17278. (define iarr int[])
  17279. (apply iarr (list 3 4 5)) @result{} [3 4 5]
  17280. @end example
  17281. However @code{add@var{Xxx}} methods and SAM-conversion
  17282. are currently only recognized in the case of a class known at compile-time,
  17283. not at run-time.
  17284. Here is a working Swing demo illustrating many of these techniques:
  17285. @example
  17286. (import (class javax.swing
  17287. JButton Box JFrame))
  17288. (define-simple-class HBox (Box)
  17289. ((*init*) (invoke-special Box (this) '*init* 0)))
  17290. (define value 0)
  17291. (define txt
  17292. (javax.swing.JLabel
  17293. text: "0"))
  17294. (define (set-value i)
  17295. (set! value i)
  17296. (set! txt:text (number->string i)))
  17297. (define fr
  17298. (JFrame
  17299. title: "Hello!"
  17300. (Box 1#|VERTICAL|# ||:
  17301. (javax.swing.Box:createGlue)
  17302. txt
  17303. (javax.swing.Box:createGlue)
  17304. (HBox
  17305. (JButton ;; uses 1-argument constructor
  17306. "Decrement" ;; constructor argument
  17307. tool-tip-text: "decrement"
  17308. action-listener: (lambda (e) (set-value (- value 1))))
  17309. (javax.swing.Box:createGlue)
  17310. (JButton ;; uses 0-argument constructor
  17311. text: "Increment"
  17312. tool-tip-text: "increment"
  17313. action-listener: (lambda (e) (set-value (+ value 1))))))))
  17314. (fr:setSize 200 100)
  17315. (set! fr:visible #t)
  17316. @end example
  17317. If you prefer, you can use the older @code{make} special function:
  17318. @deffn Procedure make type args ...
  17319. Constructs a new object instance of the specified @var{type},
  17320. which must be either a @code{java.lang.Class} or a
  17321. @code{<gnu.bytecode.ClassType>}.
  17322. Equivalent to:
  17323. @example
  17324. @var{type} @var{args} ...
  17325. @end example
  17326. @end deffn
  17327. Another (semi-deprecated) function is to use the colon notation
  17328. with the @code{new} pseudo-function.
  17329. The following three are all equivalent:
  17330. @example
  17331. (java.awt.Point:new x: 4 y: 3)
  17332. (make java.awt.Point: x: 4 y: 3)
  17333. (java.awt.Point x: 4 y: 3)
  17334. @end example
  17335. @node Field operations, Mangling, Allocating objects, Objects Classes and Modules
  17336. @section Accessing object fields
  17337. @subsection Accessing static fields and properties
  17338. The recommmended way to access fields
  17339. uses the @ref{Colon notation, colon notation}.
  17340. For static fields and properties the following is recommended:
  17341. @display
  17342. @var{class-expression}@stxlit{:}@var{field-name}
  17343. @end display
  17344. For example:
  17345. @example
  17346. java.lang.Integer:MAX_VALUE
  17347. @end example
  17348. A property with a @code{get} method is equivalent to a field.
  17349. The following are all equivalent:
  17350. @example
  17351. java.util.Currency:available-currencies
  17352. java.util.Currency:availableCurrencies
  17353. (java.util.Currency:getAvailableCurrencies)
  17354. @end example
  17355. Just like for a method call, the @var{class-expression}
  17356. can be a class in the current lexical scope,
  17357. a fully-qualified class name, or more generally an
  17358. expression that evaluates to a class.
  17359. @subsection Accessing instance fields and properties
  17360. The syntax is:
  17361. @display
  17362. @var{instance}@stxlit{:}@var{field-name}
  17363. @end display
  17364. The @var{field-name} can of course be the name of an actual
  17365. object field, but it can also be the name of a property with
  17366. a zero-argument @code{get} method.
  17367. For example, if @code{cal} is a @code{java.util-Calendar} instance,
  17368. then the following are all equivalent:
  17369. @example
  17370. cal:time-zone
  17371. cal:timeZone
  17372. (cal:getTimeZone)
  17373. (cal:get-time-zone)
  17374. @end example
  17375. You can use colon notation to assign to a field:
  17376. @example
  17377. (set! cal:time-zone TimeZone:default)
  17378. @end example
  17379. which is equivalent to:
  17380. @example
  17381. (cal:setTimeZone (TimeZone:getDefault))
  17382. @end example
  17383. A Java array only has the @code{length} field, plus the @code{class} property:
  17384. @example
  17385. (int[] 4 5 6):length @result{} 3
  17386. (int[] 4 5 6):class:name @result{} "int[]"
  17387. @end example
  17388. @subsection Using field and static-field methods
  17389. The following methods are useful in cases where colon notation
  17390. is ambiguous, for example where there are both fields and methods
  17391. with the same name.
  17392. You might also prefer as a matter of style, to
  17393. emphasise that a field is being accessed.
  17394. @deffn Procedure field object fieldname
  17395. Get the instance field with the given @var{fieldname} from the given
  17396. @var{Object}. Returns the value of the field, which must be accessible.
  17397. This procedure has a @code{setter}, and so can be used as the first
  17398. operand to @code{set!}.
  17399. The field name is "mangled" (@pxref{Mangling}) into a valid Java name.
  17400. If there is no accessible field whose name is @code{"@var{fieldname}"},
  17401. we look for a no-argument method whose name is
  17402. @code{"get@var{Fieldname}"} (or @code{"is@var{Fieldname}"} for a
  17403. boolean property).
  17404. If @var{object} is a primitive Java array, then @var{fieldname} can only
  17405. be @code{'length}, and the result is the number of elements of the array.
  17406. @end deffn
  17407. @deffn Procedure static-field class fieldname
  17408. Get the static field with the given @var{fieldname} from the given
  17409. @var{class}. Returns the value of the field, which must be accessible.
  17410. This procedure has a @code{setter}, and so can be used as the first
  17411. operand to @code{set!}.
  17412. If the @var{fieldname} is the special name @code{class},
  17413. then it returns the @code{java.lang.Class} object corresponding to
  17414. @var{class} (which is usually a @code{gnu.bytecode.ClassType} object).
  17415. @end deffn
  17416. Examples:
  17417. @example
  17418. (static-field java.lang.System 'err)
  17419. ;; Copy the car field of b into a.
  17420. (set! (field a 'car) (field b 'car))
  17421. @end example
  17422. @deffn Procedure slot-ref object fieldname
  17423. A synonym for @code{(field @var{object} @var{fieldname})}.
  17424. @end deffn
  17425. @deffn Procedure slot-set! object fieldname value
  17426. A synonym for @code{(set! (field @var{object} @var{fieldname}) @var{value})}.
  17427. @end deffn
  17428. @subsection Older colon-dot notation
  17429. There is older syntax where following the colon
  17430. there is field name a following the colon @emph{and} a period.
  17431. To access an static field named @var{field-name} use this syntax
  17432. @example
  17433. (@var{prefix}:.@var{field-name} @var{instance})
  17434. @end example
  17435. The @var{prefix} can be as discussed in @xref{Method operations}.
  17436. Here are 5 equivalent ways:
  17437. @example
  17438. (java.lang.Integer:.MAX_VALUE)
  17439. (<java.lang.Integer>:.MAX_VALUE)
  17440. (define-namespace Int32 <java.lang.Integer>)
  17441. (Int32:.MAX_VALUE)
  17442. (define-namespace Integer "class:java.lang.Integer")
  17443. (Integer:.MAX_VALUE)
  17444. (define-alias j.l.Integer java.lang.Integer)
  17445. (j.l.Integer:.MAX_VALUE)
  17446. @end example
  17447. You can set a static field using this syntax:
  17448. @example
  17449. (set! (@var{prefix}:.@var{field-name}) @var{new-value})
  17450. @end example
  17451. The special field name @code{class} can be used to extract the
  17452. @code{java.lang.Class} object for a class-type. For example:
  17453. @example
  17454. (java.util.Vector:.class) @result{} class java.util.Vector
  17455. @end example
  17456. To access a instance field named @var{field-name} use the following syntax.
  17457. Note the period before the @var{field-name}.
  17458. @example
  17459. (*:.@var{field-name} @var{instance})
  17460. @end example
  17461. This syntax works with @code{set!} - to set the field use this syntax:
  17462. @example
  17463. (set! (*:.@var{field-name} @var{instance}) @var{new-value})
  17464. @end example
  17465. Here is an example:
  17466. @example
  17467. (define p (list 3 4 5))
  17468. (*:.cdr p) @result{} (4 5)
  17469. (set! (*:.cdr p) (list 6 7))
  17470. p @result{} (3 6 7)
  17471. @end example
  17472. You can specify an explicit class:
  17473. @example
  17474. (@var{prefix}:.@var{field-name} @var{instance})
  17475. @end example
  17476. If @var{prefix} is bound to @code{<@var{class}>}, then the above
  17477. is equivalent to:
  17478. @example
  17479. (*:.@var{field-name} (as <@var{class}> @var{instance}))
  17480. @end example
  17481. @node Mangling, Scheme types in Java, Field operations, Objects Classes and Modules
  17482. @section Mapping Scheme names to Java names
  17483. Programs use "names" to refer to various values and procedures.
  17484. The definition of what is a "name" is different in different
  17485. programming languages. A name in Scheme (and other Lisp-like
  17486. languages) can in principle contain any character (if using a
  17487. suitable quoting convention), but typically names consist of
  17488. "words" (one or more letters) separated by hyphens, such
  17489. as @samp{make-temporary-file}. Digits
  17490. and some special symbols are also used. Traditionally, Scheme is
  17491. case-insensitive; this means that the names @samp{loop},
  17492. @samp{Loop}, and @samp{LOOP} are all the same name. Kawa
  17493. is by default case-sensitive, but we recommend that you
  17494. avoid using upper-case letters as a general rule.
  17495. The Java language and the Java virtual machine uses names for
  17496. classes, variables, fields and methods.
  17497. Names in the Java language can contain upper- and lower-case letters,
  17498. digits, and the special symbols @samp{_} and @samp{$}.
  17499. The Java virtual machine (JVM) allows most characters, but still
  17500. has some limitations.
  17501. Kawa translates class names, package names, field names, and local variable
  17502. names using the
  17503. @uref{https://blogs.oracle.com/jrose/entry/symbolic_freedom_in_the_vm,''symbolic'' convention}, so most characters are unchanged.
  17504. For example the Scheme function @samp{file-exists?}
  17505. becomes the field @samp{file-exists?}, but @code{dotted.name}
  17506. becomes @samp{dotted\,name}.
  17507. Such names may not be valid Java name, so to access them from a
  17508. Java program you might have to use reflection.
  17509. When translating procedure names to method names,
  17510. Kawa uses a different translation, in order to achieve
  17511. more ``Java-like'' names. This means translating a
  17512. Scheme-style name like @samp{make-temporary-file} to
  17513. "mixed-case" words, such as @samp{makeTemporaryFile}.
  17514. The basic rule is simple: Hyphens are dropped, and
  17515. a letter that follows a hyphen is translated to its
  17516. upper-case (actually "title-case") equivalent. Otherwise,
  17517. letters are translated as is.
  17518. Some special characters are handled specially. A final @samp{?}
  17519. is replaced by an @emph{initial} @samp{is}, with the following
  17520. letter converted to titlecase. Thus @samp{number?} is
  17521. converted to @samp{isNumber} (which fits with Java conventions),
  17522. and @samp{file-exists?} is converted to @samp{isFileExists}
  17523. (which doesn't really).
  17524. The pair @samp{->} is translated to @samp{$To$}.
  17525. For example @samp{list->string} is translated to @samp{list$To$string}.
  17526. Some symbols are mapped to a mnemonic sequence, starting with a dollar-sign,
  17527. followed by a two-character abbreviation. For example, the less-than
  17528. symbol @samp{<} is mangled as @samp{$Ls}.
  17529. See the source code to the @code{mangleName} method in the
  17530. @code{gnu.expr.Mangling} class for the full list.
  17531. Characters that do not have a mnemonic abbreviation are
  17532. mangled as @samp{$} followed by a four-hex-digit unicode value.
  17533. For example @samp{Tamil vowel sign ai} is mangled as @samp{$0bc8}.
  17534. Note that this mapping may map different Scheme names to the
  17535. same Java name. For example @samp{string?}, @samp{String?},
  17536. @samp{is-string}, @samp{is-String},
  17537. and @samp{isString} are all mapped to the same Java identifier
  17538. @samp{isString}. Code that uses such "Java-clashing" names
  17539. is @emph{not} supported. There is very partial support for
  17540. renaming names in the case of a clash, and there may be better
  17541. support in the future. However, some of the nice features of
  17542. Kawa depend on being able to map Scheme name to Java names
  17543. naturally, so we urge you to @emph{not} write code that
  17544. "mixes" naming conventions by using (say) the names @samp{open-file}
  17545. and @samp{openFile} to name two different objects.
  17546. @node Scheme types in Java, Array operations, Mangling, Objects Classes and Modules
  17547. @section Scheme types in Java
  17548. All Scheme values are implemented by sub-classes of @samp{java.lang.Object}.
  17549. Scheme symbols are implemented using @code{java.lang.String}.
  17550. (Don't be confused by the fact the Scheme sybols are represented
  17551. using Java Strings, while Scheme strings are represented by
  17552. @code{gnu.lists.FString}. It is just that the semantics of Java strings
  17553. match Scheme symbols, but do not match mutable Scheme strings.)
  17554. Interned symbols are presented as interned Strings.
  17555. (Note that with JDK 1.1 string literals are automatically interned.)
  17556. Scheme integers are implemented by @code{gnu.math.IntNum}.
  17557. Use the make static function to create a new IntNum from an int or a long.
  17558. Use the intValue or longValue methods to get the int or long value of
  17559. an IntNum.
  17560. A Scheme "flonum" is implemented by @code{gnu.math.DFloNum}.
  17561. A Scheme pair is implemented by @code{gnu.lists.Pair}.
  17562. A Scheme vector is implemented by @code{gnu.lists.FVectror}.
  17563. Scheme characters are implemented using @code{gnu.text.Char}.
  17564. Scheme strings are implemented using @code{gnu.lists.FString}.
  17565. Scheme procedures are all sub-classes of @code{gnu.mapping.Procedure}.
  17566. The "action" of a @samp{Procedure} is invoked by using one of
  17567. the @samp{apply*} methods: @samp{apply0}, @samp{apply1},
  17568. @samp{apply2}, @samp{apply3}, @samp{apply4}, or @samp{applyN}.
  17569. Various sub-class of @samp{Procedure} provide defaults
  17570. for the various @samp{apply*} methods. For example,
  17571. a @samp{Procedure2} is used by 2-argument procedures.
  17572. The @samp{Procedure2} class provides implementations of all
  17573. the @samp{apply*} methods @emph{except} @samp{apply2},
  17574. which must be provided by any class that extends @code{Procedure2}.
  17575. @node Array operations, Loading Java functions into Scheme, Scheme types in Java, Objects Classes and Modules
  17576. @section Using Java Arrays
  17577. @anchor{Creating-new-Java-arrays}
  17578. @subsection Creating new Java arrays
  17579. To allocate a Java array you can use the array type specifier
  17580. as a constructor function. For example, to allocate an array with room for 10 elements
  17581. each of each is a primitive @code{int}:
  17582. @example
  17583. (int[] length: 10)
  17584. @end example
  17585. You can specify the initial elements instead of the length:
  17586. @example
  17587. (object[] 31 32 33 34)
  17588. @end example
  17589. This creates a 4-length array, initialized to the given values.
  17590. Note this is a variation of the generation object-allocation
  17591. (@pxref{Allocating objects}) pattern. You can explicitly
  17592. use the @code{make} function, if you prefer:
  17593. @example
  17594. (make object[] 31 32 33 34)
  17595. @end example
  17596. If you specify a length, you can also specify initial values for selected
  17597. elements.
  17598. If you specify an index, in the form of a literal integer-valued keyword,
  17599. then following elements are placed starting at that position.
  17600. @example
  17601. (int[] length: 100 10 12 80: 15 16 50: 13 14)
  17602. @end example
  17603. This creates an array with 100 elements. Most of them are initialized
  17604. to the default value of zero,
  17605. but elements with indexes 0, 1, 50, 51, 80, 81 are initialized
  17606. to the values 10, 12, 13, 14, 15, 16, respectively.
  17607. @subsection Accessing Java array elements
  17608. You can access the elements of a Java array by treating it as
  17609. a one-argument function, where the argument is the index:
  17610. @example
  17611. (define primes (integer[] 2 3 5 7 11 13))
  17612. (primes 0) @result{} 2
  17613. (primes 5) @result{} 13
  17614. @end example
  17615. You can set an element by treating the array as a function
  17616. with a @code{setter}:
  17617. @example
  17618. (set! (primes 0) -2)
  17619. (set! (primes 3) -7)
  17620. primes @result{} [-2 3 5 -7 11 13]
  17621. @end example
  17622. To get the number of elements of an array, you can treat
  17623. it as having a @code{length} field:
  17624. @example
  17625. primes:length @result{} 6
  17626. @end example
  17627. Here is a longer example. This is the actual definition of the
  17628. standard @code{gcd} function. Note the @code{args} variable
  17629. receives all the arguments on the form of an @code{integer} array.
  17630. (This uses the Java5 varargs feature.)
  17631. @example
  17632. (define (gcd #!rest (args ::integer[])) ::integer
  17633. (let ((n ::int args:length))
  17634. (if (= n 0)
  17635. 0
  17636. (let ((result ::integer (args 0)))
  17637. (do ((i ::int 1 (+ i 1)))
  17638. ((>= i n) result)
  17639. (set! result (gnu.math.IntNum:gcd result (args i))))))))
  17640. @end example
  17641. The above example generates good code,
  17642. thanks to judicious use of casts and type specifications.
  17643. In general, if Kawa knows that
  17644. a ``function'' is an array then it will generate efficient
  17645. bytecode instructions for array operations.
  17646. @subsection Old low-level array macros
  17647. The deprecated @ref{Low-level array macros} are also supported.
  17648. @node Loading Java functions into Scheme, Evaluating Scheme expressions from Java, Array operations, Objects Classes and Modules
  17649. @section Loading Java functions into Scheme
  17650. When @code{kawa -C} compiles (@pxref{Files compilation}) a Scheme module
  17651. it creates a class that implements the @code{java.lang.Runnable} interface.
  17652. (Usually it is a class that extends the @code{gnu.expr.ModuleBody}.)
  17653. It is actually fairly easy to write similar "modules" by hand in Java,
  17654. which is useful when you want to extend Kawa with new "primitive functions"
  17655. written in Java. For each function you need to create an object that
  17656. extends @code{gnu.mapping.Procedure}, and then bind it in the global
  17657. environment. We will look at these two operations.
  17658. There are multiple ways you can create a @code{Procedure} object. Below
  17659. is a simple example, using the @code{Procedure1} class, which is class
  17660. extending @code{Procedure} that can be useful for one-argument
  17661. procedure. You can use other classes to write procedures. For example
  17662. a @code{ProcedureN} takes a variable number of arguments, and you must
  17663. define @code{applyN(Object[] args)} method instead of @code{apply1}.
  17664. (You may notice that some builtin classes extend @code{CpsProcedure}.
  17665. Doing so allows has certain advantages, including support for
  17666. full tail-recursion, but it has some costs, and is a bit trickier.)
  17667. @example
  17668. import gnu.mapping.*;
  17669. import gnu.math.*;
  17670. public class MyFunc extends Procedure1
  17671. @{
  17672. // An "argument" that is part of each procedure instance.
  17673. private Object arg0;
  17674. public MyFunc(String name, Object arg0)
  17675. @{
  17676. super(name);
  17677. this.arg0 = arg0;
  17678. @}
  17679. public Object apply1 (Object arg1)
  17680. @{
  17681. // Here you can so whatever you want. In this example,
  17682. // we return a pair of the argument and arg0.
  17683. return gnu.lists.Pair.make(arg0, arg1);
  17684. @}
  17685. @}
  17686. @end example
  17687. You can create a @code{MyFunc} instance and call it from Java:
  17688. @example
  17689. Procedure myfunc1 = new MyFunc("my-func-1", Boolean.FALSE);
  17690. Object aresult = myfunc1.apply1(some_object);
  17691. @end example
  17692. The name @code{my-func-1} is used when @code{myfunc1} is printed
  17693. or when @code{myfunc1.toString()} is called. However,
  17694. the Scheme variable @code{my-func-1} is still not bound.
  17695. To define the function to Scheme, we can create
  17696. a "module", which is a class intended to be loaded
  17697. into the top-level environment. The provides the definitions to be
  17698. loaded, as well as any actions to be performed on loading
  17699. @example
  17700. public class MyModule
  17701. @{
  17702. // Define a function instance.
  17703. public static final MyFunc myfunc1
  17704. = new MyFunc("my-func-1", IntNum.make(1));
  17705. @}
  17706. @end example
  17707. If you use Scheme you can use @code{require}:
  17708. @example
  17709. #|kawa:1|# (require <MyModule>)
  17710. #|kawa:2|# (my-func-1 0)
  17711. (1 0)
  17712. @end example
  17713. Note that @code{require} magically defines @code{my-func-1} without
  17714. you telling it to. For each public final
  17715. field, the name and value of the field are entered in the
  17716. top-level environment when the class is loaded. (If there are
  17717. non-static fields, or the class implements @code{Runnable}, then
  17718. an instance of the object is created, if one isn't available.)
  17719. If the field value is a @code{Procedure} (or implements @code{Named}),
  17720. then the name bound to the procedure is used instead of the field name.
  17721. That is why the variable that gets bound in the Scheme environment is
  17722. @code{my-func-1}, not @code{myfunc1}.
  17723. Instead of @code{(require <MyModule>)}, you can do @code{(load "MyModule")}
  17724. or @code{(load "MyModule.class")}.
  17725. If you're not using Scheme, you can use Kawa's @code{-f} option:
  17726. @example
  17727. $ kawa -f MyModule --xquery --
  17728. #|kawa:1|# my-func-1(3+4)
  17729. <list>1 7</list>
  17730. @end example
  17731. If you need to do some more complex calculations when a module is loaded,
  17732. you can put them in a @code{run} method, and have the module
  17733. implement @code{Runnable}:
  17734. @example
  17735. public class MyModule implements Runnable
  17736. @{
  17737. public void run ()
  17738. @{
  17739. Interpreter interp = Interpreter.getInterpreter();
  17740. Object arg = Boolean.TRUE;
  17741. interp.defineFunction (new MyFunc ("my-func-t", arg));
  17742. System.err.println("MyModule loaded");
  17743. @}
  17744. @}
  17745. @end example
  17746. Loading @code{MyModule} causes @code{"MyModule loaded"} to be printed,
  17747. and @code{my-func-t} to be defined. Using @code{Interpreter}'s
  17748. @code{defineFunction} method is recommended because it does the righ
  17749. things even for languages like Common Lisp that use separate
  17750. "namespaces" for variables and functions.
  17751. A final trick is that you can have a @code{Procedure} be its own module:
  17752. @example
  17753. import gnu.mapping.*;
  17754. import gnu.math.*;
  17755. public class MyFunc2 extends Procedure2
  17756. @{
  17757. public MyFunc(String name)
  17758. @{
  17759. super(name);
  17760. @}
  17761. public Object apply2 (Object arg1, arg2)
  17762. @{
  17763. return gnu.lists.Pair.make(arg1, arg2);
  17764. @}
  17765. public static final MyFunc myfunc1 = new MyFunc("my-func-2);
  17766. @}
  17767. @end example
  17768. @node Evaluating Scheme expressions from Java, , Loading Java functions into Scheme, Objects Classes and Modules
  17769. @section Evaluating Scheme expressions from Java
  17770. The following methods are recommended if you need to evaluate a
  17771. Scheme expression from a Java method.
  17772. (Some details (such as the @samp{throws} lists) may change.)
  17773. @deftypefn {Static method} void Scheme.registerEnvironment ()
  17774. Initializes the Scheme environment. Maybe needed if you
  17775. try to load a module compiled from a Scheme source file.
  17776. @end deftypefn
  17777. @deftypefn {Static method} Object Scheme.eval (InPort @var{port}, Environment @var{env})
  17778. Read expressions from @var{port}, and evaluate them in the
  17779. @var{env} environment, until end-of-file is reached.
  17780. Return the value of the last expression,
  17781. or @code{Interpreter.voidObject} if there is no expression.
  17782. @end deftypefn
  17783. @deftypefn {Static method} Object Scheme.eval (String @var{string}, Environment @var{env})
  17784. Read expressions from @var{string}, and evaluate them in the
  17785. @var{env} environment, until the end of the string is reached.
  17786. Return the value of the last expression,
  17787. or @code{Interpreter.voidObject} if there is no expression.
  17788. @end deftypefn
  17789. @deftypefn {Static method} Object Scheme.eval (Object @var{sexpr}, Environment @var{env})
  17790. The @var{sexpr} is an S-expression (as may be returned by @code{read}).
  17791. Evaluate it in the @var{env} environment, and return the result.
  17792. @end deftypefn
  17793. For the @code{Environment} in most cases you could use
  17794. @samp{Environment.current()}. Before you start, you
  17795. need to initialize the global environment,
  17796. which you can do with
  17797. @example
  17798. Environment.setCurrent(new Scheme().getEnvironment());
  17799. @end example
  17800. Alternatively, rather than setting the global environment,
  17801. you can use this style:
  17802. @example
  17803. Scheme scm = new Scheme();
  17804. Object x = scm.eval("(+ 3 2)");
  17805. System.out.println(x);
  17806. @end example
  17807. @subsection Using @code{javax.script} portable Java scripting
  17808. Kawa also supports the standard
  17809. @uref{http://docs.oracle.com/javase/8/docs/api/javax/script/package-summary.html,@code{javax.script}} API.
  17810. The main advantage of this API is if you want your users to be able to choose
  17811. between multiple scripting languages. That way you can support Kawa
  17812. without Kawa-specific programming.
  17813. For example the standard JDK tool @uref{http://docs.oracle.com/javase/8/docs/technotes/tools/unix/jrunscript.html,jrunscript} provides a
  17814. read-eval-print-loop for any language that implements the @code{javax.script}
  17815. API. It knows nothing about Kawa but can still use it:
  17816. @example
  17817. $ jrunscript -cp kawa.jar -l scheme
  17818. scheme> (cadr '(3 4 5))
  17819. 4
  17820. @end example
  17821. (Of course the @code{jrunscript} REPL isn't as nice as the one that
  17822. Kawa provides. For example the latter can handle multi-line inputs.)
  17823. @node XML tools
  17824. @chapter Working with XML and HTML
  17825. Kawa has a number of features for working with XML, HTML,
  17826. and generated web pages.
  17827. In Kawa you don't write XML or HTML directly.
  17828. Instead you write expressions that evaluate to ``node objects''
  17829. corresponding to elements, attributes, and text.
  17830. You then write these node objects using either an XML or HTML format.
  17831. Many web-page-generating tools require you to work directly
  17832. with raw HTML, as for example:
  17833. @example
  17834. (display "<p>Don't use the <code>&lt;blink&gt;</code> tag.</p>")
  17835. @end example
  17836. In Kawa you would instead do:
  17837. @example
  17838. (display (html:p "Don't use the " (html:code "<blink>") " tag."))
  17839. @end example
  17840. The conversion from node objects to XML or HTML is handled by
  17841. the formatter (or serializer).
  17842. Some advantages of doing it this way are:
  17843. @itemize
  17844. @item
  17845. You don't have to worry about quoting special characters.
  17846. Missing or incorrect quoting is a common source of bugs
  17847. and security problems on systems that work directly with text, such as PHP.
  17848. @item
  17849. Some errors, such as mismatched element tags, are automatically avoided.
  17850. @item
  17851. The generated XML can be validated as it is generated,
  17852. or even using compile-time type-checking. (Kawa doesn't yet do either.)
  17853. @item
  17854. In an application that also reads XML,
  17855. you can treat XML that is read in and XML that is generated using
  17856. the same functions.
  17857. @end itemize
  17858. @menu
  17859. * Formatting XML::
  17860. * Creating HTML nodes::
  17861. * Creating XML nodes::
  17862. * XML literals::
  17863. * Server-side scripts:: Writing web-server-side Kawa scripts
  17864. * Self-configuring page scripts::
  17865. * Servlets:: Installing Kawa programs as Servlets
  17866. * CGI scripts:: Installing Kawa programs as CGI scripts
  17867. * HTTP requests:: Functions for accessing HTTP requests
  17868. * HTTP response:: Functions for generating HTTP response
  17869. * XML beyond Scheme:: Using non-Scheme languages for XML/HTML
  17870. @end menu
  17871. @node Formatting XML, Creating HTML nodes, , XML tools
  17872. @section Formatting XML
  17873. The easiest way to generate HTML or XML output is to run Kawa
  17874. with the appropriate @ref{Named output formats, , @code{--output-format} option}.
  17875. The intentation is that these output modes should be compatible with
  17876. @uref{http://www.w3.org/TR/2006/PR-xslt-xquery-serialization-20061121/,
  17877. XSLT 2.0 and XQuery 1.0 Serialization}.
  17878. (However, that specifies many options, most
  17879. of which have not yet been implemented.
  17880. @table @code
  17881. @item xml
  17882. Values are printed in XML format.
  17883. "Groups" or "elements" are written as using xml element syntax.
  17884. Plain characters (such as @samp{<}) are escaped (such as @samp{&lt;}).
  17885. @item xhtml
  17886. Same as @code{xml}, but follows the xhtml compatibility guidelines.
  17887. @item html
  17888. Values are printed in HTML format.
  17889. Mostly same as @code{xml} format, but certain elements without body,
  17890. are written without a closing tag. For example @code{<img>} is written
  17891. without @code{</img>}, which would be illegal for html, but required for xml.
  17892. Plain characters (such as @samp{<}) are not escaped inside @code{<script>}
  17893. or @code{<style>} elements.
  17894. @end table
  17895. To illustrate:
  17896. @example
  17897. $ kawa --output-format html
  17898. #|kawa:1|# (html:img src:"img.jpg")
  17899. <img src="img.jpg">
  17900. @end example
  17901. @example
  17902. $ kawa --output-format xhtml
  17903. #|kawa:1|# (html:img src:"img.jpg")
  17904. <img xmlns="http://www.w3.org/1999/xhtml" src="img.jpg" />
  17905. @end example
  17906. @example
  17907. $ kawa --output-format xml
  17908. #|kawa:1|# (html:img src:"img.jpg")
  17909. <img xmlns="http://www.w3.org/1999/xhtml" src="img.jpg"></img>
  17910. @end example
  17911. And here is the default @code{scheme} formatting:
  17912. @example
  17913. $ kawa
  17914. #|kawa:1|# (html:img src:"img.jpg")
  17915. (@{http://www.w3.org/1999/xhtml@}img src: img.jpg )
  17916. @end example
  17917. @deffn Procedure as-xml value
  17918. Return a value (or multiple values) that when printed will
  17919. print @var{value} in XML syntax.
  17920. @example
  17921. (require 'xml)
  17922. (as-xml (make-element 'p "Some " (make-element 'em "text") "."))
  17923. @end example
  17924. prints @code{<p>Some <em>text</em>.</p>}.
  17925. @end deffn
  17926. @deffn Procedure unescaped-data data
  17927. Creates a special value which causes @code{data} to be printed,
  17928. as is, without normal escaping. For example, when the output format
  17929. is XML, then printing @code{"<?xml?>"} prints as @samp{&lt;?xml?&gt;},
  17930. but @code{(unescaped-data "<?xml?>")} prints as @samp{<?xml?>}.
  17931. @end deffn
  17932. @node Creating HTML nodes, Creating XML nodes, Formatting XML, XML tools
  17933. @section Creating HTML nodes
  17934. The @code{html} prefix names a special namespace
  17935. (@pxref{Namespaces}) of functions to create HTML element nodes.
  17936. For example, @code{html:em} is a constructor that
  17937. when called creates a element node whose tag is @code{em}.
  17938. If this element node is formatted as HTML, the
  17939. result has an @code{<em>} tag.
  17940. @deffn Syntax html:@var{tag} attributes ... content ...
  17941. Creates an element node whose tag is @var{tag}.
  17942. The parameters are first zero or more attributes, followed
  17943. by zero of more child values.
  17944. An attribute is either an attribute value (possibly
  17945. created using @code{make-attribute}), or a pair of arguments:
  17946. A keyword followed by the attribute value.
  17947. Child values are usually either strings (text content),
  17948. or nested element nodes, but can also be comment or processing-instruction
  17949. nodes.
  17950. @example
  17951. (html:a href: "http://gnu.org/" "the "(html:i "GNU")" homepage")
  17952. @end example
  17953. @end deffn
  17954. The compound identifier @code{html:@var{tag}} is actually
  17955. a type: When you call it as a function you're using Kawa's
  17956. standard coercion of a type to its constructor function.
  17957. This means you can do type tests:
  17958. @example
  17959. (define some-node ...)
  17960. (if (instance? some-node html:blink)
  17961. (error "blinking not allowed!"))
  17962. @end example
  17963. Object identity is currently not fully specified. Specifically,
  17964. it is undefined if a nested (child) element node is copied
  17965. ``by value'' or ``by reference''. This is related to whether
  17966. nodes have a parent reference. In the XPath/XQuery data model
  17967. nodes do have a parent reference, and child nodes are conceptually
  17968. copied. (In the actual implemention copying is commonly avoided.)
  17969. Kawa/Scheme currently followed the XQuery copying semantics,
  17970. which may not be the most appropriate for Scheme.
  17971. @node Creating XML nodes, XML literals, Creating HTML nodes, XML tools
  17972. @section Creating XML nodes
  17973. The XML data model is similar to HTML, with one important addition:
  17974. XML tags may be @dfn{qualified names}, which are similar
  17975. to @ref{Namespaces, , compound symbols}.
  17976. You must do this to use the following types and functions:
  17977. @example
  17978. (require 'xml)
  17979. @end example
  17980. The following types and functions assume:
  17981. @example
  17982. (require 'xml)
  17983. @end example
  17984. @deffn Procedure make-element tag [attribute ...] child ...
  17985. Create a representation of a XML element, corresponding to
  17986. @example
  17987. <@var{tag} @var{attribute}...>@var{child}...</@var{tag}>
  17988. @end example
  17989. The result is a @code{TreeList}, though if the result context is a consumer
  17990. the result is instead "written" to the consumer.
  17991. Thus nested calls to @code{make-element} only result in a
  17992. single @code{TreeList}.
  17993. More generally, whether an @var{attribute} or @var{child} is includded
  17994. by copying or by reference is (for now) undefined.
  17995. The @var{tag} should currently be a symbol, though in the future it should
  17996. be a qualified name.
  17997. An @var{attribute} is typically a call to @code{make-attribute},
  17998. but it can be any attribute-valued expression.
  17999. @example
  18000. (make-element 'p
  18001. "The time is now: "
  18002. (make-element 'code (make <java.util.Date>)))
  18003. @end example
  18004. @end deffn
  18005. @deffn Procedure element-name element
  18006. Returns the name (tag) of the element node, as a symbol (QName).
  18007. @end deffn
  18008. @deffn Procedure make-attribute name value...
  18009. Create an "attribute", which is a name-value pair.
  18010. For now, @var{name} should be a symbol.
  18011. @end deffn
  18012. @deffn Procedure attribute-name element
  18013. Returns the name of the attribute node, as a symbol (QName).
  18014. @end deffn
  18015. @deffn Type comment
  18016. Instances of this type represent comment values,
  18017. specifically including comments in XML files.
  18018. Comment nodes are currently ignored when printing using Scheme formatting,
  18019. though that may change.
  18020. @end deffn
  18021. @deffn Constructor comment comment-text
  18022. Create a comment object with the specified @var{comment-text}.
  18023. @end deffn
  18024. @deffn Type processing-instruction
  18025. Instances of this type represent ``processing instructions'',
  18026. such as may appear in XML files.
  18027. Processing-instruction nodes are currently ignored when printing using
  18028. Scheme formatting, though that may change.
  18029. @end deffn
  18030. @deffn Constructor processing-instruction target contents
  18031. Crreate a processing-instruction object with the specified @var{target}
  18032. (a simple symbol) and @var{contents} (a string).
  18033. @end deffn
  18034. @node XML literals, Server-side scripts, Creating XML nodes, XML tools
  18035. @section XML literals
  18036. You can write XML literals directly in Scheme code,
  18037. following a @code{#}.
  18038. Notice that the outermost element needs to be prefixed
  18039. by @code{#}, but nested elements do not (and must not).
  18040. @example
  18041. #<p>The result is <b>final</b>!</p>
  18042. @end example
  18043. Actually, these are not really literals since they can contain
  18044. enclosed expressions:
  18045. @example
  18046. #<em>The result is &@{result@}.</em>
  18047. @end example
  18048. The value of @var{result} is substituted into the output,
  18049. in a similar way to quasi-quotation.
  18050. (If you try to quote one of these ``XML literals'',
  18051. what you get is unspecified and is subject to change.)
  18052. An @var{xml-literal} is usually an element constructor,
  18053. but there some rarely used forms (processing-instructions,
  18054. comments, and CDATA section) we'll cover later.
  18055. @display
  18056. @stxdef{xml-literal} @stxlit{#}@stxref{xml-constructor}
  18057. @stxdef{xml-constructor} @stxref{xml-element-constructor}
  18058. | @stxref{xml-PI-constructor}
  18059. | @stxref{xml-comment-constructor}
  18060. | @stxref{xml-CDATA-constructor}
  18061. @end display
  18062. @subsection Element constructors
  18063. @display
  18064. @stxdef{xml-element-constructor}
  18065. @stxlit{<}@stxref{QName} @stxref{xml-attribute}*@stxlit{>}@stxref{xml-element-datum}...@stxlit{</}@stxref{QName} @stxlit{>}
  18066. | @stxlit{<}@stxref{xml-name-form} @stxref{xml-attribute}*@stxlit{>}@stxref{xml-element-datum}...@stxlit{</>}
  18067. | @stxlit{<}@var{xml-name-form} @stxref{xml-attribute}*@stxlit{/>}
  18068. @stxdef{xml-name-form} @stxref{QName}
  18069. | @stxref{xml-enclosed-expression}
  18070. @stxdef{xml-enclosed-expression}
  18071. @stxlit{@lbracechar{}}@stxref{expression}@stxlit{@rbracechar{}}
  18072. | @stxlit{(}@stxref{expression}...@stxlit{)}
  18073. @end display
  18074. The first @var{xml-element-constructor} variant uses a literal @var{QName},
  18075. and looks like standard non-empty XML element, where the starting @var{QName}
  18076. and the ending @var{QName} must match exactly:
  18077. @example
  18078. #<a href="next.html">Next</a>
  18079. @end example
  18080. As a convenience, you can leave out the ending tag(s):
  18081. @example
  18082. This is a paragraph in <emphasis>DocBook</> syntax.</>
  18083. @end example
  18084. You can use an expression to compute the element tag at runtime -
  18085. in that case you @emph{must} leave out the ending tag:
  18086. @example
  18087. #<p>This is <(if be-bold 'strong 'em)>important</>!</p>
  18088. @end example
  18089. You can use arbitrary @var{expression} inside curly braces,
  18090. as long as it evaluates to a symbol.
  18091. You can leave out the curly braces
  18092. if the @var{expression} is a simple parenthesised compound expression.
  18093. The previous example is equivalent to:
  18094. @example
  18095. #<p>This is <@{(if be-bold 'strong 'em)@}>important</>!</p>
  18096. @end example
  18097. The third @var{xml-element-constructor} variant above is an XML
  18098. ``empty element''; it is equivalent to the second variant
  18099. when there are no @var{xml-element-datum} items.
  18100. (Note that every well-formed XML element, as defined in the XML specifications,
  18101. is a valid @var{xml-element-constructor}, but not vice versa.)
  18102. @subsection Elements contents (children)
  18103. The ``contents'' (children) of an element
  18104. are a sequence of character (text) data, and nested nodes.
  18105. The characters @code{&}, @code{<}, and @code{>} are special,
  18106. and need to be escaped.
  18107. @display
  18108. @stxdef{xml-element-datum}
  18109. any character except @code{&}, or @code{<}.
  18110. | @stxref{xml-constructor}
  18111. | @stxref{xml-escaped}
  18112. @stxdef{xml-escaped}
  18113. @stxlit{&}@stxref{xml-enclosed-expression}
  18114. | @stxlit{&}@stxref{xml-entity-name}@stxlit{;}
  18115. | @stxref{xml-character-reference}
  18116. @stxdef{xml-character-reference}
  18117. @stxlit{&#}@stxref{digit}+@stxlit{;}
  18118. | @stxlit{&#x}@stxref{hex-digit}+@stxlit{;}
  18119. @end display
  18120. Here is an example shows both hex and decimal character references:
  18121. @example
  18122. #<p>A&#66;C&#x44;E</p> @result{} <p>ABCDE</p>
  18123. @end example
  18124. @display
  18125. @stxdef{xml-entity-name} @stxref{identifier}
  18126. @end display
  18127. Currently, the only supported values for @var{xml-entity-name}
  18128. are the builtin XML names @code{lt}, @code{gt}, @code{amp},
  18129. @code{quot}, and @code{apos}, which stand for the characters
  18130. @code{<}, @code{>}, @code{&}, @code{"}, and @code{'}, respectively.
  18131. The following two expressions are equivalent:
  18132. @example
  18133. #<p>&lt; &gt; &amp; &quot; &apos;</p>
  18134. #<p>&@{"< > & \" '"@}</p>
  18135. @end example
  18136. @subsection Attributes
  18137. @display
  18138. @stxdef{xml-attribute}
  18139. @stxref{xml-name-form}@stxlit{=}@stxref{xml-attribute-value}
  18140. @stxdef{xml-attribute-value}
  18141. @stxlit{"}@stxref{quot-attribute-datum}*@stxlit{"}
  18142. | @stxlit{'}@stxref{apos-attribute-datum}*@stxlit{'}
  18143. @stxdef{quot-attribute-datum}
  18144. any character except @code{"}, @code{&}, or @code{<}.
  18145. | @stxref{xml-escaped}
  18146. @stxdef{apos-attribute-datum}
  18147. any character except @code{'}, @code{&}, or @code{<}.
  18148. | @stxref{xml-escaped}
  18149. @end display
  18150. If the @var{xml-name-form} is either @code{xmlns} or
  18151. a compound named with the prefix @code{xmlns}, then
  18152. technically we have a namespace declaration, rather than
  18153. an attribute.
  18154. @subsection QNames and namespaces
  18155. The names of elements and attributes are @dfn{qualified names}
  18156. (QNames), which are represented using compound symbols (@pxref{Namespaces}).
  18157. The lexical syntax for a QName is either a simple identifier,
  18158. or a (prefix,local-name) pair:
  18159. @display
  18160. @stxdef{QName} @stxref{xml-local-part}
  18161. | @stxref{xml-prefix}@stxlit{:}@stxref{xml-local-part}
  18162. @stxdef{xml-local-part} @stxref{identifier}
  18163. @stxdef{xml-prefix} @stxref{identifier}
  18164. @end display
  18165. An @var{xml-prefix} is an alias for a namespace-uri,
  18166. and the mapping between them is defined by a namespace-declaration.
  18167. You can either use a @code{define-namespace} form, or you
  18168. can use a @dfn{namespace declaration attribute}:
  18169. @display
  18170. @stxdef{xml-namespace-declaration-attribute}
  18171. @stxlit{xmlns:}@stxref{xml-prefix}@stxlit{=}@stxref{xml-attribute-value}
  18172. | @stxlit{xmlns=}@stxref{xml-attribute-value}
  18173. @end display
  18174. The former declares @var{xml-prefix} as a namespace alias for
  18175. the namespace-uri specified by @var{xml-attribute-value}
  18176. (which must be a compile-time constant).
  18177. The second declares that @var{xml-attribute-value} is the default
  18178. namespace for simple (unprefixed) element tags.
  18179. (A default namespace declaration is ignored for attribute names.)
  18180. @example
  18181. (let ((qn (element-name #<gnu:b xmlns:gnu="http://gnu.org/"/>)))
  18182. (list (symbol-local-name qn)
  18183. (symbol-prefix qn)
  18184. (symbol-namespace-uri qn)))
  18185. @result{} ("b" "gnu" "http://gnu.org/")
  18186. @end example
  18187. @subsection Other XML types
  18188. @subsubsection Processing instructions
  18189. An @var{xml-PI-constructor} can be used to create an XML
  18190. @dfn{processing instruction}, which can be used to pass
  18191. instructions or annotations to an XML processor (or tool).
  18192. (Alternatively, you can use the @code{processing-instruction}
  18193. type constructor.)
  18194. @display
  18195. @stxdef{xml-PI-constructor} @stxlit{<?}@stxref{xml-PI-target} @stxref{xml-PI-content}@stxlit{?>}
  18196. @stxdef{xml-PI-target} @var{NCname} (i.e. a simple (non-compound) identifier)
  18197. @stxdef{xml-PI-content} any characters, not containing @code{?>}.
  18198. @end display
  18199. For example, the DocBook XSLT stylesheets can use the @code{dbhtml}
  18200. instructions to specify that a specific chapter should be
  18201. written to a named HTML file:
  18202. @example
  18203. #<chapter><?dbhtml filename="intro.html" ?>
  18204. <title>Introduction</title>
  18205. ...
  18206. </chapter>
  18207. @end example
  18208. @subsubsection XML comments
  18209. You can cause XML comments to be emitted in the XML output document.
  18210. Such comments can be useful for humans reading the XML document,
  18211. but are usually ignored by programs.
  18212. (Alternatively, you can use the @code{comment} type constructor.)
  18213. @display
  18214. @stxdef{xml-comment-constructor} @stxlit{<!--}@stxref{xml-comment-content}@stxlit{-->}
  18215. @stxdef{xml-comment-content} any characters, not containing @code{--}.
  18216. @end display
  18217. @subsubsection CDATA sections
  18218. A @code{CDATA} section can be used to avoid excessive use of
  18219. @var{xml-entity-ref} such as @code{&amp;} in element content.
  18220. @display
  18221. @stxdef{xml-CDATA-constructor} @stxlit{<![CDATA[}@stxref{xml-CDATA-content}@stxlit{]]>}
  18222. @stxdef{xml-CDATA-content} any characters, not containing @code{]]>}.
  18223. @end display
  18224. The following are equivalent:
  18225. @example
  18226. #<p>Specal characters <![CDATA[< > & ' "]]> here.</p>
  18227. #<p>Specal characters &lt; &gt; &amp; &quot; &apos; here.</p>
  18228. @end example
  18229. Kawa remembers that you used a @code{CDATA} section in
  18230. the @var{xml-element-constructor} and will write it out
  18231. using a @code{CDATA} constructor.
  18232. @node Server-side scripts, Self-configuring page scripts, XML literals, XML tools
  18233. @section Web page scripts
  18234. A Kawa @dfn{web page script} is a Kawa program that is invoked
  18235. by a web server because the server received an HTTP request.
  18236. The result of evaluating the top-level expressions becomes
  18237. the HTTP response that the servlet sends back to the client, usually a browser.
  18238. A web page script may be as simple as:
  18239. @example
  18240. (format "The time is <~s>." (java.util.Date))
  18241. @end example
  18242. This returns a response of consisting of a formatted string
  18243. giving the current time.
  18244. The string would interpreted as @code{text/plain} content:
  18245. The angle brackets are regular characters, and not
  18246. HTML tag markers.
  18247. The script can alternatively evaluate to XML/HTML node
  18248. values, for example those created by @ref{XML literals}:
  18249. @example
  18250. #<p>Hello, <b>&(request-remote-host)</b>!</p>
  18251. @end example
  18252. In this case the response would be @code{text/html} or similar content:
  18253. The angle brackets should be interpreted by the browser as HTML tag markers.
  18254. The function @code{request-remote-host} is available (automatically)
  18255. to web page scripts; it returns the host that made the HTTP request,
  18256. which is then interpolated into the response.
  18257. Following sections will go into more details about how
  18258. to write web page scripts. You can do so in any supported
  18259. Kawa language, including Scheme, BRL, KRL, or XQuery.
  18260. A web server will use a URL mapping to map a request URL
  18261. to a specific web page script. This can be done in a
  18262. number of different ways:
  18263. @itemize
  18264. @item
  18265. The easiest to manage is to use Kawa's mechanism for
  18266. @ref{Self-configuring page scripts}. Ths is especially
  18267. easy if you the web server built in to JDK 6, since no
  18268. configuration files are needed.
  18269. You can also use a ``servlet engine'' like Tomcat or Glassfish.
  18270. @item
  18271. You can explicitly compile the web page script to a servlet,
  18272. in the same way Java servlets are compiled.
  18273. This can then be installed ("deployed") in a servlet-supporting
  18274. web server, such a Tomcat or Glassfish. @xref{Servlets}.
  18275. @item
  18276. You can run the servlet as a @ref{CGI scripts,CGI script}.
  18277. @end itemize
  18278. For details on how to extract information from the request
  18279. see @ref{HTTP requests}.
  18280. For details on how the response is created see @ref{HTTP response,Generating HTTP responses}.
  18281. If the response is HTML or XML, you may want to
  18282. read @ref{Creating HTML nodes}, or @ref{Creating XML nodes},
  18283. or @ref{XML literals}.
  18284. Here are some examples, starting with a simple @code{hello.scm}:
  18285. @example
  18286. (response-content-type 'text/html) ; Optional
  18287. (html:p
  18288. "The request URL was: " (request-url))
  18289. (make-element 'p
  18290. (let ((query (request-query-string)))
  18291. (if query
  18292. (values-append "The query string was: " query)
  18293. "There was no query string.")))
  18294. @end example
  18295. This returns two @code{<p>} (paragraph) elements: One using
  18296. @code{make-element} and one using the @code{html:p} constructor.
  18297. Or you may prefer to use @ref{XML literals}.
  18298. The same program using KRL:
  18299. @example
  18300. <p>The request URL was: [(request-url)]</p>,
  18301. <p>[(let ((query (request-query-string)))
  18302. (if query
  18303. (begin ]The query string was: [query)
  18304. ]There was no query string.[))]</p>
  18305. @end example
  18306. You can also use XQuery:
  18307. @example
  18308. <p>The request URL was: @{request-url()@}</p>
  18309. <p>@{let $query := request-query-string() return
  18310. if ($query)
  18311. then ("The query string was: ",$query)
  18312. else "There was no query string."@}</p>
  18313. @end example
  18314. The @code{+default+} script in the @code{doc} directory is
  18315. useful for reading the Kawa documentation using a browser.
  18316. The script uses the @code{jar:} URL scheme to automatically extract
  18317. and uncompress the pages from @code{doc/kawa-manual.epub},
  18318. which is in EPUB3 format. Read the script for usage instructions.
  18319. @node Self-configuring page scripts, Servlets, Server-side scripts, XML tools
  18320. @section Self-configuring web page scripts
  18321. Kawa makes it easy to set up a web site without configuration
  18322. files. Instead, the mapping from request URL to web page script
  18323. matches the layout of files in the application directory.
  18324. Many web servers make it easy to execute a script using a script
  18325. processor which is selected depending on the extension of the
  18326. requested URL. That is why you see lots of URLs that end in
  18327. @code{.cgi}, @code{.php}, or @code{.jsp}. This is bad, because it
  18328. exposes the server-side implementation to the user: Not only are such
  18329. URLs ugly, but they make it difficult to change the server without
  18330. breaking people's bookmarks and search engines. A server will usually
  18331. provide a mechanism to use prettier URLs, but doing so requires extra
  18332. effort, so many web-masters don't.
  18333. If you want a script to be executed in response to a URL
  18334. @code{http://host/app/foo/bar} you give the script the name
  18335. @code{app/foo/bar}, in the appropriate server ``application''
  18336. directory (as explained below). You get to pick the name @code{bar}.
  18337. Or you can use the name @code{bar.html}, even though the file named
  18338. @code{bar.html} isn't actually
  18339. an html file - rather it produces html when evaluated. Or better: just use
  18340. a name without an extension at all.
  18341. Kawa figures
  18342. out what kind of script it is based on the content of the file,
  18343. rather than the file name. Once Kawa has
  18344. found a script, it looks at the first line to see if it can recognize
  18345. the kind (language) of the script. Normally this would be a comment
  18346. that contains the name of a programming language that Kawa
  18347. knows about. For example:
  18348. @example
  18349. ;; Hello world page script written in -*- scheme -*-
  18350. #<p>Hello, <b>&(request-remote-host)</b>!</p>
  18351. @end example
  18352. (Using the funny-looking string @code{-*- scheme -*-} has the
  18353. bonus is that it recognized by the Emacs text editor.)
  18354. A script named @code{+default+} is run if there isn't a matching script.
  18355. For example assume the following is a file named @code{+default}.
  18356. @example
  18357. ;; This is -*- scheme -*-
  18358. (make-element 'p "servlet-path: " (request-servlet-path))
  18359. @end example
  18360. This becomes the default script for HTTP requests that aren't handled
  18361. by a more specific script.
  18362. The @code{request-servlet-path} function
  18363. returns the "servlet path", which is the part of the requested URL
  18364. that is relative to the current web application. Thus a request for
  18365. @code{http://host:port/app/this/is/a/test} will return:
  18366. @example
  18367. servlet-path: /this/is/a/test
  18368. @end example
  18369. You can use the feature variable @code{in-http-server}
  18370. in a @code{cond-expand} to test if the code is executing
  18371. in a web server.
  18372. @subsection Using the OpenJDK built-in web server
  18373. The easiest way to run a Kawa web server is to
  18374. use the web server built in to JDK 6 or later.
  18375. @example
  18376. kawa --http-auto-handler @var{context-path} @var{appdir} --http-start @var{port}
  18377. @end example
  18378. This starts a web server that listens on the given @var{port},
  18379. using the files in directory @var{appdir} to handle
  18380. requests that start with the given @var{context-path}.
  18381. The @var{context-path} must start with a @code{"/"} (one is added if
  18382. needed), and it is recommended that it also end with a @code{"/"}
  18383. (otherwise you might get some surprising behavior).
  18384. You can specify multiple @code{--http-auto-handler} options.
  18385. For example use the files in the current directory to handle
  18386. all requests on the standard port 80 do:
  18387. @example
  18388. kawa --http-auto-handler / . --http-start 80
  18389. @end example
  18390. There are some examples in the @code{testsuite/webtest} directory
  18391. the Kawa source distribution. You can start the server thus:
  18392. @example
  18393. bin/kawa --http-auto-handler / testsuite/webtest/ --http-start 8888
  18394. @end example
  18395. and then for example browse to @code{http://localhost:8888/adder.scm}.
  18396. For lots of information about the HTTP request, browse to
  18397. @code{http://localhost:8888/info/@var{anything}}.
  18398. @subsection Using a servlet container
  18399. You can also can use a ``servlet container''
  18400. such as Tomcat or Glassfish with self-configuring script.
  18401. See @ref{Servlets} for information on how to install
  18402. these servers, and the concept of web applications.
  18403. Once you have these server installed, you create a
  18404. web application with the following in the
  18405. @code{@var{appdir}/WEB-INF/web.xml} configuration file:
  18406. @example
  18407. <web-app>
  18408. <display-name>Kawa auto-servlet</display-name>
  18409. <servlet>
  18410. <servlet-name>KawaPageServlet</servlet-name>
  18411. <servlet-class>gnu.kawa.servlet.KawaPageServlet</servlet-class>
  18412. </servlet>
  18413. <servlet-mapping>
  18414. <servlet-name>KawaPageServlet</servlet-name>
  18415. <url-pattern>/*</url-pattern>
  18416. </servlet-mapping>
  18417. </web-app>
  18418. @end example
  18419. This creates a web application where all URLs
  18420. are handled by the @code{gnu.kawa.servlet.KawaPageServlet} servlet class,
  18421. which is included in the Kawa jar file.
  18422. The @code{KawaPageServlet} class handles the searching
  18423. and compiling described in this page.
  18424. @subsection Finding a matching script
  18425. When Kawa receives a request for:
  18426. @example
  18427. http://host:port/appname/a/b/anything
  18428. @end example
  18429. it will look for a file:
  18430. @example
  18431. @var{appdir}/a/b/anything
  18432. @end example
  18433. If such a file exists, the script will be executed, as described
  18434. below. If not, it will look for a file name @code{+default+} in the same
  18435. directory. If that desn't exist either, it will look for @code{+default+}
  18436. in the parent
  18437. directory, then the grand-parent directory, and so on until it gets to
  18438. the appname web application root directory. So the default script is
  18439. this: @code{@var{appdir}/+default}.
  18440. If that doesn't exist then Kawa returns a 404 "page not found" error.
  18441. @subsection Determining script language
  18442. Once Kawa has found a script file corresponding to a request URL,
  18443. it needs to determine if this is a data file or a web page script,
  18444. and in the latter case, what language it is written in.
  18445. Kawa recognizes the following "magic strings" in the first line of a script:
  18446. @table @code
  18447. @item kawa:scheme
  18448. The Scheme language.
  18449. @item kawa:xquery
  18450. The XQuery language.
  18451. @item kawa:@var{language}
  18452. Some other language known to Kawa.
  18453. @end table
  18454. Kawa also recognizes Emacs-style "mode specifiers":
  18455. @table @code
  18456. @item -*- scheme -*-
  18457. The Scheme language.
  18458. @item -*- xquery -*-
  18459. The XQuery language (though Emacs doesn't know about XQuery).
  18460. @item -*- emacs-lisp -*-
  18461. @itemx -*- elisp -*-
  18462. The Emacs Lisp extension language.
  18463. @item -*- common-lisp -*-
  18464. @itemx -*- lisp -*-
  18465. The Common Lisp language.
  18466. @end table
  18467. Also, it also recognizes comments in the first two columns of the line:
  18468. @table @code
  18469. @item ;;
  18470. A Scheme or Lisp comment - assumed to be in the Scheme language.
  18471. @item (:
  18472. Start of an XQuery comment, so assumed to be in the XQuery language.
  18473. @end table
  18474. If Kawa doesn't recognize the language of a script (and it
  18475. isn't named +default+) then it assumes the file is a data file. It
  18476. asks the servlet engine to figure out the content type (using the
  18477. getMimeType method of ServletContext), and just copies the file into
  18478. the response.
  18479. @subsection Compilation and caching
  18480. Kawa automatically compiles a script into a class. The
  18481. class is internal to the server, and is not written out to
  18482. disk. (There is an unsupported option to write the compiled file to a
  18483. class file, but there is no support to use previously-compiled
  18484. classes.) The server then creates a module instance to handle the
  18485. actual request, and runs the body (the @code{run} method)
  18486. of the script class. On subsequence
  18487. requests for the same script, the same class and instance are reused;
  18488. only the @code{run} is re-executed.
  18489. If the script is changed, then it is re-compiled and a new module
  18490. instance created. This makes it very easy to develop and modify a
  18491. script. (Kawa for performance reasons doesn't check more
  18492. than once a second whether a script has been modified.)
  18493. @node Servlets, CGI scripts, Self-configuring page scripts, XML tools
  18494. @section Installing web page scripts as Servlets
  18495. You can compile a Kawa program to a @uref{http://en.wikipedia.org/wiki/Java_Servlet,Servlet}, and run it
  18496. in a servlet engine (a Servlet-aware web server).
  18497. One or more servlets are installed together as a web application.
  18498. This section includes specific information for
  18499. the Tomcat and Glassfish web servers.
  18500. @subsection Creating a web application
  18501. A @dfn{web application} is a group of data, servlets, and
  18502. configuration files to handle a related set of URLs.
  18503. The @uref{http://jcp.org/aboutJava/communityprocess/final/jsr315/index.html,
  18504. servlet specification}
  18505. specifies the directory structure of a web application.
  18506. Assume the web application is called @code{myapp}, and lives in a
  18507. directory with the same name. The application normally handles
  18508. requests for URLs that start with @code{http://example.com/myapp}.
  18509. Most files in the application directory are used to handle
  18510. requests with corresponding URL. For example,
  18511. a file @code{myapp/list/help.html} would be the response
  18512. to the request @code{http://example.com/myapp/list/help.html}.
  18513. The directory @code{WEB-INF} is special. It contains configuration
  18514. files, library code, and other server data.
  18515. So to create the @code{myapp} application, start with:
  18516. @example
  18517. mkdir myapp
  18518. cd myapp
  18519. mkdir WEB-INF WEB-INF/lib WEB-INF/classes
  18520. @end example
  18521. Copy the Kawa jar from the @code{lib} direcory.
  18522. (You can also use a ``hard'' link, but symbolic links may not
  18523. work, for security systems.)
  18524. @example
  18525. cp @var{kawa-home}/kawa-@value{VERSION}.jar WEB-INF/lib/kawa.jar
  18526. @end example
  18527. If you build Kawa from source, you must specify the
  18528. @code{--with-servlet} @ref{configure options,configure option}.
  18529. You should also create the file @code{WEB-INF/web.xml}.
  18530. For now, this is is just a place-holder:
  18531. @example
  18532. <web-app>
  18533. <display-name>My Application</display-name>
  18534. </web-app>
  18535. @end example
  18536. @subsection Compiling a web page script to a servlet
  18537. Assume for simplicity that the source files
  18538. are in the @code{WEB-INF/classes} directory, and make that the
  18539. current directory:
  18540. @example
  18541. cd .../myapp/WEB-INF/classes
  18542. @end example
  18543. Depending on the source language, you compile your script
  18544. sing the @code{--servlet} switch:
  18545. @example
  18546. kawa --servlet -C hello.scm
  18547. @end example
  18548. or:
  18549. @example
  18550. kawa --servlet --krl -C hello.krl
  18551. @end example
  18552. or:
  18553. @example
  18554. kawa --servlet --xquery -C hello.xql
  18555. @end example
  18556. This lets the web-application find the compiled servlets.
  18557. Finally, you just need to add the new servlet to
  18558. the @code{WEB-INF/web.xml} file:
  18559. @example
  18560. <web-app>
  18561. <display-name>My Application</display-name>
  18562. <servlet>
  18563. <servlet-name>MyHello</servlet-name>
  18564. <servlet-class>hello</servlet-class>
  18565. </servlet>
  18566. <servlet-mapping>
  18567. <servlet-name>MyHello</servlet-name>
  18568. <url-pattern>/hello</url-pattern>
  18569. </servlet-mapping>
  18570. </web-app>
  18571. @end example
  18572. The @code{<servlet>} clause says that the servlet named
  18573. @code{MyHello} is implemented by the Java class @code{hello}.
  18574. The @code{<servlet-mapping>} clause says that a request
  18575. URL @code{/hello} should be handled by the servlet named @code{MyHello}.
  18576. The URL is relative to the application context path,
  18577. so the actual URL would be @code{http://example.com/myapp/hello}.
  18578. @subsection Installing a servlet under Tomcat
  18579. @cindex Tomcat
  18580. Apache's @uref{http://tomcat.apache.org/,Tomcat} is an open-source
  18581. implementation of the servlet specifications.
  18582. After you @uref{http://tomcat.apache.org/download-60.cgi, download it},
  18583. uncompress it in some convenient location,
  18584. which is commonly referred to as @code{$CATALINA_HOME}.
  18585. To install your web application, copy/move its directory
  18586. to be in the @code{$CATALINA_HOME/webapps} directory.
  18587. Thus for the example above you would have
  18588. a @code{$CATALINA_HOME/webapps/myapp} directory.
  18589. To start or stop Tomcat use the scripts in @code{$CATALINA_HOME/bin}.
  18590. For example to start Tomcat on a GNU/Linux system run
  18591. @code{$CATALINA_HOME/bin/startup.sh}. This will start a web server
  18592. that listens on the default port of 8080,
  18593. so you can browse the above example at @code{http://localhost:8080/myapp/hello}.
  18594. If you're running Fedora GNU/Linux, you can use the @code{tomcat6} package:
  18595. @example
  18596. # yum install tomcat6
  18597. # export CATALINA_HOME=/usr/share/tomcat6
  18598. @end example
  18599. You can the manage Tomcat like other system services.
  18600. You can install webapps under @code{$CATALINA_HOME/webapps}.
  18601. @subsection Installing a servlet under Glassfish
  18602. @cindex Glassfish
  18603. @uref{https://glassfish.dev.java.net/,Glassfish} from Oracle/Sun
  18604. is a open-source ``application server'' that implements
  18605. Java EE 6, including the 3.0 servlet specification.
  18606. After you @uref{https://glassfish.dev.java.net/downloads/3.0.1-final.html, download it}, uncompress it in some convenient location.
  18607. This location is called @var{as-install-parent} in the
  18608. @uref{http://docs.sun.com/app/docs/doc/820-7689/aboaa?a=view,Quick Start Guide}.
  18609. The commands you will use is most in @code{@var{as-install}/bin},
  18610. where @var{as-install} is @code{@var{as-install}/glassfish}.
  18611. To start the server, do:
  18612. @example
  18613. @var{as-install}/bin/startserv
  18614. @end example
  18615. or under under Windows:
  18616. @example
  18617. @var{as-install}\bin\startserv.bat
  18618. @end example
  18619. The default post to listen to is @code{8080};
  18620. you can the port (and lots of other properties)
  18621. using the adminstration console at port @code{4848}.
  18622. A web application does not need to be any particular
  18623. location, instead you just install it with this command:
  18624. @example
  18625. @var{as-install}/bin/adadmin deploy @var{appdir}
  18626. @end example
  18627. where @var{appdir} is the application directory - @code{myapp} in the example.
  18628. (Use @code{asadmin.bat} under Windows.)
  18629. @subsection Servlet-specific script functions
  18630. The following functions only work within a servlet container.
  18631. To use these functions, first do:
  18632. @example
  18633. (require 'servlets)
  18634. @end example
  18635. You can conditionalize your code to check at compile-time for servlets,
  18636. like this:
  18637. @example
  18638. (cond-expand
  18639. (in-servlet
  18640. (require 'servlets)
  18641. (format "[servlet-context: ~s]" (current-servlet-context)))
  18642. (else
  18643. "[Not in a servlet]"))
  18644. @end example
  18645. For a run-time check you can test if @code{(current-servlet)} is
  18646. non-@code{#!null}.
  18647. @deffn Procedure current-servlet
  18648. When called from a Kawa servlet handler, returns the
  18649. actual @code{javax.servlet.http.HttpServlet} instance.
  18650. Returns @code{#!null} if the current context is not that of
  18651. @code{KawaServlet}.
  18652. (Hence this function also returns @code{#!null} if you compile a servlet
  18653. ``by hand'' rather that using the @code{--servet} option.)
  18654. @end deffn
  18655. @deffn Procedure current-servlet-context
  18656. Returns the context of the currently executing servlet,
  18657. as an instance of @code{javax.servlet.ServletContext}.
  18658. @end deffn
  18659. @deffn Procedure current-servlet-config
  18660. Returns the @code{ServletConfig} of the currently executing servlet.
  18661. @end deffn
  18662. @deffn Procedure get-request
  18663. Return the current servlet request, as an instance of
  18664. @code{javax.servlet.http.HttpServletRequest}.
  18665. @end deffn
  18666. @deffn Procedure get-response
  18667. Return the current servlet response, as an instance of
  18668. @code{javax.servlet.http.HttpServletResponse}.
  18669. @end deffn
  18670. @deffn Procedure request-servlet-path
  18671. Get the servlet path of the current request.
  18672. Similar to @code{request-script-path}, but not always the same,
  18673. depending on configuration, and does @emph{not} end with a @code{"/"}.
  18674. @end deffn
  18675. @deffn Procedure request-path-info
  18676. Get the path info of the current request.
  18677. Corresponds to the CGI variable @code{PATH_INFO}.
  18678. @end deffn
  18679. @deffn Procedure servlet-context-realpath [path]
  18680. Returns the file path of the current servlet's "Web application".
  18681. @end deffn
  18682. @node CGI scripts, HTTP requests, Servlets, XML tools
  18683. @section Installing Kawa programs as CGI scripts
  18684. The recommended way to have a web-server run a Kawa program
  18685. as a CGI script is to compile the Kawa program to a servlet
  18686. (as explained in @ref{Server-side scripts}, and then use
  18687. Kawa's supplied CGI-to-servlet bridge.
  18688. First, compile your program to one or more class files
  18689. as explained in @ref{Server-side scripts}. For example:
  18690. @example
  18691. kawa --servlet --xquery -C hello.xql
  18692. @end example
  18693. Then copy the resulting @code{.class} files to your server's
  18694. CGI directory. On Red Hat GNU/Linux, you can do the following (as root):
  18695. @example
  18696. cp hello*.class /var/www/cgi-bin/
  18697. @end example
  18698. Next find the @code{cgi-servlet} program that Kawa builds and installs.
  18699. If you installed Kawa in the default place, it will be in
  18700. @code{/usr/local/bin/cgi-servlet}.
  18701. (You'll have this if you installed Kawa from source, but not
  18702. if you're just using Kawa @code{.jar} file.)
  18703. Copy this program into the same CGI directory:
  18704. @example
  18705. cp /usr/local/bin/cgi-servlet /var/www/cgi-bin/
  18706. @end example
  18707. You can link instead of copying:
  18708. @example
  18709. ln -s /usr/local/bin/cgi-servlet /var/www/cgi-bin/
  18710. @end example
  18711. However, because of security issues this may not work, so it is
  18712. safer to copy the file. However, if you already have a copy
  18713. of @code{cgi-servlet} in the CGI-directory, it is safe to make
  18714. a hard link instead of making an extra copy.
  18715. Make sure the files have the correct permissions:
  18716. @example
  18717. chmod a+r /var/www/cgi-bin/hello*.class /var/www/cgi-bin/hello
  18718. chmod a+x /var/www/cgi-bin/hello
  18719. @end example
  18720. Now you should be able to run the Kawa program,
  18721. using the URL @url{http://localhost/cgi-bin/hello}.
  18722. It may take a few seconds to get the reply, mainly because of the
  18723. start-up time of the Java VM. That is why servlets are
  18724. preferred. Using the CGI interface can still be useful
  18725. for testing or when you can't run servlets.
  18726. @node HTTP requests, HTTP response, CGI scripts, XML tools
  18727. @section Functions for accessing HTTP requests
  18728. The following functions are useful for accessing
  18729. properties of a HTTP request, in a Kawa program that is
  18730. run either as a servlet or a CGI script. These functions
  18731. can be used from plain Scheme, from KRL (whether
  18732. in BRL-compatible mode or not), and from XQuery.
  18733. The examples below assume the request @code{http://example.com:8080/myapp/foo/bar?val1=xyz&val2=abc}, where @code{myapp} is the application context.
  18734. We also assume that this is handled by a script @code{foo/+default+}.
  18735. The file @code{testsuite/webtest/info/+default+} in the Kawa source distribution
  18736. calls most of these functions.
  18737. You can try it as described in @ref{Self-configuring page scripts}.
  18738. @subsection Request URL components
  18739. @deffn Procedure request-URI
  18740. Returns the URI of the request, as a value of type @code{URI}.
  18741. This excludes the server specification,
  18742. but includes the query string.
  18743. (It is the combination of CGI variables @code{SCRIPT_NAME},
  18744. @code{PATH_INFO}, and @code{QUERY_STRING}.
  18745. Using servlets terminology, it is the combination of
  18746. Context Path, Servlet Path, PathInfo, and Query String.)
  18747. @example
  18748. (request-URI) @result{} "/myapp/foo/bar?val1=xyz&val2=abc"
  18749. @end example
  18750. @end deffn
  18751. @deffn Procedure request-path
  18752. Returns the URI of the request, as a value of type @code{URI}.
  18753. This excludes the server specification and the query string.
  18754. Equivalent to @code{(path-file (request-URI))}.
  18755. (It is the combination of CGI variables @code{SCRIPT_NAME}, and
  18756. @code{PATH_INFO}.
  18757. Same as the concatenation of @code{(request-context-path)},
  18758. @code{(request-script-path)}, and @code{(request-local-path)}.
  18759. Using servlets terminology, it is the combination of
  18760. Context Path, Servlet Path, and PathInfo.)
  18761. @example
  18762. (request-path) @result{} "/myapp/foo/bar"
  18763. @end example
  18764. @end deffn
  18765. @deffn Procedure request-uri
  18766. This function is deprecated, because of possible confusion
  18767. with @code{request-URI}. Use @code{request-path} instead.
  18768. @end deffn
  18769. @deffn Procedure request-url
  18770. Returns the complete URL of the request, except the query string.
  18771. The result is a @code{java.lang.StringBuffer}.
  18772. @example
  18773. (request-url) @result{} "http://example.com:8080/myapp/foo/bar"
  18774. @end example
  18775. @end deffn
  18776. @deffn Procedure request-context-path
  18777. Returns the context path, relative to the server root.
  18778. This is an initial substring of the @code{(request-path)}.
  18779. Similar to the Context Path of a servlet request,
  18780. except that it ends with a @code{"/"}.
  18781. @example
  18782. (request-context-path) @result{} "/myapp/"
  18783. @end example
  18784. @end deffn
  18785. @deffn Procedure request-script-path
  18786. Returns the path of the script, relative to the context.
  18787. This is either an empty string, or a string that ends with @code{"/"},
  18788. but does not start with one. (The reason for this is to produce URIs
  18789. that work better with operations like @code{resolve-uri}.)
  18790. This is conceptually similar to @code{request-servlet-path},
  18791. though not always the same, and the @code{"/"} conventions differ.
  18792. @example
  18793. (request-script-path) @result{} "foo/"
  18794. @end example
  18795. @end deffn
  18796. @deffn Procedure request-local-path
  18797. Returns the remainder of the @code{request-path},
  18798. relative to the @code{request-script-path}.
  18799. @example
  18800. (request-local-path) @result{} "bar"
  18801. @end example
  18802. @end deffn
  18803. @deffn Procedure request-query-string
  18804. Returns the query string from an HTTP request. The query string is
  18805. the part of the request URL after a question mark.
  18806. Returns false if there was no query string.
  18807. Corresponds to the CGI variable @code{QUERY_STRING}.
  18808. @example
  18809. (request-query-string) @result{} "val1=xyz&val2=abc"
  18810. @end example
  18811. @end deffn
  18812. @subsection Request parameters
  18813. Request parameters are used for data returned from forms,
  18814. and for other uses.
  18815. They may be encoded in the query string or in the request body.
  18816. @deffn Procedure request-parameter name [default]
  18817. If there is a parameter with the given name (a string),
  18818. return the (first) corresponding value, as a string.
  18819. Otherwise, return the @var{default} value,
  18820. or @code{#!null} if there is no @var{default}.
  18821. @example
  18822. (request-parameter "val1") @result{} "xyz"
  18823. (request-parameter "val9" "(missing)") @result{} "(missing)"
  18824. @end example
  18825. @end deffn
  18826. @deffn Procedure request-parameters name
  18827. If there is are one or more parameter with the given name (a string),
  18828. return them all (as multiple values).
  18829. Otherwise, return no values (i.e. @code{(values)}).
  18830. @example
  18831. (request-parameters "val1") @result{} "xyz"
  18832. (request-parameters "val9") @result{} #!void
  18833. @end example
  18834. @end deffn
  18835. @deffn Procedure request-parameter-map
  18836. Request a map of all the parameters.
  18837. This is a map from strings to a sequence of strings.
  18838. (Specifically, a @code{java.util.Map<String,java.util.List<String>>}.)
  18839. @end deffn
  18840. @subsection Request headers
  18841. The request headers are a set of (keyword, string)-pairs
  18842. transmitted as part of the HTTP request, before the request body.
  18843. @deffn Procedure request-header name
  18844. If there is a header with the given @var{name} (a string),
  18845. return the corresponding value string.
  18846. Otherwise, return @code{#!null}.
  18847. @example
  18848. (request-header "accept-language") @result{} "en-us,en;q=0.5"
  18849. @end example
  18850. @end deffn
  18851. @deffn Procedure request-header-map
  18852. Request a map of all the headers.
  18853. This is a map from strings to a sequence of strings.
  18854. (Specifically, a @code{java.util.Map<String,java.util.List<String>>}.)
  18855. @end deffn
  18856. @subsection Request body
  18857. @deffn Procedure request-input-port
  18858. Return a textual input port for reading the request body,
  18859. as a sequence of characters.
  18860. @end deffn
  18861. @deffn Procedure request-input-stream
  18862. Return a binary input stream for reading the request body,
  18863. as a sequence of bytes.
  18864. @end deffn
  18865. @deffn Procedure request-body-string
  18866. Return the entire request body as a string
  18867. @end deffn
  18868. @subsection Request IP addresses and ports
  18869. Information about the interface and port on which the request was received.
  18870. @deffn Procedure request-local-socket-address
  18871. The local address on which the request was received.
  18872. This is the combination of @code{(request-local-host)}
  18873. and @code{(request-local-port)}, as an instance of
  18874. @code{java.net.InetSocketAddress}.
  18875. @end deffn
  18876. @deffn Procedure request-local-host
  18877. Get the IP address of the interface on which request was received,
  18878. as an @code{java.net.InetAddress}.
  18879. @end deffn
  18880. @deffn Procedure request-local-IP-address
  18881. Get the IP address of the interface on which request was received,
  18882. a string in numeric form:
  18883. @example
  18884. (request-local-host) @result{} "127.0.0.1"
  18885. @end example
  18886. @end deffn
  18887. @deffn Procedure request-local-port
  18888. Get the port this request was received on.
  18889. @example
  18890. (request-local-port) @result{} 8080
  18891. @end example
  18892. @end deffn
  18893. Information about the interface and port of the remote client that invoked the request.
  18894. @deffn Procedure request-remote-socket-address
  18895. The address of the remote client (usually a web browser)
  18896. which invoked the request.
  18897. This is the combination of @code{(request-remove-host)}
  18898. and @code{(request-remote-port)}, as an instance of
  18899. @code{java.net.InetSocketAddress}.
  18900. @end deffn
  18901. @deffn Procedure request-remote-host
  18902. Get the IP address of the remote client which invoked the request,
  18903. as an @code{java.net.InetAddress}.
  18904. @end deffn
  18905. @deffn Procedure request-remote-IP-address
  18906. Get the IP address of the remote client which invoked the request,
  18907. as a string in numeric form.
  18908. @example
  18909. (request-remote-host) @result{} "123.45.6.7"
  18910. @end example
  18911. @end deffn
  18912. @deffn Procedure request-remote-port
  18913. The port used by the remote client.
  18914. @end deffn
  18915. @subsection Miscellaneous request properties
  18916. @deffn Procedure request-path-translated
  18917. Map the request-path to a file name (a string)
  18918. in the server application directory.
  18919. Corresponds to the CGI variable @code{PATH_TRANSLATED}.
  18920. @end deffn
  18921. @deffn Procedure request-method
  18922. Returns the method of the HTTP request, usually @code{"GET"}
  18923. or @code{"POST"}. Corresponds to the CGI variable @code{REQUEST_METHOD}.
  18924. @end deffn
  18925. @deffn Procedure request-scheme
  18926. Returns the scheme (protocol) of the request.
  18927. Usually @code{"http"}, or @code{"https"}.
  18928. @end deffn
  18929. @node HTTP response, XML beyond Scheme, HTTP requests, XML tools
  18930. @section Generating HTTP responses
  18931. The result of evaluating the top-level expressions of a web page script
  18932. becomes the HTTP response that the servlet sends back to the browser.
  18933. The result is typically an HTML/XML element code object
  18934. Kawa will automatically format the result as appropriate for the type.
  18935. Before the main part of the response there may be
  18936. special "response header values",
  18937. as created by the @code{response-header} function.
  18938. Kawa will use the response header values to set various
  18939. required and optional fields of the HTTP response.
  18940. Note that @code{response-header} does not actually do anything
  18941. until it is "printed" to the standard output.
  18942. Note also that a @code{"Content-Type"} response value is
  18943. special since it controls the formatting of the following
  18944. non-response-header values.
  18945. @deffn Procedure response-header key value
  18946. Create the response header @samp{@var{key}: @var{value}} in the HTTP
  18947. response. The result is a "response header value" (of some unspecified
  18948. type). It does not directly set or print a response header, but only
  18949. does so when you actually "print" its value to the response output stream.
  18950. @end deffn
  18951. @deffn Procedure response-content-type type
  18952. Species the content-type of the result - for example @code{"text/plain"}.
  18953. Convenience function for @code{(response-header "Content-Type" @var{type})}.
  18954. @end deffn
  18955. @deffn Procedure error-response code [message]
  18956. Creates a response-header with an error code of @var{code} and a
  18957. response message of @var{message}.
  18958. (For now this is the same as @code{response-status}.)
  18959. Note this also returns a response-header value, which does not actually
  18960. do anything unless it is returned as the result of executing a servlet body.
  18961. @end deffn
  18962. @deffn Procedure response-status code [message]
  18963. Creates a response-header with an status code of @var{code} and a
  18964. response message of @var{message}.
  18965. (For now this is the same as @code{error-response}.)
  18966. @end deffn
  18967. @node XML beyond Scheme, , HTTP response, XML tools
  18968. @section Using non-Scheme languages for XML/HTML
  18969. @subsection XQuery language
  18970. Bundled with Kawa is a fairly complete implementation of W3C's
  18971. new @uref{http://www.w3c.org/XML/Query,XML Query language}.
  18972. If you start Kawa with the @code{--xquery} it selects the "XQuery"
  18973. source language; this also prints output using XML syntax.
  18974. See the @uref{http://www.gnu.org/software/qexo/,Qexo (Kawa-XQuery) home page}
  18975. for examples and more information.
  18976. @subsection XSL transformations
  18977. There is an experimental implementation of the XSLT (XML Stylesheet
  18978. Language Transformations) language. Selecting @code{--xslt} at the
  18979. Kawa command line will parse a source file according to the syntax
  18980. on an XSLT stylesheet.
  18981. See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
  18982. for more information.
  18983. @menu
  18984. * KRL:: KRL - The Kawa Report Language for generating XML/HTML
  18985. @end menu
  18986. @node KRL, , , XML beyond Scheme
  18987. @subsection KRL - The Kawa Report Language for generating XML/HTML
  18988. KRL (the "Kawa Report Language") is powerful Kawa dialect for embedding
  18989. Scheme code in text files such as HTML or XML templates. You select
  18990. the KRL language by specifying @code{--krl} on the Kawa command line.
  18991. KRL is based on on @uref{http://brl.sourceforge.net/,BRL},
  18992. Bruce Lewis's "Beautiful Report Language", and
  18993. uses some of BRL's code, but there are some experimental differences,
  18994. and the implementation core is different. You can run KRL in
  18995. BRL-compatility-mode by specifying @code{--brl} instead of @code{--krl}.
  18996. @subsection Differences between KRL and BRL
  18997. This section summarizes the known differences between KRL and BRL.
  18998. Unless otherwise specified, KRL in BRL-compatibility mode will
  18999. act as BRL.
  19000. @itemize
  19001. @item
  19002. In BRL a normal Scheme string @code{"mystring"} is the same
  19003. as the inverted quote string @code{]mystring[}, and both are instances
  19004. of the type @code{<string>}.
  19005. In KRL @code{"mystring"} is a normal Scheme string of type @code{<string>},
  19006. but @code{]mystring[} is special type that suppresses output escaping.
  19007. (It is equivalent to @code{(unescaped-data "mystring")}.)
  19008. @item
  19009. When BRL writes out a string, it does not do any processing
  19010. to escape special characters like @code{<}. However, KRL in its default
  19011. mode does normally escape characters and strings. Thus @code{"<a>"}
  19012. is written as @code{&lt;a&gr;}.
  19013. You can stop it from doing this by overriding the output format, for example
  19014. by specifying @code{--output-format scheme} on the Kawa command line,
  19015. or by using the @code{unescaped-data} function.
  19016. @item
  19017. Various Scheme syntax forms, including @code{lambda},
  19018. take a @stxref{body}, which is a list of one or more declarations and
  19019. expressions. In normal Scheme and in BRL the value of a @var{body}
  19020. is the value of the last expression. In KRL the value of a @var{body}
  19021. is the concatenation of all the values of the expressions,
  19022. as if using @code{values-append}.
  19023. @item
  19024. In BRL a word starting with a colon is a keyword.
  19025. In KRL a word starting with a colon is an identifier, which by
  19026. default is bound to the @code{make-element} function specialized
  19027. to take the rest of the word as the tag name (first argument).
  19028. @item
  19029. BRL has an extensive utility library. Most of this has not yet been ported
  19030. to KRL, even in BRL-compatibility mode.
  19031. @end itemize
  19032. @node Miscellaneous
  19033. @chapter Miscellaneous topics
  19034. @deffn Procedure scheme-implementation-version
  19035. Returns the Kawa version number as a string.
  19036. @c (Compatible with slib.)
  19037. @end deffn
  19038. @deffn Procedure scheme-window [shared]
  19039. Create a read-eval-print-loop in a new top-level window.
  19040. If @var{shared} is true, it uses the same environment as the
  19041. current @code{(interaction-environment)}; if not (the default),
  19042. a new top-level environment is created.
  19043. You can create multiple top-level window that can co-exist.
  19044. They run in separate threads.
  19045. @end deffn
  19046. @menu
  19047. * Composable pictures::
  19048. * Building JavaFX applications::
  19049. * Building for Android:: Building for Android devices
  19050. * Android view construction::
  19051. * System inquiry::
  19052. * Processes::
  19053. * Time-related functions::
  19054. * Low-level functions:: Deprecated low-level functions
  19055. @end menu
  19056. @node Composable pictures
  19057. @section Composable pictures
  19058. The @code{(kawa pictures)} library lets you create geometric shapes
  19059. and images, and combine them in interesting ways.
  19060. The @ref{Tutorial - Pictures,tutorial} gives an introduction.
  19061. The easiest way to use and learn the @code{pictures} library
  19062. is with a suitable REPL. You can use the old Swing-based console
  19063. or any @ref{Using DomTerm,DomTerm}-based terminal emulator.
  19064. You can create a suitable window either by starting @code{kawa}
  19065. with the @code{-w} flag, or by running the @code{kawa} command
  19066. inside an existing DomTerm-based terminal emulator.
  19067. The screenshot below is of the latter,
  19068. using the @code{qtdomterm} terminal emulator.
  19069. @image{images/domterm-pictures-1}
  19070. After @code{(import (kawa swing))} you can use @code{show-picture}
  19071. to display a picture in a Swing window.
  19072. A @dfn{picture} is an object that can be displayed on a screen,
  19073. web-page, or printed page, and combined with other pictures.
  19074. A picture has a method printing itself in a graphical context.
  19075. It also has various properties.
  19076. An important property of a picture is its @dfn{bounding box}.
  19077. This is a rectangle (with edges parallel to the axes) that
  19078. surrounds the contents of the picture.
  19079. Usually the entire visible part of the picture is inside the
  19080. bounding box, but in some cases part of the picture may stick
  19081. outside the bounding box.
  19082. For example when a circle is drawn (stroked) with a ``pen'',
  19083. the bounding box is that of the infinitely-thin mathematical circle, so
  19084. ``ink'' from the pen that is outside the circle may be outside the bounding box.
  19085. A picture has an origin point corresponding to the (0 0) cordinates.
  19086. The origin is commonly but not always inside the bounding box.
  19087. Certain operations (for example @code{hbox}) combine pictures by putting
  19088. them ``next to'' each other, where ``next to'' is defined in
  19089. terms of the bounding box and origin point.
  19090. @c The Racket language has a @uref{https://docs.racket-lang.org/pict/,Pict}
  19091. @c library, with a lot more functionality;
  19092. @c it is used by the @uref{https://docs.racket-lang.org/quick/,Racket tutorial}.
  19093. @c Racket also has a @uref{https://docs.racket-lang.org/teachpack/2htdpimage-guide.html,@code{2htdp/image} library} which should also be studied.
  19094. @subsection Coordinates - points and dimensions
  19095. The library works with a two-dimensional grid,
  19096. where each position has an x cordinate and y coordinate.
  19097. Normally, x values increase as you move right on the screen/page,
  19098. while y values increase as you move @emph{down}.
  19099. This convention matches that used by Java 2D, SVG, and many other
  19100. graphics libraries. However, note that this is different from the traditional
  19101. mathematical convention of y values increasing as you go up.
  19102. By default, one unit is one ``pixel''. (More precisely,
  19103. it is the @code{px} unit in the CSS specification.)
  19104. @deffn Type Point
  19105. A point is a pair consisting of an x and a y coordinate.
  19106. @end deffn
  19107. @deftypefn Literal {} &P@stxlit{[} @var{x} @var{y} @stxlit{]}
  19108. Construct a point value with the specified @var{x} and @var{y} values.
  19109. Both @var{x} and @var{y} are expressions that evaluate to real numbers:
  19110. @example
  19111. &P[(+ old-right 10) baseline]
  19112. @end example
  19113. @end deftypefn
  19114. @deffn Type Dimension
  19115. A dimension value is a pair of a width and a height.
  19116. It is used for the size of pictures in the two dimensions.
  19117. In a context that expects a point, a dimension is treated
  19118. as an offset relative to some other point.
  19119. @end deffn
  19120. @deftypefn Literal {} &D@stxlit{[} @var{width} @var{height} @stxlit{]}
  19121. Construct a dimension value with the specified @var{width}
  19122. and @var{height} values, which are both expressions that
  19123. evaluate to real numbers.
  19124. @end deftypefn
  19125. @subsection Shapes
  19126. A shape is a collection of lines and curves.
  19127. Examples include lines, circles, and polygons.
  19128. A shape can be @dfn{stroked}, which you can think of as
  19129. being drawn by a very fancy calligraphic pen that
  19130. follows the lines and curves of the shape.
  19131. A @dfn{closed shape} is a shape that is continuous and ends up where it
  19132. started. This includes circles and polygons.
  19133. A closed shape can be filled, which means the entire ``interior''
  19134. is painted with some color or texture.
  19135. A shape is represented by the Java @code{java.awt.Shape} interface.
  19136. The @code{picture} library only provides relatively simple shapes,
  19137. but you can use any methods that create a @code{java.awt.Shape} object.
  19138. @dfn{Shape} is effectively a sub-type of @dfn{picture},
  19139. though they're represented using using disjoint classes:
  19140. If you use a shape where a picture is required,
  19141. the shape is automatically converted to a picture,
  19142. as if using the @code{draw} procedure.
  19143. @deffn Procedure line p1 [p2 ...]
  19144. In the simple case two points are specified, and the result
  19145. is a line that goes from point @var{p1} to @var{p2}.
  19146. If @var{n} points are specied, the result is a @dfn{polyline}:
  19147. a path consisting of @var{n-1} line segments, connecting adjacent arguments.
  19148. (If only a single point is specified, the result is degenerate
  19149. single-point shape.)
  19150. All of the points except the first can optionally be specified
  19151. using a dimension, which is treated an an offset from the previous point:
  19152. @example
  19153. (line &P[30 40] &D[10 5] &D[10 -10])
  19154. @end example
  19155. is the same as:
  19156. @example
  19157. (line &P[30 40] &P[40 45] &P[50 35])
  19158. @end example
  19159. @end deffn
  19160. @deffn Procedure polygon p1 [p2 ...]
  19161. Constructs a closed shape from line segments.
  19162. This is the same as calling @code{line} with the same arguments,
  19163. with the addition of a final line segment from the last point
  19164. back to the first point.
  19165. @end deffn
  19166. @deffn Procedure rectangle p1 [p2]
  19167. A rectangle is closed polygon of 4 line segments that are
  19168. alternatively parallel to the x-axis and the y-axis.
  19169. I.e. if you rotate a rectangle it is no longer a rectangle by
  19170. this definition, though of course it still has a rectangular shape.
  19171. If @var{p2} is not specified, constructs a rectangle whose upper-left corner
  19172. is @code{&P[0 0]} and whose lower-right corner is @var{p1}.
  19173. If @var{p2} is specified, constructs a rectangle whose upper-left corner
  19174. is @var{p1} and whose lower-right corner is @var{p2}.
  19175. If @var{p2} is a dimension it is considered a relative offset from @var{p1},
  19176. just like for @code{polygon}.
  19177. @end deffn
  19178. @deffn Procedure circle radius [center]
  19179. Creates a circle with the specified @var{radius}.
  19180. If the @var{center} is not specified, it defaults to @code{&P[0 0]}.
  19181. @end deffn
  19182. @subsection Colors and paints
  19183. A @dfn{paint} is a color pattern used to fill part of the canvas.
  19184. A paint can be a color, a texture (a replicated pattern), or a gradient
  19185. (a color that gradually fades to some other color).
  19186. A @dfn{color} is defined by red, green, and blue values.
  19187. It may also have an alpha component, which specifies transparency.
  19188. @deffn Procedure ->paint value
  19189. Converts @var{value} to a color - or more general a paint.
  19190. Specificlly, the return type is @code{java.awt.Paint}.
  19191. The @var{value} can be any one of:
  19192. @itemize
  19193. @item
  19194. A @code{java.awt.Paint}, commonly a @code{java.awt.Color}.
  19195. @item
  19196. A 24-bit integer value is converted to a color.
  19197. Assume the integer is equal
  19198. to a hexadecimal literal of the form @code{#xRRGGBB}.
  19199. Then @code{RR} (bits 16-23) is the intensity of the red component;
  19200. @code{GG} (bits 8-15) is the intensity of the green component; and
  19201. @code{RR} (bits 0-7) is the intensity of the red component.
  19202. @item
  19203. One of the standard HTML/CSS/SVG color names, as a string or symbol.
  19204. See the table in @code{gnu/kawa/models/StandardColor.java} source file.
  19205. Case is ignored, and you can optionally use hyphens to separate words.
  19206. For example @code{'hot-pink}, @code{'hotpink}, and @code{'hotPink}
  19207. are all the same sRGB color @code{#xFF69B4}.
  19208. @end itemize
  19209. @end deffn
  19210. @deffn Procedure with-paint paint picture
  19211. Create a new picture that is the ``same'' as @var{picture}
  19212. but use @var{paint} as the default paint.
  19213. For @var{paint} you can use any valid argument to @code{->paint}.
  19214. The default paint (which is the color black if none is specified)
  19215. is used for both @code{fill} (paint interior) and @code{draw} (stroke outline).
  19216. @example
  19217. #|kawa:1|# @kbd{(! circ1 (circle 20 &P[20 20]))}
  19218. #|kawa:2|# @kbd{(hbox (fill circ1) (draw circ1))}
  19219. @image{images/paint-circ-1}
  19220. #|kawa:3|# @kbd{(with-paint 'hot-pink (hbox (fill circ1) (draw circ1)))}
  19221. @image{images/paint-circ-2}
  19222. @end example
  19223. Above we use @code{with-paint} to create a cloned picture, which is
  19224. the same as the original @code{hbox}, except for the default paint,
  19225. in this case the color @code{hot-pink}.
  19226. @example
  19227. #|kawa:4|# @kbd{(! circ2 (hbox (fill circ1) (with-paint 'hot-pink (fill circ1))))}
  19228. #|kawa:5|# @kbd{circ2}
  19229. @image{images/paint-circ-3}
  19230. #|kawa:6|# @kbd{(with-paint 'lime-green circ2)}
  19231. @image{images/paint-circ-4}
  19232. @end example
  19233. Here @code{circ2} is an @code{hbox} of two filled circles,
  19234. one that has unspecified paint, and one that is @code{hot-pink}.
  19235. Printing @code{circ2} directly uses black for the
  19236. circle with unspecified color,
  19237. but if we wrap @code{circ2} in another @code{with-paint}
  19238. that provides a default that is used for the first circle.
  19239. @end deffn
  19240. @subsection Filling a shape with a color
  19241. @deffn Procedure fill shape
  19242. @deffnx Procedure fill paint shape
  19243. Fill the ``inside'' of @var{shape}.
  19244. If no @var{paint} is specified, uses the current default paint.
  19245. Otherwise, @code{(fill @var{paint} @var{shape})}
  19246. is the same @code{(with-paint @var{paint} (fill @var{shape}))}.
  19247. @end deffn
  19248. @subsection Stroking (outlining) a shape
  19249. @deffn Procedure draw @arbno{option} @atleastone{shape}
  19250. Returns a picture that draws the outline of the @var{shape}.
  19251. This is called @dfn{stroking}.
  19252. An @var{option} may be one of:
  19253. @itemize
  19254. @item
  19255. A @code{Paint} or @code{Color} object, which is used to draw the shape.
  19256. @item
  19257. A standard color name, such as @code{'red} or @code{'medium-slate-blue}.
  19258. This is mapped to a @code{Color}.
  19259. @item
  19260. A join-specifier, which is a symbol specifying how each curve of the shape is
  19261. connected to the next one.
  19262. The options are @code{'miter-join}, @code{'round-join}, and @code{'bevel-join}.
  19263. The default if none is specified is @code{'miter-join}.
  19264. @item
  19265. A end-cap-specifier, which is a symbol specifying how each end of the
  19266. shape is terminated.
  19267. The options are @code{'square-cap}, @code{'round-cap}, or @code{'butt-cap}.
  19268. The default is @code{'butt-cap}.
  19269. (This follows SVG and HTML Canvas.
  19270. The default in plain Java AWT is a square cap.)
  19271. @item
  19272. A real number specifies the thickness of the stroke.
  19273. @item
  19274. A @code{java.awt.Stroke} object.
  19275. This combines join-specifier, end-cap-specifier, thickness, and more
  19276. in a single object. The @code{BasicStroke} class can specify dashes,
  19277. though that is not yet supported for SVG output; only AWT or image output.
  19278. @end itemize
  19279. Let us illustrate with a sample line @code{lin}
  19280. and a helper macro @code{show-draw}, which adds a border around a shape,
  19281. then draws the given shape with some options, and finally
  19282. re-draws the shape in plain form.
  19283. @example
  19284. #|kawa:10|# @kbd{(define lin (line &P[0 0] &P[300 40] &P[200 100] &P[50 70]))}
  19285. #|kawa:11|# @kbd{(define-syntax show-draw}
  19286. #|....:12|# @kbd{ (syntax-rules ()}
  19287. #|....:13|# @kbd{ ((_ options ... shape)}
  19288. #|....:14|# @kbd{ (border 12 'bisque (zbox (draw options ... shape) shape)))))}
  19289. #|....:15|# @kbd{(show-draw 8 'lime lin)}
  19290. @image{images/show-draw-1}
  19291. #|....:16|# @kbd{(show-draw 8 'lime 'round-cap 'round-join lin)}
  19292. @image{images/show-draw-2}
  19293. #|....:17|# @kbd{(show-draw 8 'lime 'square-cap 'bevel-join lin)}
  19294. @image{images/show-draw-3}
  19295. @end example
  19296. @end deffn
  19297. Notice how the different cap and join styles change the drawing.
  19298. Also note how the stroke (color lime) extends beyond its bounding box,
  19299. into the surrounding border (color bisque).
  19300. @subsection Affine transforms
  19301. A 2D affine transform is a linear mapping from coordinates to
  19302. coordinates. It generalizes translation, scaling, flipping, shearing,
  19303. and their composition. An affine transform maps straight parallel lines
  19304. into other straight parallel lines, so it is only a subset of possible
  19305. mappings - but a very useful subset.
  19306. @deffn Procedure affine-transform xx xy yx yy x0 y0
  19307. @deffnx Procedure affine-transform px py p0
  19308. Creates a new affine transform.
  19309. The result of applying @code{(affine-transform @var{x@sub{x}} @var{x@sub{y}} @var{y@sub{x}} @var{y@sub{y}} @var{x@sub{0}} @var{y@sub{0}})}
  19310. to the point @code{&P[@var{x} @var{y}]}
  19311. is the transformed point
  19312. @example
  19313. &P[(+ (* @var{x} @var{x@sub{x}}) (* @var{y} @var{y@sub{x}}) @var{x@sub{0}})
  19314. (+ (* @var{x} @var{x@sub{y}}) (* @var{y} @var{y@sub{y}}) @var{y@sub{0}})]
  19315. @end example
  19316. If using point arguments,
  19317. @code{(affine-transform &P[@var{x@sub{x}} @var{x@sub{y}}] &P[@var{y@sub{x}} @var{y@sub{y}}] &P[@var{x@sub{0}} @var{y@sub{0}}])}
  19318. is equivalent to:
  19319. @code{(affine-transform @var{x@sub{x}} @var{x@sub{y}} @var{y@sub{x}} @var{y@sub{y}} @var{x@sub{0}} @var{y@sub{0}})}.
  19320. @end deffn
  19321. @deffn Procedure with-transform transform picture
  19322. @deffnx Procedure with-transform transform shape
  19323. Creates a transformed picture.
  19324. If the argument is a @var{shape}, then the result is also a shape.
  19325. @end deffn
  19326. @deffn Procedure with-transform transform point
  19327. Apply a transform to a single point, yielding a new point.
  19328. @end deffn
  19329. @deffn Procedure with-transform transform1 transform2
  19330. Combine two transforms, yielding the composed transform.
  19331. @end deffn
  19332. @deffn Procedure rotate angle
  19333. @deffnx Procedure rotate angle picture
  19334. The one-argument variant creates a new affine transform that rotates
  19335. a picture about the origin by the specified @var{angle}.
  19336. A positive @var{angle} yields a clockwise rotation.
  19337. The @var{angle} can be either a quantity (with a unit of
  19338. either @code{rad} radians, @code{deg} (degrees), or @code{grad} (gradians)),
  19339. or it can be a unit-less real number (which is treated as degrees).
  19340. The two-argument variant applies the resulting transform to
  19341. the specified picture. It is equivalent to:
  19342. @example
  19343. (with-transform (rotate @var{angle}) @var{picture})
  19344. @end example
  19345. @end deffn
  19346. @deffn Procedure scale factor
  19347. @deffnx Procedure scale factor picture
  19348. Scales the @var{picture} by the given @var{factor}.
  19349. The @var{factor} can be a real number.
  19350. The @var{factor} can also be a point or a dimension, in which case
  19351. the two cordinates are scaled by a different amount.
  19352. The two-argument variant applies the resulting transform to
  19353. the specified picture. It is equivalent to:
  19354. @example
  19355. (with-transform (scale @var{factor}) @var{picture})
  19356. @end example
  19357. @end deffn
  19358. @deffn Procedure translate offset
  19359. @deffnx Procedure translate offset picture
  19360. The single-argument variant creates a transform
  19361. that adds the @var{offset} to each point.
  19362. The @var{offset} can be either a point or a dimension (which
  19363. are treated quivalently).
  19364. The two-argument variant applies the resulting transform to
  19365. the specified picture. It is equivalent to:
  19366. @example
  19367. (with-transform (translate @var{offset}) @var{picture})
  19368. @end example
  19369. @end deffn
  19370. @subsection Combining pictures
  19371. @deffn Procedure hbox [spacing] picture ...
  19372. @deffnx Procedure vbox [spacing] picture ...
  19373. @deffnx Procedure zbox picture ...
  19374. Make a combined picture from multiple sub-pictures drawn
  19375. either ``next to'' or ``on top of'' each other.
  19376. The case of @code{zbox} is simplest: The sub-pictures are drawn
  19377. in argument order at the same position (origin). The ``@code{z}'' refers to
  19378. the idea that the pictures are stacked on top of each other along
  19379. the ``Z-axis'' (the one perpendicular to the screen).
  19380. The @code{hbox} and @code{vbox} instead place the sub-pictures
  19381. next to each other, in a row or column.
  19382. If @var{spacing} is specified, if must be a real number.
  19383. That much extra spacing is added between each sub-picture.
  19384. More precisely: @code{hbox} shifts each sub-picture except the first
  19385. so its left-origin control-point
  19386. (see discussion at @code{re-center}) has the same position
  19387. as the right-origin control point of the previous picture
  19388. @var{plus} the amount of @var{spacing}.
  19389. Similarly, @code{vbox} shifts each sub-picture except the first
  19390. so its top-origin control point has the same position
  19391. as the bottom-origin point of the previous picture, plus @var{spacing}.
  19392. The bounding box of the result is the smallest rectangle that
  19393. includes the bounding boxes of the (shifted) sub-pictures.
  19394. The origin of the result is that of the first picture.
  19395. @end deffn
  19396. @deffn Procedure border [size [paint]] picture
  19397. Return a picture that combines @var{picture}
  19398. with a rectangular border (frame) around @var{picture}'s bounding box.
  19399. The @var{size} specifies the thickness of the border:
  19400. it can be real number, in which it is the thickness on all four sides;
  19401. it can be a Dimension, in which case the width is the left and right
  19402. thickness, while the height is the top and bottom thickness;
  19403. or it can be a Rectangle, in which case it is the new bounding box.
  19404. If @var{paint} is specified it is used for the border;
  19405. otherwise the default paint is used.
  19406. The border is painted before (below) the @var{picture} painted.
  19407. The bounding box of the result is that of the border, while
  19408. the origin point is that of the original @var{picture}.
  19409. @example
  19410. #|kawa:2|# @kbd{(with-paint 'blue (border &D[8 5] (fill 'pink (circle 30))))}
  19411. @image{images/border-1}
  19412. @end example
  19413. @end deffn
  19414. @deffn Procedure padding width [background] picture
  19415. This is similar to @code{border},
  19416. but it just adds extra space around @var{picture},
  19417. without painting it. The @var{size} is specified the same way.
  19418. If @var{background} is specified,
  19419. it becomes the background paint for the entire padded
  19420. rectangle (both @var{picture} and the extra padding).
  19421. @example
  19422. #|kawa:3|# @kbd{(define circ1 (fill 'teal (circle 25)))}
  19423. #|kawa:4|# @kbd{(zbox (line &P[-30 20] &P[150 20])}
  19424. #|kawa:5|# @kbd{ (hbox circ1 (padding 6 'yellow circ1) (padding 6 circ1)))}
  19425. @image{images/padding-1}
  19426. @end example
  19427. This shows a circle drawn three ways:
  19428. as-is; with padding and a background color;
  19429. with padding and a transparent background.
  19430. A line is drawn before (below) the circles to contrast
  19431. the yellow vs transparent backgrounds.
  19432. @end deffn
  19433. @deffn Procedure re-center [xpos] [ypos] picture
  19434. Translate the @var{picture} such that the point specified by @var{xpos}
  19435. and @var{ypos} is the new origin point, adjusting the bounding box to match.
  19436. If the @var{picture} is a shape, so is the result.
  19437. The @var{xpos} can have four possible values, all of which are symbols:
  19438. @code{'left} (move the origin to the left edge of the bounding box);
  19439. @code{'right} (move the origin to the right edge of the bounding box);
  19440. @code{'center} (or @code{'centre}) (move the origin to halfway between the left and right edges);
  19441. or @code{'origin} (don't change the location along the x-axis).
  19442. The @var{ypos} can likewise have four possible values:
  19443. @code{'top} (move the origin to the top edge of the bounding box);
  19444. @code{'bottom} (move the origin to the bottom edge of the bounding box);
  19445. @code{'center} (or @code{'centre}) (move the origin to halfway between the
  19446. top and bottom edges);
  19447. or @code{'origin} (don't change the location along the y-axis).
  19448. A single @code{'center} argument
  19449. is the same as specifying @code{'center} for both axis; this is the default.
  19450. A single @code{'origin} argument
  19451. is the same as specifying @code{'origin} for both axis;
  19452. this is the same as just @var{picture}.
  19453. The 16 control points are shown below, relative to a picture's
  19454. bounding box and the X- and Y-axes.
  19455. The abbreviations have the obvious values, for example
  19456. @code{LC} means @code{'left 'center}.
  19457. @example
  19458. LT OT CT RT
  19459. ┌────┬──────────┐
  19460. │ │ │
  19461. │ │ │
  19462. LC│ OC C │RC
  19463. LO├────O──CO──────┤RO
  19464. │ │ │
  19465. └────┴──────────┘
  19466. LB OB CB RB
  19467. @end example
  19468. The result of (for example) @code{(re-center 'left 'center @var{P})}
  19469. is @var{P} translated so the origin is at control point @code{LC}.
  19470. @example
  19471. #|kawa:1|# @kbd{(define D (fill 'light-steel-blue (polygon &P[-20 0] &P[0 -20] &P[60 0] &P[0 40])))}
  19472. #|kawa:2|# @kbd{(zbox D (draw 'red (circle 5)))}
  19473. @image{images/re-center-1}
  19474. @end example
  19475. Above we defined @code{D} as a vaguely diamond-shaped quadrilateral.
  19476. A small red circle is added to show the origin point.
  19477. Below we display 5 versions of @code{D} in a line (an @code{hbox}),
  19478. starting with the original @code{D} and 4 calls to @code{re-center}.
  19479. @example
  19480. #|kawa:3|# @kbd{(zbox (hbox D (re-center 'top D) (re-center 'bottom D)}
  19481. #|....:4|# @kbd{ (re-center 'center D) (re-center 'origin D))}
  19482. #|....:5|# @kbd{ (line &P[0 0] &P[300 0]))}
  19483. @image{images/re-center-2}
  19484. @end example
  19485. The line at @var{y=0} shows the effects of @code{re-center}.
  19486. @end deffn
  19487. @subsection Images
  19488. An image is a picture represented as a rectangular grid of color values.
  19489. An image file is some encoding (usually compressed) of an image,
  19490. and mostly commonly has the extensions @code{png}, @code{gif},
  19491. or @code{jpg}/@code{jpeg}.
  19492. A ``native image'' is an instance of @code{java.awt.image.BufferedImage},
  19493. while a ``picture image'' is an instance of @code{gnu.kawa.models.DrawImage}.
  19494. (Both classes implement the @code{java.awt.image.RenderedImage} interface.)
  19495. A @code{BufferedImage} is automatically converted to a @code{DrawImage}
  19496. when needed.
  19497. @deffn Procedure image bimage
  19498. @deffnx Procedure image picture
  19499. @deffnx Procedure image src: path
  19500. Creates a picture image, using either an existing native image @var{bimage},
  19501. or an image file specified by @var{path}.
  19502. Writing @code{(image src: @var{path})} is roughly the same
  19503. as @code{(image (read-image @var{path}))} except that the former
  19504. has the @var{path} associated with the resulting picture image.
  19505. This can make a difference when the image is used or displayed.
  19506. If the argument is a @var{picture}, it is converted to an image
  19507. as if by @code{->image}.
  19508. @end deffn
  19509. @deffn Procedure image-read path
  19510. Read an image file from the specified @var{path},
  19511. and returns a native image object (a @code{BufferedImage}).
  19512. @example
  19513. #|kawa:10|# @kbd{(define img1 (image-read "http://pics.bothner.com/2013/Cats/06t.jpg"))}
  19514. #|kawa:11|# @kbd{img1}
  19515. @image{images/image-cat-1a}
  19516. #|kawa:12|# @kbd{(scale 0.6 (rotate 30 img1))}
  19517. @image{images/image-cat-1b}
  19518. @end example
  19519. @end deffn
  19520. Note that while @code{img1} above is a (native) image,
  19521. the scaled rotated image is not an image object.
  19522. It is a picture - a more complex value that @emph{contains} an image.
  19523. @deffn Procedure image-write picture path
  19524. The @var{picture} is converted to an image
  19525. (as if by using @code{->image}) and then it is written
  19526. to the specified @var{path}.
  19527. The format used depends on (the lower-cased string value of) the path:
  19528. A JPG file if the name ends with @code{".jpg"} or @code{".jpeg"};
  19529. a GIF file if the name ends with @code{".gif"};
  19530. a PNG file if the name ends with @code{".png"}.
  19531. (Otherwise, the defalt is PNG, but that might change.)
  19532. @end deffn
  19533. @deffn Procedure image-width image
  19534. @deffnx Procedure image-height image
  19535. Return the width or height of the given @var{image}, in pixels.
  19536. @end deffn
  19537. @deffn Procedure ->image picture
  19538. Convert @var{picture} to an image (a @code{RenderedImage}).
  19539. If the @var{picture} is an image, return as-is.
  19540. Otherwise, create an empty image (a @code{BufferedImage} whose size is the
  19541. @var{picture}'s bounding box), and ``paint'' the @var{picture} into it.
  19542. @example
  19543. #|kawa:1|# @kbd{(define c (fill (circle 10)))}
  19544. #|kawa:2|# @kbd{(scale 3 (hbox c (->image c)))}
  19545. @image{images/image-scaled-1}
  19546. @end example
  19547. Here we take a circle @code{c}, and convert it to an image.
  19548. Note how when the image is scaled, the pixel artifacts are very noticable.
  19549. Also note how the origin of the image is the top-level corner,
  19550. while the origin of the original circle is its center.
  19551. @end deffn
  19552. @subsection Compositing - Controlling how pictures are combined
  19553. @deffn Procedure with-composite [[compose-op] picture] ...
  19554. Limited support - SVG and DomTerm output has not been implemented.
  19555. @end deffn
  19556. @subsection Displaying and exporting pictures
  19557. @subsubsection Export to SVG
  19558. @deffn Procedure picture-write-svg picture path [headers]
  19559. Writes the @var{picture} to the file specified by @var{path},
  19560. in SVG (Structered Vector Graphics) format.
  19561. If @var{headers} is true (which is the default)
  19562. first write out the XML and DOCTYPE declarations
  19563. that should be in a well-formed standaline SVG file.
  19564. Otherwise, just write of the @code{<svg>} element.
  19565. (Modern browers should be able to display a file
  19566. consisting of just the @code{<svg>} element,
  19567. as long as it has extension @code{.svg}, @code{.xml}, or @code{.html};
  19568. the latter may add some extra padding.)
  19569. @end deffn
  19570. @deffn Procedure picture->svg-node picture
  19571. Returns a SVG representation of @code{picture},
  19572. in the form of an @code{<svg>} element,
  19573. similar to those discussed in @ref{Creating XML nodes}.
  19574. If you convert the @code{<svg>} element to a string,
  19575. you get formatted XML;
  19576. if you @code{write} the @code{<svg>} element
  19577. you get an @ref{XML literals,XML literal} of form @code{"#<svg>...</svg>"}.
  19578. If you @code{display} the @code{<svg>} element
  19579. in a DomTerm terminal you get the picture (as a picture).
  19580. This works because when you display an element in DomTerm
  19581. it gets inserted into the display.
  19582. @end deffn
  19583. @subsubsection Display in Swing
  19584. These procedures require @code{(import (kawa swing))} in addition to
  19585. @code{(import (kawa pictures))}.
  19586. The convenience function @code{show-picture} is useful
  19587. for displaying a picture in a new (Swing) window.
  19588. @deffn Procedure show-picture picture
  19589. If this is the first call to @code{show-pictures},
  19590. displays @var{picture} in a new top-level window (using the Swing toolkit).
  19591. Sequenent calls to @code{show-picture} will reuse the window.
  19592. @example
  19593. #|kawa:1|# @kbd{(import (kawa swing) (kawa pictures))}
  19594. #|kawa:2|# @kbd{(show-picture @var{some-picture})}
  19595. #|kawa:3|# @kbd{(set-frame-size! &D[200 200])} ; Adjust window size
  19596. #|kawa:4|# @kbd{(show-picture @var{some-other-picture})}
  19597. @end example
  19598. @end deffn
  19599. @deffn Procedure picture->jpanel picture
  19600. Return a @code{JPanel} that displays @var{picture}.
  19601. You can change the displayed picture by:
  19602. @example
  19603. (set! @var{panel}:picture @var{some-other-picture})
  19604. @end example
  19605. @end deffn
  19606. @deffn Procedure set-frame-size! size [frame]
  19607. If @var{frame} is specified, set its size.
  19608. Otherwise, remember the size for future @code{show-picture} calls;
  19609. if there is already a @code{show-picture} window, adjust its size.
  19610. @end deffn
  19611. @subsubsection Convert to image
  19612. You can convert a picture to an image using the @code{->image} procedure,
  19613. or write it to a file using the @code{image-write} procedure.
  19614. @node Building JavaFX applications
  19615. @section Building JavaFX applications
  19616. @cindex JavaFX
  19617. Kawa makes it easy to build ``rich client'' (i.e. GUI) applications using
  19618. @uref{http://www.oracle.com/technetwork/java/javafx/overview/index.html,JavaFX}.
  19619. For example the following program will print up a window with a button;
  19620. clicking on the button will print a message on the console output about the
  19621. event.
  19622. @example
  19623. (require 'javafx-defs)
  19624. (javafx-application)
  19625. (javafx-scene
  19626. title: "Hello Button"
  19627. width: 600 height: 450
  19628. (Button
  19629. text: "Click Me"
  19630. layout-x: 25
  19631. layout-y: 40
  19632. on-action: (lambda (e) (format #t "Event: ~s~%~!" e))))
  19633. @end example
  19634. JavaFX support is builtin to the pre-built @code{kawa-@value{VERSION}.jar}.
  19635. It is easiest to use JDK 8; see below if you're using JDK 7.
  19636. If you build Kawa from source, specify @code{--with-javafx} on the
  19637. @code{configure} command line (assuming you're using JDK 8).
  19638. Assume the above file is @code{HelloButton1.scm}, you can
  19639. run it like this:
  19640. @example
  19641. $ kawa HelloButton1.scm
  19642. @end example
  19643. For more information and examples read this (slightly older)
  19644. @uref{http://per.bothner.com/blog/2011/JavaFX-using-Kawa-intro/,introduction},
  19645. and
  19646. @uref{http://localhost/per/blog/2011/JavaFX-using-Kawa-animation/,this on animation}.
  19647. The @code{browse-kawa-manual} script in the @code{doc} directory (source only)
  19648. uses JavaFX WebView to create a window for browsing the Kawa documentation.
  19649. @subsection Using JavaFX with JDK 7
  19650. JDK 8 ships with JavaFX, and it is in the default @code{CLASSPATH}.
  19651. JDK 7 update 9 or later does have JavaFX included, but it is a separate
  19652. @code{jfxrt.jar} which not in the default @code{CLASSPATH}.
  19653. Thus you have to explicitly add @code{jfxrt.jar}.
  19654. To run the previous @code{HelloButton1.scm} you can do:
  19655. @example
  19656. java -cp $JAVA_HOME/lib/jfxrt.jar:$KAWA_HOME/kawa.jar HelloButton1.scm
  19657. @end example
  19658. If you build Kawa from source, do:
  19659. @example
  19660. $ ./configure --with-javafx=$JAVA_HOME --enable-kawa-frontend ...other-args...
  19661. @end example
  19662. The resulting Kawa binary sets up the path to @code{jfxrt.jar} so you just need to do:
  19663. @example
  19664. $ kawa HelloButton1.scm
  19665. @end example
  19666. @node Building for Android
  19667. @section Building for Android
  19668. Google's phone/tablet operating system
  19669. @uref{https://developers.google.com/android/,Android}
  19670. is based on a custom virtual machine on top of a Linux kernel.
  19671. Even though Android isn't strictly (or legally) speaking Java,
  19672. you can build Android applications using Kawa.
  19673. Below is "Hello world" written in Kawa Scheme. A slightly
  19674. more interesting example is in @ref{Android view construction,next section}.
  19675. @example
  19676. (require 'android-defs)
  19677. (activity hello
  19678. (on-create-view
  19679. (android.widget.TextView (this)
  19680. text: "Hello, Android from Kawa Scheme!")))
  19681. @end example
  19682. The following instructions have been tested on GNU/Linux,
  19683. specifically Fedora 17.
  19684. @uref{http://asieno.com/blog/index.php/post/2012/08/16/Setting-up-the-environment-Android-Kawa,This link} may be helpful if you're building on Windows.
  19685. @subsection Downloading and setting up the Android SDK
  19686. First @uref{http://code.google.com/android/download.html,download the Android SDK}. Unzip in a suitable location, which we'll refer to as @code{ANDROID_HOME}.
  19687. @example
  19688. export ANDROID_HOME=/path/to/android-sdk-linux
  19689. PATH=$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$PATH
  19690. @end example
  19691. Next you have to get the appropriate platform SDK:
  19692. @example
  19693. $ android update sdk
  19694. @end example
  19695. You need to select an Android ``platform''.
  19696. Platform (API) 16 corresponds to Android 4.1.2 (Jelly Bean).
  19697. Select that or whatever you prefer, and click @code{Install}.
  19698. (You can install multiple platforms, but each project
  19699. is built for a specific platform.)
  19700. @example
  19701. ANDROID_PLATFORM=android-16
  19702. @end example
  19703. @subsection Building Kawa for Android
  19704. Set @code{JAVA_HOME} to where your JDK tree is.
  19705. You should use JDK 6; JDK 7 does not work at time of writing.
  19706. @example
  19707. $ export JAVA_HOME=/opt/jdk1.6
  19708. @end example
  19709. First @ref{Getting Kawa,get the Kawa source code}.
  19710. If using Ant (as is recommended on Windows):
  19711. @example
  19712. $ ant -Denable-android=true
  19713. @end example
  19714. Alternatively, you can use @code{configure} and @code{make}:
  19715. @example
  19716. $ KAWA_DIR=path_to_Kawa_sources
  19717. $ cd $KAWA_DIR
  19718. $ ./configure --with-android=$ANDROID_HOME/platforms/$ANDROID_PLATFORM/android.jar --disable-xquery --disable-jemacs
  19719. $ make
  19720. @end example
  19721. @subsection Creating the application
  19722. Next, we need to create a project or ``activity''.
  19723. This tutorial assumes you want to create the project
  19724. in the target directory @code{KawaHello},
  19725. with the main activity being a class named @code{hello} in a
  19726. package @code{kawa.android}:
  19727. @example
  19728. PROJECT_DIR=KawaHello
  19729. PROJECT_CLASS=hello
  19730. PROJECT_PACKAGE=kawa.android
  19731. PROJECT_PACKAGE_PATH=kawa/android
  19732. @end example
  19733. To create the project use the following command:
  19734. @example
  19735. $ android create project --target $ANDROID_PLATFORM --name $PROJECT_DIR --activity $PROJECT_CLASS --path ./$PROJECT_DIR --package $PROJECT_PACKAGE
  19736. @end example
  19737. Replace the skeleton @code{hello.java} by the Scheme code at the
  19738. top of this note, placing in a file named @code{hello.scm}:
  19739. @example
  19740. $ cd $PROJECT_DIR
  19741. $ HELLO_APP_DIR=`pwd`
  19742. $ cd $HELLO_APP_DIR/src/$PROJECT_PACKAGE_PATH
  19743. $ rm $PROJECT_CLASS.java
  19744. $ @i{create} $PROJECT_CLASS.scm
  19745. @end example
  19746. We need to copy/link the Kawa jar file so the Android SDK can find it:
  19747. @example
  19748. $ cd $HELLO_APP_DIR
  19749. $ ln -s $KAWA_DIR/kawa-@value{VERSION}.jar libs/kawa.jar
  19750. @end example
  19751. Optionally, you can use kawart-@value{VERSION}.jar, which is slightly smaller,
  19752. but does not support eval, and does not get built by the Ant build:
  19753. @example
  19754. $ ln -s $KAWA_DIR/kawart-@value{VERSION}.jar libs/kawa.jar
  19755. @end example
  19756. Copy or link @code{custom_rules.xml} from the Kawa sources:
  19757. @example
  19758. ln -s $KAWA_DIR/gnu/kawa/android/custom_rules.xml .
  19759. @end example
  19760. Finally to build the application just do:
  19761. @example
  19762. $ ant debug
  19763. @end example
  19764. @subsection Running the application on the Android emulator
  19765. First you need to create an @uref{http://developer.android.com/tools/devices,Android Virtual Device (avd)}. Start:
  19766. @example
  19767. android
  19768. @end example
  19769. Then from menu @code{Tools} select @code{Manage AVDs...}.
  19770. In the new window click @code{New....}
  19771. Pick a @code{Name} (we use @code{avd16} in the following),
  19772. a @code{Target} (to match @code{$ANDROID_PLATFORM}),
  19773. and optionally change the other properties, before clicking @code{Create AVD}.
  19774. Now you can start up the Android emulator:
  19775. @example
  19776. $ emulator -avd avd16 &
  19777. @end example
  19778. Wait until Android has finished booting (you will see the Android home screen),
  19779. click the menu and home buttons. Now install our new application:
  19780. @example
  19781. adb install bin/KawaHello-debug.apk
  19782. @end example
  19783. @subsection Running the application on your device
  19784. If the emulator is running, kill it:
  19785. @example
  19786. $ kill %emulator
  19787. @end example
  19788. On your phone or other Android devude, enable USB debugging.
  19789. (This is settable from the @code{Settings} application,
  19790. under @code{Applications / Development}.)
  19791. Connect the phone to your computer with the USB cable.
  19792. Verify that the phone is accessible to @code{adb}:
  19793. @example
  19794. $ adb devices
  19795. List of devices attached
  19796. 0A3A560F0C015024 device
  19797. @end example
  19798. If you don't see a device listed, it may be permission problem. You can figure out which device corresponds to the phone by doing:
  19799. @example
  19800. $ ls -l /dev/bus/usb/*
  19801. /dev/bus/usb/001:
  19802. total 0
  19803. ...
  19804. crw-rw-rw- 1 root wheel 189, 5 2010-10-18 16:52 006
  19805. ...
  19806. @end example
  19807. The timestamp corresponds to when you connected the phone.
  19808. Make the USB connection readable:
  19809. @example
  19810. $ sudo chmod a+w /dev/bus/usb/001/006
  19811. @end example
  19812. Obviously if you spend time developing for an Androd phone you'll want to automate this process;
  19813. @uref{https://sites.google.com/site/siteofhx/Home/android/drivers/udc,this link}
  19814. or @uref{https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nTfhhPktGfM,this link} may be helpful.
  19815. Anyway, once @code{adb} can talk to the phone, you install in the same way as before:
  19816. @example
  19817. adb install bin/KawaHello-debug.apk
  19818. @end example
  19819. @subsection Some debugging notes
  19820. You will find a copy of the SDK documentation in @code{$ANDROID_HOME/docs/index.html}.
  19821. If the emulator complains that your application has stopped unexpectedly, do:
  19822. @example
  19823. $ adb logcat
  19824. @end example
  19825. This shows log messages, stack traces, output from the @code{Log.i} logging method, and other useful information.
  19826. (You can alternatively start @code{ddms} (Dalvik Debug Monitor Service), click on the @code{kawa.android line} in the top-left sub-window to select it, then from the @code{Device} menu select @code{Run logcat....}).
  19827. To uninstall your application, do:
  19828. @example
  19829. $ adb uninstall kawa.android
  19830. @end example
  19831. @subsection Other resources
  19832. (A more interesting @uref{http://androidscheme.blogspot.com/2010/10/text-to-speech-app.html,text-to-speech} example app is on Santosh Rajan's @uref{http://androidscheme.blogspot.com/,Android-Scheme blog}.)
  19833. @uref{https://github.com/ecraven/SchemeAndroidOGL}
  19834. @node Android view construction
  19835. @section Android view construction
  19836. An Android user interface is constructed from @code{View} objects.
  19837. The following is an example that illustrates some features of
  19838. Kawa to help write views hierarchies,
  19839. The example is self-contained, and can be built and run
  19840. as described in @ref{Building for Android}.
  19841. @example
  19842. (require 'android-defs)
  19843. (activity hello
  19844. (on-create-view
  19845. (define counter ::integer 0)
  19846. (define counter-view
  19847. (TextView text: "Not clicked yet."))
  19848. (LinearLayout orientation: LinearLayout:VERTICAL
  19849. (TextView text: "Hello, Android from Kawa Scheme!")
  19850. (Button
  19851. text: "Click here!"
  19852. on-click-listener: (lambda (e)
  19853. (set! counter (+ counter 1))
  19854. (counter-view:setText
  19855. (format "Clicked ~d times." counter))))
  19856. counter-view)))
  19857. @end example
  19858. The first @code{import} form imports various useful definitions
  19859. from the Kawa Android library. Using these is not required for
  19860. writing a Kawa application, but makes it more convenient.
  19861. The names @code{LinearLayout}, @code{TextView}, and @code{Button}
  19862. are just aliases for standard Android @code{View} sub-classes.
  19863. A few are prefined by @code{(require 'android-defs)}, or you
  19864. can define them yourself using @code{define-alias}.
  19865. An Android application consists of one or more @dfn{activities},
  19866. each of which is an instance of the @code{android.app.Activity} class.
  19867. You can use the @code{activity} macro to define your @code{Activity} class.
  19868. The first macro argument (in this case @code{hello}) is the class name,
  19869. and the others are members of the class, in the syntax of
  19870. a @stxref{field-or-method-decl}. The sub-form @code{on-create-view}
  19871. is an abbreviation for declaring an @code{onCreate} method
  19872. (which is called when the @code{Activity} starts up
  19873. @c LOOK THIS UP - also when re-started?
  19874. followed by a @code{setContentView}:
  19875. The body of the @code{on-create-view} is evaluated.
  19876. The result should be a @code{View} expression,
  19877. which is passed to @code{setContentView}.
  19878. @deffn Procedure current-activity [new-value]
  19879. With no arguments, returns the current @code{Activity}.
  19880. If a @var{new-value} argument is given, sets the current activity.
  19881. It is set automatically by the @code{on-create} and @code{on-create-view}
  19882. methods of the @code{activity} macro.
  19883. Since @code{current-activity} is a @ref{Parameter objects,parameter object},
  19884. you can
  19885. locally change the value using @ref{parameterize-syntax,@code{parameterize}}.
  19886. @end deffn
  19887. @subsection View object allocation
  19888. To create an instance of a @code{View} class you ``call'' the
  19889. class as if it were a function,
  19890. as described in @ref{Allocating objects}.
  19891. For example:
  19892. @example
  19893. (TextView (this) text: "Hello, Android from Kawa Scheme!")
  19894. @end example
  19895. If you @code{(require 'android-defs)} that defines
  19896. some special handling for @code{View} classes.
  19897. You can leave out the @code{(this)} argument,
  19898. which refers to the enclosing @code{Activity}:
  19899. @example
  19900. (TextView text: "Hello, Android from Kawa Scheme!")
  19901. @end example
  19902. @subsection Event handlers
  19903. You can register event listeners on Android @code{View} objects
  19904. using methods typically named @code{setOn@var{EVENT}Listener}.
  19905. For example @code{setOnClickListener}. When allocating
  19906. an object you can leave out the @code{set}, and you can optionally
  19907. use Scheme-style names: @code{on-click-listener}. The argument
  19908. is an object of a special nested listener class,
  19909. for example @code{View$OnClickListener}. These are
  19910. single-method classes, so you can use a lambda expression
  19911. and @ref{SAM-conversion} will automatically create the needed
  19912. listener class.
  19913. @node System inquiry
  19914. @section System inquiry
  19915. @defvar home-directory
  19916. A string containing the home directory of the user.
  19917. @end defvar
  19918. @deffn Procedure command-line
  19919. Returns a nonempty list of immutable strings. The first element is
  19920. an implementation-specific name for the running top-level
  19921. program.
  19922. The remaining elements are the command-line arguments,
  19923. as passed to the @code{main} method (except for those
  19924. flags processed by Kawa itself).
  19925. The first element will depend on how the Kawa module was invoked.
  19926. Kawa uses the following rules to determine the command name:
  19927. @enumerate
  19928. @item
  19929. If the property @code{kawa.command.name} is set, that is used.
  19930. This variable can be set on the @code{kawa} command line,
  19931. for example from a script:
  19932. @example
  19933. kawa -Dkawa.command.name="$0" foo "$@@"
  19934. @end example
  19935. This variable is also set implicitly by the meta-arg option. FIXME.
  19936. @item
  19937. If we're reading a source file that starts with the Unix command-file prefix
  19938. @samp{#!/} then we use the name of the source file.
  19939. The assumption is that such a file is an executable script.
  19940. @item
  19941. If the Java property @code{kawa.command.line} is set,
  19942. then we use that (after stripping off text that duplicates
  19943. the remaining arguments).
  19944. The @code{kawa} program sets this property to the
  19945. command line used to invoke it
  19946. (specifically the contents of the entire @code{argv} array),
  19947. before invoking the @code{java} program.
  19948. @item
  19949. If the Java property @code{sun.java.command} is set,
  19950. then we use that (after stripping off text that duplicates
  19951. the remaining arguments), and then prepending the string @code{"java "}.
  19952. The OpenJDK @code{java} program sets this property.
  19953. @item
  19954. If all else fails, the command name is @code{"kawa"}.
  19955. @end enumerate
  19956. @end deffn
  19957. @defvar command-line-arguments
  19958. Any command-line arguments (following flags processed by Kawa itself)
  19959. are assigned to the global variable @samp{command-line-arguments},
  19960. which is a vector of strings.
  19961. @end defvar
  19962. @deffn Procedure process-command-line-assignments
  19963. Process any initial command-line options that set variables.
  19964. These have the form @code{@var{name}=@var{value}}.
  19965. Any such command-line options (at the start of the command-line)
  19966. are processed and removed from the command-line.
  19967. @example
  19968. $ java kawa.repl -- abc=123 def
  19969. #|kawa:1|# (write (command-line))
  19970. ("java kawa.repl --" "abc=123" "def")
  19971. #|kawa:2|# (process-command-line-assignments)
  19972. #|kawa:3|# (write (command-line))
  19973. ("java kawa.repl -- abc=123" "def")
  19974. #|kawa:4|# abc
  19975. 123
  19976. @end example
  19977. This function is mostly useful for Kawa applications
  19978. compiled with the @code{--main} option.
  19979. (It is used to set XQuery @code{external} variables.)
  19980. @end deffn
  19981. @deffn Procedure get-environment-variable name
  19982. Many operating systems provide each running process with
  19983. an environment conisting of environment variables.
  19984. (This environment is not to be confused with the
  19985. Scheme environments that can be passed to @code{eval}.)
  19986. Both the name and value of an environment variable are
  19987. strings. The procedure @code{get-environment-variable}
  19988. returns the value of the environment variable @var{name},
  19989. or @code{#f} if the environment variable is not found.
  19990. @c It may use locale information to encode the name and
  19991. @c decode the value of the environment variable.
  19992. (This uses the @code{java.lang.System:getenv} method.)
  19993. It is an error to mutate the resulting string.
  19994. @example
  19995. (get-environment-variable "PATH")
  19996. @result{} "/usr/local/bin:/usr/bin:/bin"
  19997. @end example
  19998. @end deffn
  19999. @deffn Procedure get-environment-variables
  20000. Returns the names and values of all the environment variables as an alist,
  20001. where the car of each entry is the name of an environment variable,
  20002. and the cdr is its value, both as strings.
  20003. It is an error to mutate any of the strings or the alist itself.
  20004. @example
  20005. (get-environment-variables)
  20006. @result{} (("USER" . "root") ("HOME" . "/"))
  20007. @end example
  20008. @end deffn
  20009. @node Processes
  20010. @section Processes
  20011. A @dfn{process} is a native (operating-system-level) application or
  20012. program that runs separately from the current virtual machine.
  20013. Many programming languages have facilities to allow access to system
  20014. processes (commands). (For example Java has @code{java.lang.Process}
  20015. and @code{java.lang.ProcessBuilder}.)
  20016. These facilities let you send data to the standard input, extract the
  20017. resulting output, look at the return code, and sometimes even pipe
  20018. commands together. However, this is rarely as easy as it is using
  20019. the old Bourne shell; for example command substitution is awkward.
  20020. Kawa's solution is based on these two ideas:
  20021. @itemize
  20022. @item
  20023. A ``process expression'' (typically a function call) evaluates to a
  20024. @code{LProcess} value, which provides access to a Unix-style
  20025. (or Windows) process.
  20026. @item
  20027. In a context requiring a string (or a bytevector), an @code{LProcess} is
  20028. automatically converted to a string (or bytevector)
  20029. comprising the standard output from the process.
  20030. @end itemize
  20031. @subsection Creating a process
  20032. The most flexible way to start a process is with either the
  20033. @code{run-process} procedure or
  20034. the @code{&`@lbracechar{}@meta{command}@rbracechar{}} syntax
  20035. for @ref{process literals}.
  20036. @deffn Procedure run-process @arbno{@stxref{process-keyword-argument}} @meta{command}
  20037. Creates a process object, specifically a @code{gnu.kawa.functions.LProcess}
  20038. object.
  20039. A @var{process-keyword-argument} can be used to set various options,
  20040. as discussed below.
  20041. The @var{command} is the process command-line (name and arguments).
  20042. It can be an array of strings, in which case those are used as the
  20043. command arguments directly:
  20044. @example
  20045. (run-process ["ls" "-l"])
  20046. @end example
  20047. The @var{command} can also be a single string, which is split (tokenized)
  20048. into command arguments separated by whitespace.
  20049. Quotation groups words together just like traditional shells:
  20050. @example
  20051. (run-process "cmd a\"b 'c\"d k'l m\"n'o")
  20052. @result{} (run-process ["cmd" "ab 'cd" "k'l m\"no"])
  20053. @end example
  20054. The syntax shorthand @code{&`@lbracechar{}@meta{command}@rbracechar{}}
  20055. or @code{&sh@lbracechar{}@meta{command}@rbracechar{}} (discussed below)
  20056. is usually more convenient.
  20057. @end deffn
  20058. @display
  20059. @stxdef{process-keyword-argument}
  20060. @stxref{process-redirect-argument}
  20061. | @stxref{process-environment-argument}
  20062. | @stxref{process-misc-argument}
  20063. @end display
  20064. We discuss @stxref{process-redirect-argument} and
  20065. @stxref{process-environment-argument} later.
  20066. @anchor{meta-process-misc-argument}
  20067. The @var{process-misc-argument} options are just the following:
  20068. @table @asis
  20069. @item @stxlit{shell:} @var{shell}
  20070. Currently, @var{shell} must be one of @code{#f} (which is ignored)
  20071. or @code{#t}. The latter means to use an external shell to tokenize
  20072. the @var{command}.
  20073. I.e. the following are equivalent:
  20074. @example
  20075. (run-process shell: #t "@var{command}")
  20076. (run-process ["/bin/sh" "-c" "@var{command}"])
  20077. @end example
  20078. @item @stxlit{directory:} @var{dir}
  20079. Change the working directory of the new process to @var{dir}.
  20080. @end table
  20081. @anchor{process literals}
  20082. @subsection Process literals
  20083. A simple @dfn{process literal} is a kind of
  20084. @ref{Named quasi-literals,named literal} that uses the backtick character
  20085. (@code{`}) as the @stxref{cname}.
  20086. For example:
  20087. @example
  20088. &`@lbracechar{}date --utc@rbracechar{}
  20089. @end example
  20090. This is equivalent to:
  20091. @example
  20092. (run-process "date --utc")
  20093. @end example
  20094. In general the following are
  20095. roughly equivalent (using @ref{string quasi-literals}):
  20096. @example
  20097. &`[@var{args}...]@lbracechar{}@var{command}@rbracechar{}
  20098. (run-process @var{args}... &@lbracechar{}@var{command}@rbracechar{})
  20099. @end example
  20100. The reason for the ``roughly'' is if @var{command} contains
  20101. escaped sub-expressions; in that case @code{&`} may process
  20102. the resulting values differently from plain string-substitution,
  20103. as discussed below.
  20104. If you use @code{&sh} instead of @code{&`} then a shell is used:
  20105. @example
  20106. &sh@lbracechar{}rm *.class@rbracechar{}
  20107. @end example
  20108. which is equivalent to:
  20109. @example
  20110. &`@lbracechar{}/bin/sh -c "rm *.class"@rbracechar{}
  20111. @end example
  20112. In general, the following are equivalent:
  20113. @example
  20114. &sh[@var{args}...]@lbracechar{}@var{command}@rbracechar{}
  20115. &`[shell: #t @var{args}...]@lbracechar{}@var{command}@rbracechar{}
  20116. @end example
  20117. @subsection Process values and process output
  20118. The value returned from a call to @code{run-process} or a process literal
  20119. is an instance of @code{gnu.kawa.functions.LProcess}.
  20120. This class extends @code{java.lang.Process}, so you can treat it as
  20121. any other @code{Process} object.
  20122. @example
  20123. #|kawa:1|# (define p1 &`@lbracechar{}date --utc@rbracechar{})
  20124. #|kawa:2|# (p1:toString)
  20125. gnu.kawa.functions.LProcess@@377dca04
  20126. #|kawa:3|# (write p1)
  20127. gnu.kawa.functions.LProcess@@377dca04
  20128. @end example
  20129. What makes an @code{LProcess} interesting is that it is also
  20130. a @ref{Blobs,blob}, which is automatically
  20131. converted to a string (or bytevector) in a context that requires it.
  20132. The contents of the blob comes from the standard output of the process.
  20133. The blob is evaluated @ref{Lazy evaluation,lazily},
  20134. so data it is only collected when requested.
  20135. @example
  20136. #|kawa:4|# (define s1 ::string p1)
  20137. #|kawa:5|# (write s1)
  20138. "Wed Jan 1 01:18:21 UTC 2014\n"
  20139. #|kawa:6|# (define b1 ::bytevector p1)
  20140. (write b1)
  20141. #u8(87 101 100 32 74 97 110 ... 52 10)
  20142. @end example
  20143. The @code{display} procedure prints it in ``human'' form, as a string:
  20144. @example
  20145. #|kawa:7|# (display p1)
  20146. Wed Jan 1 01:18:21 UTC 2014
  20147. @end example
  20148. This is also the default REPL formatting:
  20149. @example
  20150. #|kawa:8|# &`@lbracechar{}date --utc@rbracechar{}
  20151. Wed Jan 1 01:18:22 UTC 2014
  20152. @end example
  20153. When you type a command to a shell, its output goes to the console,
  20154. Similarly, in a REPL the output from the process
  20155. is copied to the console output - which can sometimes by optimized
  20156. by letting the process inherit its standard output from the Kawa process.
  20157. @subsection Substitution and tokenization
  20158. To substitute the variable or the result of an expression
  20159. in the command line use the usual syntax for quasi literals:
  20160. @example
  20161. (define filename (make-temporary-file))
  20162. &sh@lbracechar{}run-experiment >&[filename]@rbracechar{}
  20163. @end example
  20164. Since a process is convertible a string, we need no special
  20165. syntax for command substitution:
  20166. @example
  20167. `@lbracechar{}echo The directory is: &[&`@lbracechar{}pwd@rbracechar{}]@rbracechar{}
  20168. @end example
  20169. or equivalently:
  20170. @example
  20171. `@lbracechar{}echo The directory is: &`@lbracechar{}pwd@rbracechar{}@rbracechar{}
  20172. @end example
  20173. @anchor{substitution-tokenization}
  20174. Things get more interesting when considering the interaction between
  20175. substitution and tokenization. This is not simple string
  20176. interpolation. For example, if an interpolated value contains a quote
  20177. character, we want to treat it as a literal quote, rather than a token
  20178. delimiter. This matches the behavior of traditional shells. There are
  20179. multiple cases, depending on whether the interpolation result is a
  20180. string or a vector/list, and depending on whether the interpolation is
  20181. inside quotes.
  20182. @itemize
  20183. @item
  20184. If the value is a string, and we're not inside quotes, then all
  20185. non-whitespace characters (including quotes) are literal, but
  20186. whitespace still separates tokens:
  20187. @example
  20188. (define v1 "a b'c ")
  20189. &`@lbracechar{}cmd x y&[v1]z@rbracechar{} @result{} (run-process ["cmd" "x" "ya" "b'c" "z"])
  20190. @end example
  20191. @item
  20192. If the value is a string, and we are inside single quotes,
  20193. all characters (including whitespace) are literal.
  20194. @example
  20195. &`@lbracechar{}cmd 'x y&[v1]z'@rbracechar{} @result{} (run-process ["cmd" "x ya b'c z"])
  20196. @end example
  20197. Double quotes work the same except that newline is an argument
  20198. separator. This is useful when you have one filename per line, and the
  20199. filenames may contain spaces, as in the output from @code{find}:
  20200. @example
  20201. &`@lbracechar{}ls -l "&`@lbracechar{}find . -name '*.pdf'@rbracechar{}"@rbracechar{}
  20202. @end example
  20203. This solves a problem that is quite painful with traditional shells.
  20204. @item
  20205. If the value is a vector or list (of strings), and we're not inside
  20206. quotes, then each element of the array becomes its own argument, as-is:
  20207. @example
  20208. (define v2 ["a b" "c\"d"])
  20209. &`@lbracechar{}cmd &[v2]@rbracechar{} @result{} (run-process ["cmd" "a b" "c\"d"])
  20210. @end example
  20211. However, if the enclosed expression is adjacent to non-space non-quote
  20212. characters, those are prepended to the first element, or appended to
  20213. the last element, respectively.
  20214. @example
  20215. &`@lbracechar{}cmd x&[v2]y@rbracechar{} @result{} (run-process ["cmd" "xa b" "c\"dy"])
  20216. &`@lbracechar{}cmd x&[[]]y@rbracechar{} @result{} (run-process ["cmd" "xy"])
  20217. @end example
  20218. This behavior is similar to how shells handle @code{"$@@"}
  20219. (or @code{"$@lbracechar{}name[@@]@rbracechar{}"} for general arrays), though in Kawa you would
  20220. leave off the quotes.
  20221. Note the equivalence:
  20222. @example
  20223. &`@lbracechar{}&[array]@rbracechar{} @result{} (run-process array)
  20224. @end example
  20225. @item
  20226. If the value is a vector or list (of strings), and we @emph{are}
  20227. inside quotes, it is equivalent to interpolating a single string
  20228. resulting from concatenating the elements separated by a space:
  20229. @example
  20230. &`@lbracechar{}cmd "&[v2]"@rbracechar{}
  20231. @result{} (run-process ["cmd" "a b c\"d"])
  20232. @end example
  20233. This behavior is similar to how shells handle @code{"$*"} (or
  20234. @code{"$@lbracechar{}name[*]@rbracechar{}"} for general arrays).
  20235. @item
  20236. If the value is the result of a call to @code{unescaped-data} then it
  20237. is parsed as if it were literal. For example a quote in the unescaped
  20238. data may match a quote in the literal:
  20239. @example
  20240. (define vu (unescaped-data "b ' c d '"))
  20241. &`@lbracechar{}cmd 'a &[vu]z'@rbracechar{} @result{} (run-process ["cmd" "a b " "c" "d" "z"])
  20242. @end example
  20243. @item
  20244. If we're using a shell to tokenize the command, then we add quotes or
  20245. backslashes as needed so that the shell will tokenize as described
  20246. above:
  20247. @example
  20248. (define authors ["O'Conner" "de Beauvoir"])
  20249. &sh@lbracechar{}list-books &[authors]@rbracechar{}
  20250. @end example
  20251. The command passed to the shell is:
  20252. @example
  20253. list-books 'O'\''Conner' 'de Beauvoir
  20254. @end example
  20255. Having quoting be handled by the @code{$construct$:sh}
  20256. implementation automatically eliminates common code injection problems.
  20257. @end itemize
  20258. Smart tokenization only happens when using the quasi-literal forms such
  20259. as @code{&`@lbracechar{}command@rbracechar{}}.
  20260. You can of course use string templates with @code{run-process}:
  20261. @example
  20262. (run-process &@lbracechar{}echo The directory is: &`@lbracechar{}pwd@rbracechar{}@rbracechar{})
  20263. @end example
  20264. However, in that case there is no smart tokenization: The template is
  20265. evaluated to a string, and then the resulting string is tokenized,
  20266. with no knowledge of where expressions were substituted.
  20267. @subsection Input/output redirection
  20268. You can use various keyword arguments to specify standard input, output,
  20269. and error streams. For example to lower-case the text in @code{in.txt},
  20270. writing the result to @code{out.txt}, you can do:
  20271. @example
  20272. &`[in-from: "in.txt" out-to: "out.txt"]@lbracechar{}tr A-Z a-z@rbracechar{}
  20273. @end example
  20274. or:
  20275. @example
  20276. (run-process in-from: "in.txt" out-to: "out.txt" "tr A-Z a-z")
  20277. @end example
  20278. @anchor{meta-process-redirect-argument}
  20279. A @var{process-redirect-argument} can be one of the following:
  20280. @table @asis
  20281. @item @stxlit{in:} @var{value}
  20282. The @var{value} is evaluated, converted to a string (as if
  20283. using @code{display}), and copied to the input file of the process.
  20284. The following are equivalent:
  20285. @example
  20286. &`[in: "text\n"]@lbracechar{}command@rbracechar{}
  20287. &`[in: &`@lbracechar{}echo "text"@rbracechar{}]@lbracechar{}command@rbracechar{}
  20288. @end example
  20289. You can pipe the output from @code{command1} to the input
  20290. of @code{command2} as follows:
  20291. @example
  20292. &`[in: &`@lbracechar{}command1@rbracechar{}]@lbracechar{}command2@rbracechar{}
  20293. @end example
  20294. @item @stxlit{in-from:} @var{path}
  20295. The process reads its input from the specified @var{path}, which
  20296. can be any value coercible to a @code{filepath}.
  20297. @item @stxlit{out-to:} @var{path}
  20298. The process writes its output to the specified @var{path}.
  20299. @item @stxlit{err-to:} @var{path}
  20300. Similarly for the error stream.
  20301. @item @stxlit{out-append-to:} @var{path}
  20302. @item @stxlit{err-append-to:} @var{path}
  20303. Similar to @code{out-to} and @code{err-to}, but append to the file
  20304. specified by @var{path}, instead of replacing it.
  20305. @item @stxlit{in-from: 'pipe}
  20306. @item @stxlit{out-to: 'pipe}
  20307. @item @stxlit{err-to: 'pipe}
  20308. Does not set up redirection. Instead, the specified stream is available
  20309. using the methods @code{getOutputStream}, @code{getInputStream},
  20310. or @code{getErrorStream}, respectively, on the resulting @code{Process} object,
  20311. just like Java's @code{ProcessBuilder.Redirect.PIPE}.
  20312. @item @stxlit{in-from: 'inherit}
  20313. @item @stxlit{out-to: 'inherit}
  20314. @item @stxlit{err-to: 'inherit}
  20315. Inherits the standard input, output, or error stream from the
  20316. current JVM process.
  20317. @item @stxlit{out-to:} @var{port}
  20318. @item @stxlit{err-to:} @var{port}
  20319. Redirects the standard output or error of the process to
  20320. the specified @var{port}.
  20321. @item @stxlit{out-to: 'current}
  20322. @item @stxlit{err-to: 'current}
  20323. Same as @code{out-to: (current-output-port)},
  20324. or @code{err-to: (current-error-port)}, respectively.
  20325. @item @stxlit{in-from:} @var{port}
  20326. @item @stxlit{in-from: 'current}
  20327. Re-directs standard input to read from the @var{port}
  20328. (or @code{(current-input-port)}). It is unspecified how much is read from
  20329. the @var{port}. (The implementation is to use a thread that reads from the
  20330. port, and sends it to the process, so it might read to the end of the port,
  20331. even if the process doesn't read it all.)
  20332. @item @stxlit{err-to: 'out}
  20333. Redirect the standard error of the process to be merged with the
  20334. standard output.
  20335. @end table
  20336. The default for the error stream (if neither @code{err-to} or
  20337. @code{err-append-to} is specified) is equivalent to @code{err-to: 'current}.
  20338. @emph{Note:} Writing to a port is implemented by copying the output or error
  20339. stream of the process. This is done in a thread, which means we don't have
  20340. any guarantees when the copying is finished. (In the future we might
  20341. change @code{process-exit-wait} (discussed later) wait for not only the
  20342. process to finish, but also for these helper threads to finish.)
  20343. A @uref{https://en.wikipedia.org/wiki/Here_document,here document} is
  20344. a form a literal string, typically multi-line, and commonly used in
  20345. shells for the standard input of a process. You can use string literals or
  20346. @ref{string quasi-literals} for this.
  20347. For example, this passes the string @code{"line1\nline2\nline3\n"} to
  20348. the standard input of @code{command}:
  20349. @example
  20350. (run-process [in: &@lbracechar{}
  20351. &|line1
  20352. &|line2
  20353. &|line3
  20354. @rbracechar{}] "command")
  20355. @end example
  20356. Note the use of @code{&|} to mark the end of ignored indentation.
  20357. @subsection Pipe-lines
  20358. Piping the output of one process as the input of another
  20359. is in principle easy - just use the @code{in:}
  20360. process argument. However, writing a multi-stage pipe-line quickly gets ugly:
  20361. @example
  20362. &`[in: &`[in: "My text\n"]@lbracechar{}tr a-z A-Z@rbracechar{}]@lbracechar{}wc@rbracechar{}
  20363. @end example
  20364. The convenience macro @code{pipe-process} makes this much nicer:
  20365. @example
  20366. (pipe-process
  20367. "My text\n"
  20368. &`@lbracechar{}tr a-z A-Z@rbracechar{}
  20369. &`@lbracechar{}wc@rbracechar{})
  20370. @end example
  20371. @deffn Syntax pipe-process input @arbno{process}
  20372. All of the @var{process} expressions must be @code{run-process} forms,
  20373. or equivalent @code{&`@lbracechar{}command@rbracechar{}} forms.
  20374. The result of evaluating @var{input} becomes the input to the first
  20375. @var{process}; the output from the first @var{process} becomes
  20376. the input to the second @var{process}, and so on. The result of
  20377. whole @code{pipe-process} expression is that of the last @var{process}.
  20378. Copying the output of one process to the input of the next is
  20379. optimized: it uses a copying loop in a separate thread. Thus you can
  20380. safely pipe long-running processes that produce huge output. This
  20381. isn't quite as efficient as using an operating system pipe, but is
  20382. portable and works pretty well.
  20383. @end deffn
  20384. @subsection Setting the process environment
  20385. @anchor{meta-process-environment-argument}
  20386. By default the new process inherits the system environment of the current
  20387. (JVM) process as returned by @code{System.getenv()}, but you can override it.
  20388. A @var{process-environment-argument} can be one of the following:
  20389. @table @asis
  20390. @item @stxlit{env-}@var{name}@stxlit{:} @var{value}
  20391. In the process environment, set the @code{"@var{name}"} to the
  20392. specified @var{value}. For example:
  20393. @example
  20394. &`[env-CLASSPATH: ".:classes"]@lbracechar{}java MyClass@rbracechar{}
  20395. @end example
  20396. @item @var{NAME}@stxlit{:} @var{value}
  20397. Same as using the @code{env-@var{NAME}} option above, but only if the
  20398. @code{@var{NAME}} is uppercase (i.e. if uppercasing @code{@var{NAME}} yields
  20399. the same string). For example the previous example could be written:
  20400. @example
  20401. &`[CLASSPATH: ".:classes"]@lbracechar{}java MyClass@rbracechar{}
  20402. @end example
  20403. @item @stxlit{environment:} @var{env}
  20404. The @var{env} is evaluated and must yield a @code{HashMap}.
  20405. This map is used as the system environment of the process.
  20406. @end table
  20407. @subsection Waiting for process exit
  20408. When a process finishes, it returns an integer exit code.
  20409. The code is traditionally 0 on successful completion,
  20410. while a non-zero code indicates some kind of failure or error.
  20411. @deffn Procedure process-exit-wait process
  20412. The @var{process} expression must evaluate to a process
  20413. (any @code{java.lang.Process} object).
  20414. This procedure waits for the process to finish, and then returns the
  20415. exit code as an @code{int}.
  20416. @example
  20417. (process-exit-wait (run-process "echo foo")) @result{} 0
  20418. @end example
  20419. @end deffn
  20420. @deffn Procedure process-exit-ok? process
  20421. Calls @code{process-exit-wait}, and then returns @code{#false}
  20422. if the process exited it 0, and returns @code{#true} otherwise.
  20423. This is useful for emulating the way traditional shell do
  20424. logic control flow operations based on the exit code.
  20425. For example in @code{sh} you might write:
  20426. @example
  20427. if grep Version Makefile >/dev/null
  20428. then echo found Version
  20429. else echo no Version
  20430. fi
  20431. @end example
  20432. The equivalent in Kawa:
  20433. @example
  20434. (if (process-exit-ok? &`@lbracechar{}grep Version Makefile@rbracechar{})
  20435. &`@lbracechar{}echo found@rbracechar{}
  20436. &`@lbracechar{}echo not found@rbracechar{})
  20437. @end example
  20438. Strictly speaking these are not quite the same, since the Kawa
  20439. version silently throws away the output from @code{grep}
  20440. (because no-one has asked for it). To match the output from the @code{sh},
  20441. you can use @code{out-to: 'inherit}:
  20442. @example
  20443. (if (process-exit-ok? &`[out-to: 'inherit]@lbracechar{}grep Version Makefile@rbracechar{})
  20444. &`@lbracechar{}echo found@rbracechar{}
  20445. &`@lbracechar{}echo not found@rbracechar{})
  20446. @end example
  20447. @end deffn
  20448. @anchor{Exiting the current process}
  20449. @subsection Exiting the current process
  20450. @deffn Procedure exit [code]
  20451. Exits the Kawa interpreter, and ends the Java session.
  20452. Returns the value of @var{code} to the operating system:
  20453. The @var{code} must be integer, or the special
  20454. values @code{#f} (equivalent to -1), or
  20455. @code{#t} (equivalent to 0).
  20456. If @var{code} is not specified, zero is returned.
  20457. The @var{code} is a status code; by convention a non-zero
  20458. value indicates a non-standard (error) return.
  20459. Before exiting, finally-handlers (as in @code{try-finally},
  20460. or the @var{after} procedure of @code{dynamic-wind}) are
  20461. executed, but only in the current thread, and only if
  20462. the current thread was started normally. (Specifically
  20463. if we're inside an @code{ExitCalled} block with non-zero
  20464. nesting - see @code{gnu.kawa.util.ExitCalled}.)
  20465. Also, JVM shutdown hooks are executed - which includes
  20466. flushing buffers of output ports. (Specifically
  20467. @code{Writer} objects registered with the @code{WriterManager}.)
  20468. @end deffn
  20469. @deffn Procedure emergency-exit [code]
  20470. Exits the Kawa interpreter, and ends the Java session.
  20471. Communicates an exit value in the same manner as @code{exit}.
  20472. Unlike @code{exit}, neither finally-handlers nor
  20473. shutdown hooks are executed.
  20474. @end deffn
  20475. @subsection Deprecated functions
  20476. @deffn Procedure make-process command envp
  20477. Creates a @code{<java.lang.Process>} object, using the specified
  20478. @var{command} and @var{envp}.
  20479. The @var{command} is converted to an array of Java strings
  20480. (that is an object that has type @code{<java.lang.String[]>}.
  20481. It can be a Scheme vector or list (whose elements should be
  20482. Java strings or Scheme strings); a Java array of Java strings;
  20483. or a Scheme string. In the latter case, the command is converted
  20484. using @code{command-parse}.
  20485. The @var{envp} is process environment; it should be either
  20486. a Java array of Java strings, or the special @code{#!null} value.
  20487. Except for the representation of @var{envp}, this is similar to:
  20488. @example
  20489. (run-process environment: @var{envp} @var{command})
  20490. @end example
  20491. @end deffn
  20492. @deffn Procedure system command
  20493. Runs the specified @var{command}, and waits for it to finish.
  20494. Returns the return code from the command. The return code is an integer,
  20495. where 0 conventionally means successful completion.
  20496. The @var{command} can be any of the types handled by @code{make-process}.
  20497. Equivalent to:
  20498. @example
  20499. (process-exit-wait (make-process @var{command} #!null))
  20500. @end example
  20501. @end deffn
  20502. @defvar command-parse
  20503. The value of this variable should be a one-argument procedure.
  20504. It is used to convert a command from a Scheme string to a Java
  20505. array of the constituent "words".
  20506. The default binding, on Unix-like systems, returns a new command to
  20507. invoke @code{"/bin/sh" "-c"} concatenated with the command string;
  20508. on non-Unix-systems, it is bound to @code{tokenize-string-to-string-array}.
  20509. @end defvar
  20510. @deffn Procedure tokenize-string-to-string-array command
  20511. Uses a @code{java.util.StringTokenizer} to parse the @var{command} string
  20512. into an array of words. This splits the @var{command} using spaces
  20513. to delimit words; there is no special processing for quotes or other
  20514. special characters.
  20515. (This is the same as what @code{java.lang.Runtime.exec(String)} does.)
  20516. @end deffn
  20517. @node Time-related functions
  20518. @section Time-related functions
  20519. @deffn Procedure current-second
  20520. Returns an inexact number represent the current time on the
  20521. @uref{http://en.wikipedia.org/wiki/International_Atomic_Time,International Atomic Time (TAI)} scale.
  20522. The value 0.0 represents midnight on January 1, 1070 TAI (equivalent
  20523. to 10 seconds before midnight Universal Time), and
  20524. the value 1.0 represents on TAI second later.
  20525. Neither high acuracy nor high precision are required; in particular
  20526. returning Coordinated Universal Time plus a suitable
  20527. constant might be the best an implementation cat do.
  20528. The Kawa implementation just multiplies by 0.001 the result of calling
  20529. the method @code{currentTimeMillis} in class @code{java.lang.System}.
  20530. @end deffn
  20531. @deffn Procedure current-jiffy
  20532. Returns the number of @dfn{jiffies} as an exact integer that have
  20533. elapses since an arbitrary implementation-defined epoch (instant).
  20534. A jiffy is an implementation-defined fraction of a second which is
  20535. defined by the return value of the @code{jiffies-per-second} procedure.
  20536. The starting epoch (instant 0) is guaranteed to be constant during
  20537. a run of the program, but may vary between runs.
  20538. (At the time of writing, Kawa's jiffy is one nano-second.)
  20539. @emph{Rationale:} Jiffies are allowed to be implementation-dependent
  20540. so that @code{current-jiffy} can execute with minimal overhead.
  20541. It should be very likely that a compactly represented integer will
  20542. suffice as the return value. Any particular jiffy size will be
  20543. inappropriate some some implementations: a microsecond is too long for
  20544. a very fast machine, while a much smaller unit would force many
  20545. implementations to return integers which have to allocated for most calls,
  20546. rendering @code{current-jiffy} less useful for accurate timing measurements.
  20547. @end deffn
  20548. @deffn Procedure jiffies-per-second
  20549. Returns an exact integer representing the number of jiffies
  20550. per SI second. This value is an implementation-specified
  20551. constant.
  20552. (At the time of writing, the value in Kawa is 1,000,000,000.)
  20553. @end deffn
  20554. @deffn Procedure sleep time
  20555. Suspends the current thread for the specified time.
  20556. The @var{time} can be either a pure number (in secords),
  20557. or a quantity whose unit is a time unit (such as @code{10s}).
  20558. @end deffn
  20559. @node Low-level functions
  20560. @section Deprecated low-level functions
  20561. These sections document older and less convenient ways
  20562. to call Java methods, access Java fields, and use Java arrays.
  20563. @anchor{Low-level Method invocation}
  20564. @subsection Low-level Method invocation
  20565. The following lower-level primitives require you to specify
  20566. the parameter and return types explicitly.
  20567. You should probably use the functions @code{invoke} and @code{invoke-static}
  20568. (@pxref{Method operations}) instead.
  20569. @deffn Syntax primitive-constructor class (argtype ...)
  20570. Returns a new anonymous procedure, which when called will create
  20571. a new object of the specified class, and will then call the
  20572. constructor matching the specified argument types.
  20573. @end deffn
  20574. @deffn Syntax primitive-virtual-method class method rtype (argtype ...)
  20575. Returns a new anonymous procedure, which when called will
  20576. invoke the instance method whose name is the string @var{method}
  20577. in the class whose name is @var{class}.
  20578. @end deffn
  20579. @deffn Syntax primitive-static-method class method rtype (argtype ...)
  20580. Returns a new anonymous procedure, which when called will
  20581. invoke the static method whose name is the string @var{method}
  20582. in the class whose name is @var{class}.
  20583. @end deffn
  20584. @deffn Syntax primitive-interface-method interface method rtype (argtype ...)
  20585. Returns a new anonymous procedure, which when called will
  20586. invoke the matching method from the interface whose name is @var{interface}.
  20587. @end deffn
  20588. The macros return procedure values, just like @code{lambda}.
  20589. If the macros are used directly as the procedure of a procedure call,
  20590. then kawa can inline the correct bytecodes to call the specified methods.
  20591. (Note also that neither macro
  20592. checks that there really is a method that matches the specification.)
  20593. Otherwise, the Java reflection facility is used.
  20594. @subsection Low-level field operations
  20595. The following macros evaluate to procedures that can be used to
  20596. access or change the fields of objects or static fields.
  20597. The compiler can inline each to a single bytecode instruction
  20598. (not counting type conversion).
  20599. These macros are deprecated.
  20600. The @code{fields} and @code{static-field} functions
  20601. (@pxref{Field operations}) are easier to use, more powerful, and
  20602. just as efficient. However, the high-level functions currently do
  20603. not provide access to non-public fields.
  20604. @deffn Syntax primitive-get-field class fname ftype
  20605. Use this to access a field named @var{fname} having type @var{type} in
  20606. class @var{class}. Evaluates to a new one-argument procedure,
  20607. whose argument is a reference to an object of the specified @var{class}.
  20608. Calling that procedure returns the value of the specified field.
  20609. @end deffn
  20610. @deffn Syntax primitive-set-field class fname ftype
  20611. Use this to change a field named @var{fname} having type @var{type} in
  20612. class @var{class}. Evaluates to a new two-argument procedure,
  20613. whose first argument is a reference to an object of the
  20614. specified @var{class}, and the second argument is the new value.
  20615. Calling that procedure sets the field to the specified value.
  20616. (This macro's name does not end in a @samp{!}, because it does not actually
  20617. set the field. Rather, it returns a function for setting the field.)
  20618. @end deffn
  20619. @deffn Syntax primitive-get-static class fname ftype
  20620. Like @code{primitive-get-field}, but used to access static fields.
  20621. Returns a zero-argument function, which when called returns
  20622. the value of the static field.
  20623. @end deffn
  20624. @deffn Syntax primitive-set-static class fname ftype
  20625. Like @code{primitive-set-field}, but used to modify static fields.
  20626. Returns a one-argument function, which when called sets the
  20627. value of the static field to the argument.
  20628. @end deffn
  20629. @anchor{Low-level array macros}
  20630. @subsection Old low-level array macros
  20631. The following macros evaluate to procedures that can be used to
  20632. manipulate primitive Java array objects.
  20633. The compiler can inline each to a single bytecode instruction
  20634. (not counting type conversion).
  20635. @deffn Syntax primitive-array-new element-type
  20636. Evaluates to a one-argument procedure. Applying the resulting procedure to
  20637. an integer count allocates a new Java array of the specified length,
  20638. and whose elements have type @var{element-type}.
  20639. @end deffn
  20640. @deffn Syntax primitive-array-set element-type
  20641. Evaluates to a three-argument procedure. The first argument of
  20642. the resulting procedure must be an array whose elements have type
  20643. @var{element-type}; the second argument is an index; and the third
  20644. argument is a value (coercible to @var{element-type}) which replaces
  20645. the value specified by the index in the given array.
  20646. @end deffn
  20647. @deffn Syntax primitive-array-get element-type
  20648. Evaluates to a two-argument procedure. The first argument of
  20649. the resulting procedure must be an array whose elements have type
  20650. @var{element-type}; the second argument is an index.
  20651. Applying the procedure returns the element at the specified index.
  20652. @end deffn
  20653. @deffn Syntax primitive-array-length element-type
  20654. Evaluates to a one-argument procedure. The argument of
  20655. the resulting procedure must be an array whose elements have type
  20656. @var{element-type}.
  20657. Applying the procedure returns the length of the array.
  20658. (Alternatively, you can use @code{(field @var{array} 'length)}.)
  20659. @end deffn
  20660. @node FAQs
  20661. @chapter Frequently Asked Questions
  20662. @ignore
  20663. @subsubheading What is the difference between load, require, import, and include?
  20664. Handling @code{include} is all done at compile time. It's as if the text
  20665. of the included file is copied and replaces the include command.
  20666. If the include is inside a @code{let}, the included text can
  20667. use the name defined in the @code{let}.
  20668. In contrast @code{load} is a procedure, not syntax.
  20669. It reads and evaluates each line in the file, one at a time,
  20670. @end ignore
  20671. @anchor{importing-class-names}
  20672. @subsubheading What is the equivalent of Java import?
  20673. To provide a short name for a class instead of the complete fully-qualified
  20674. name use either @code{define-alias} (or @code{define-private-alias})
  20675. or the @code{import}-@code{class} combination.
  20676. For example, to be able to write @code{ArrayList} instead
  20677. of @code{java.util.ArrayList} do either:
  20678. @example
  20679. (import (class java.util ArrayList))
  20680. @end example
  20681. or
  20682. @example
  20683. (define-alias ArrayList java.util.ArrayList)
  20684. @end example
  20685. Using @code{import} is recommended:
  20686. It handles errors better,
  20687. and it allows you to define multiple aliases conveniently:
  20688. @example
  20689. (import (class java.util Map HashMap))
  20690. @end example
  20691. Both forms allow renaming. For example if you want to refer
  20692. to @code{java.lang.StringBuilder} as @code{StrBuf} do:
  20693. @example
  20694. (import (class java.lang (StringBuilder StrBuf)))
  20695. @end example
  20696. or:
  20697. @example
  20698. (define-alias StrBuf java.lang.StringBuilder)
  20699. @end example
  20700. The name(s) defined by @code{import} are by default private.
  20701. A name defined using @code{define-alias} is by default exported;
  20702. to avoid that use @code{define-private-alias} instead.
  20703. You can also use @code{define-namespace} to introduce an abbreviation or
  20704. renaming of a class name, but as a matter of style @code{define-alias}
  20705. is preferred.
  20706. There is no direct equivalent to Java's @code{import PackageOrTypeName.*}
  20707. (type-import-on-demand) declaration, but you can alias a package:
  20708. @example
  20709. (define-alias jutil java.util)
  20710. (define mylist :: jutil:List (jutil:ArrayList))
  20711. @end example
  20712. To import a static member, giving it a shortened name
  20713. (like Java's static-import-on-demand declaration), you can use
  20714. @code{define-alias}. For example:
  20715. @example
  20716. (define-alias console java.lang.System:console)
  20717. @end example
  20718. For static fields only (not methods or member classes) you can
  20719. use an @code{import} form, either:
  20720. @example
  20721. (import (only (java lang System) out))
  20722. @end example
  20723. or:
  20724. @example
  20725. (import (only java.lang.System out))
  20726. @end example
  20727. This works because Kawa can treat any class as a ``library'';
  20728. in which case it considers all public static fields as exported bindings.
  20729. @subsubheading How do I refer to a Java member (nested) class?
  20730. Consider the Java SE member class @code{javax.swing.text.AbstractDocument.Content}.
  20731. Using the Java syntax doesn't work in Kawa.
  20732. Inside you should use Kawa's colon operator:
  20733. @example
  20734. javax.swing.text.AbstractDocument:Content
  20735. @end example
  20736. Alternatively, you can use the internal JVM class name:
  20737. @example
  20738. javax.swing.text.AbstractDocument$Content
  20739. @end example
  20740. @subsubheading Why does Kawa's REPL use display rather than write?
  20741. The read-eval-print-loop of most Scheme implementations prints the
  20742. evaluation result using @code{write}, while Kawa uses @code{display} by default.
  20743. First note that it is easy to override the default with the
  20744. @code{--output-format} command-line option:
  20745. @example
  20746. $kawa --output-format readable-scheme
  20747. #|kawa:1|# "abc"
  20748. "abc"
  20749. @end example
  20750. The reason @code{display} is the default is because of a vision of the REPL
  20751. console as more than just printing out Scheme objects in
  20752. textual form for use by a programmer.
  20753. Some examples:
  20754. @itemize
  20755. @item
  20756. A math program can display equations and graphs as the
  20757. output of an expression.
  20758. @item
  20759. An expression can evaluate to a``@ref{Composable pictures,picture}''
  20760. which would be displayed inline.
  20761. @item
  20762. An HTML/XML obj can be insert into the output in visual
  20763. form if the console understands HTML. (There is a prototype
  20764. for this that works by using the JavaFX WebView as the display.)
  20765. @item
  20766. The plan for "Kawa-shell" functionality is to have expressions
  20767. that evaluate to process objects, which would be lazy strings.
  20768. This string would be the data from standard output. Thus the
  20769. effect of displaying a process object would be to print out
  20770. the standard output - just like a regular shell. Users would
  20771. find it confusing/annoying if shell output used quotes.
  20772. @end itemize
  20773. This "repl-as-pad" model doesn't work as well if the repl
  20774. uses @code{write} rather than @code{display}.
  20775. @node Framework
  20776. @chapter The Kawa language framework
  20777. Kawa is a framework written in Java for implementing
  20778. high-level and dynamic languages, compiling them into Java bytecodes.
  20779. The Kawa distributions includes of other programming languages
  20780. besides Scheme,
  20781. including @uref{../qexo/index.html, XQuery (Qexo)}
  20782. and @uref{http://JEmacs.sourceforge.net/,Emacs Lisp (JEmacs)}.
  20783. For a technical overview of Kawa, see these
  20784. @uref{http://www.gnu.org/software/kawa/internals/index.html}.
  20785. Javadoc generated @uref{http://www.gnu.org/software/kawa/api/,documentation of the Kawa classes} is also available.
  20786. The packages
  20787. @uref{http://www.gnu.org/software/kawa/api/gnu/bytecode/package-summary.html,@code{gnu.bytecode}},
  20788. @uref{http://www.gnu.org/software/kawa/api/gnu/math/package-summary.html,@code{gnu.math}},
  20789. @uref{http://www.gnu.org/software/kawa/api/gnu/lists/package-summary.html,@code{gnu.lists}},
  20790. @uref{http://www.gnu.org/software/kawa/api/gnu/xml/package-summary.html,@code{gnu.xml}},
  20791. @uref{http://www.gnu.org/software/kawa/api/gnu/expr/package-summary.html,@code{gnu.expr}},
  20792. @uref{http://www.gnu.org/software/kawa/api/gnu/mapping/package-summary.html,@code{gnu.mapping}},
  20793. and
  20794. @uref{http://www.gnu.org/software/kawa/api/gnu/text/package-summary.html,@code{gnu.text}},
  20795. are used by Kawa, and distributed with it, but may be independently useful.
  20796. This @uref{gnu.bytecode/compiling-regexps.html,article} explains how to
  20797. use @code{gnu.bytecode} to compile regular expressions to bytecode.
  20798. @node License
  20799. @chapter License
  20800. @menu
  20801. * Software-License:: License for the Kawa software
  20802. * Manual-License:: License for the Kawa manual
  20803. @end menu
  20804. @node Software-License, Manual-License, , License
  20805. @section License for the Kawa software
  20806. The license for the Kawa software
  20807. (except the optional JEmacs and BRL features - see below) is the
  20808. @uref{http://opensource.org/licenses/mit-license.php, X11/MIT license}
  20809. which is quoted below.
  20810. @example
  20811. The software (with related files and documentation) in these packages
  20812. are copyright (C) 1996-2009 Per Bothner.
  20813. Permission is hereby granted, free of charge, to any person obtaining
  20814. a copy of this software and associated documentation files (the
  20815. "Software"), to deal in the Software without restriction, including
  20816. without limitation the rights to use, copy, modify, merge, publish,
  20817. distribute, sublicense, and/or sell copies of the Software, and to
  20818. permit persons to whom the Software is furnished to do so, subject to
  20819. the following conditions:
  20820. The above copyright notice and this permission notice shall be
  20821. included in all copies or substantial portions of the Software.
  20822. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20823. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20824. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20825. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20826. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20827. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20828. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20829. @end example
  20830. In the past the Kawa license was a ``modified GNU GPL (General
  20831. Public License)".
  20832. If you find any files that contain the old license or otherwise seem
  20833. to contradict the new license, please report that as a bug.
  20834. Some of the JEmacs files are based on Emacs and have a GPL license,
  20835. which is incompatible with non-Free (proprietary) products. For that
  20836. reason, the @code{gnu.jemacs.*} packages are not included any more in
  20837. the standard @code{.jar}, or by default when building from source, to
  20838. avoid surprises.
  20839. To build JEmacs you have to specify the @code{configure}
  20840. flag @code{--enable-jemacs} or the @code{ant} flag
  20841. @code{-Denable-jemacs=true}.
  20842. Some code in @code{gnu/brl} and @code{gnu/kawa/brl} is copyright
  20843. Bruce R. Lewis and Eaton Vance Management,
  20844. with a modified-GPL license: no restrictions if used
  20845. unmodified, but otherwise the GPL applies.
  20846. These packages are no longer included by default in Kawa builds,
  20847. but have to be selected with the @code{configure}
  20848. flag @code{--enable-brl} or the @code{ant} flag @code{-Denable-brl=true}.
  20849. Kawa uses some math routines from fdlib's libf77,
  20850. which have a AT&T Bell Laboratories and Bellcore copyright.
  20851. See the source file @code{gnu/math/DComplex.java}.
  20852. The sorting routine in @code{gnu.xquery.util.OrderedTuples}
  20853. is a re-implementatiomn in Java of code copyrighted by
  20854. Simon Tatham.
  20855. Some of the Scheme code in @code{kawa/lib} and @code{gnu/kawa/slib}
  20856. are copyright other parties, and may have slightly different
  20857. license wording, but I believe none of then contradicts the
  20858. main Kawa license or impose extra restrictions.
  20859. Search for the word @code{copyright} in these directories.
  20860. Some code has been converted from other languages, with permission.
  20861. This includes the @code{rationalize} method
  20862. in @code{gnu/math/RatNum.java}, based on an algorithm of Alan Bawden,
  20863. as expressed by Marc Feeley in C-Gambit.
  20864. The concepts and algorithm of @code{gnu/text/PrettyWriter.java}
  20865. are converted from SBCL, which is in the public domain.
  20866. @node Manual-License, , Software-License, License
  20867. @section License for the Kawa manual
  20868. Here is the copyright license for this manual:
  20869. Copyright @copyright{} 1996, 1997, 1998, 1999, 2005 Per Bothner
  20870. Permission is granted to make and distribute verbatim copies of
  20871. this manual provided the copyright notice and this permission notice
  20872. are preserved on all copies.
  20873. Permission is granted to copy and distribute modified versions of this
  20874. manual under the conditions for verbatim copying, provided that the entire
  20875. resulting derived work is distributed under the terms of a permission
  20876. notice identical to this one.
  20877. Permission is granted to copy and distribute translations of this manual
  20878. into another language, under the above conditions for modified versions,
  20879. except that this permission notice may be stated in a translation approved
  20880. by the author.
  20881. Parts of this manual are copied from the @uref{http://www.r6rs.org/,R6RS}
  20882. or @uref{http://www.r7rs.org/,R7RS}, which both state:
  20883. @quotation
  20884. We intend this report to belong to the entire Scheme community, and so
  20885. we grant permission to copy it in whole or in part without fee. In
  20886. particular, we encourage implementors of Scheme to use this report as
  20887. a starting point for manuals and other documentation, modifying it as
  20888. necessary.
  20889. @end quotation
  20890. Parts of this manual were derived from the SLIB manual,
  20891. copyright @copyright{} 1993-1998 Todd R. Eigenschink and Aubrey Jaffer.
  20892. Parts of this manual were derived from ISO/EIC 10179:1996(E)
  20893. (Document Style and Specifical Language) - unknown copyright.
  20894. This manual has quoted from SRFI-6 (Basic String Ports),
  20895. which is Copyright (C) William D Clinger (1999). All Rights Reserved.
  20896. This manual has quoted from SRFI-8 (receive: Binding to multiple values),
  20897. which is Copyright (C) John David Stone (1999). All Rights Reserved.
  20898. This manual has quoted from SRFI-9 (Defining Record Types)
  20899. which is Copyright (C) Richard Kelsey (1999). All Rights Reserved.
  20900. This manual has quoted from SRFI-11 (Syntax for receiving multiple values),
  20901. which is Copyright (C) Lars T. Hansen (1999). All Rights Reserved.
  20902. This manual has quoted from SRFI-25 (Multi-dimensional Array Primitives),
  20903. which is Copyright (C) Jussi Piitulainen (2001). All Rights Reserved.
  20904. This manual has quoted from SRFI-26 (Notation for Specializing
  20905. Parameters without Currying),
  20906. which is Copyright (C) Sebastian Egner (2002). All Rights Reserved.
  20907. This manual has quoted from SRFI-39 (Parameter objects),
  20908. which is Copyright (C) Marc Feeley (2002). All Rights Reserved.
  20909. The following notice applies to SRFI-6, SRFI-8, SRFI-9, SRFI-11, SRFI-25,
  20910. SRFI-26, and SRFI-39,
  20911. which are quoted in this manual, but it does not apply to the manual as a whole:
  20912. @quotation
  20913. This document and translations of it may be copied and furnished to
  20914. others, and derivative works that comment on or otherwise explain it or
  20915. assist in its implementation may be prepared, copied, published and
  20916. distributed, in whole or in part, without restriction of any kind,
  20917. provided that the above copyright notice and this paragraph are included
  20918. on all such copies and derivative works. However, this document itself
  20919. may not be modified in any way, such as by removing the copyright notice
  20920. or references to the Scheme Request For Implementation process or
  20921. editors, except as needed for the purpose of developing SRFIs in which
  20922. case the procedures for copyrights defined in the SRFI process must be
  20923. followed, or as required to translate it into languages other than
  20924. English.
  20925. The limited permissions granted above are perpetual and will not be
  20926. revoked by the authors or their successors or assigns.
  20927. This document and the information contained herein is provided on an
  20928. "AS IS" basis and THE AUTHOR AND THE SRFI EDITORS DISCLAIM ALL
  20929. WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY
  20930. WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
  20931. RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
  20932. PARTICULAR PURPOSE.
  20933. @end quotation
  20934. This manual has quoted from SRFI-69 (Basic hash tables),
  20935. which is Copyright (C) Panu Kalliokoski (2005). All Rights Reserved.
  20936. The following notice applies to SRFI-69,
  20937. which is quoted in this manual, but it does not apply to the manual as a whole:
  20938. @quotation
  20939. Permission is hereby granted, free of charge, to any person obtaining
  20940. a copy of this software and associated documentation files (the
  20941. Software), to deal in the Software without restriction, including
  20942. without limitation the rights to use, copy, modify, merge, publish,
  20943. distribute, sublicense, and/or sell copies of the Software, and to
  20944. permit persons to whom the Software is furnished to do so, subject to
  20945. the following conditions:
  20946. The above copyright notice and this permission notice shall be
  20947. included in all copies or substantial portions of the Software.
  20948. THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20949. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20950. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20951. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20952. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20953. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20954. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20955. @end quotation
  20956. This manual has made use of text and examples from Dorai Sitaram's
  20957. @code{pregexp} implementation. But not where the latter talks about
  20958. @code{pregexp-xxx} functions; the manual also talks about
  20959. the @code{regex-xxx} functions (which are similar but use a
  20960. slightly different regular expression syntax).
  20961. The @code{pregexp} distribution has the following @code{COPYING} file:
  20962. @quotation
  20963. Copyright (c) 1999-2005, Dorai Sitaram.
  20964. All rights reserved.
  20965. Permission to copy, modify, distribute, and use this work or
  20966. a modified copy of this work, for any purpose, is hereby
  20967. granted, provided that the copy includes this copyright
  20968. notice, and in the case of a modified copy, also includes a
  20969. notice of modification. This work is provided as is, with
  20970. no warranty of any kind.
  20971. @end quotation
  20972. @c I'd prefer to call this node plain "Index", but that causes a clash
  20973. @c with index.html when generating HTML on case-insenstive file systems.
  20974. @node Overall Index, , License, Top
  20975. @appendix Index
  20976. @printindex cp
  20977. @bye