Home

CHICKEN User`s Manual - The User`s Manual

image

Contents

1. char snal 42 5 6 Why don t toplevel continuations captured in interpreted code work 270 CHICKEN User s Manual The User s Manual Another symptom is that require srfi 18 will silently fail This typically happens because the Chicken libraries have been installed in a non standard location such as your home directory The workaround is to explicitly tell the dynamic linker where to look for your libraries export DYLD LIBRARY PATH scheme chicken lib DYLD LIBRARY PATH Mac export LD LIBRARY PATH scheme chicken lib LD LIBRARY PATH Linux 42 5 9 How can increase the size of the trace shown when runtime errors are detected When a runtime error is detected Chicken will print the last entries from the trace of functions called unless your executable was compiled with the no trace option By default only 16 entries will be shown To increase this number pass the aN parameter to your executable 42 6 Optimizations 42 6 1 How can obtain smaller executables If you don t need eval or the stuff in the extras library unit you can just use the Library unit declare uses library dileblay world n Don t forget to compile with the explicit use option Compiled with Visual C this generates an executable of around 240 kilobytes It is theoretically possible to compile something without the library but a program would have to implement quite a lot of support code on its own 42 6 2 How can obta
2. For use with string as a hash table equivalence function 23 2 6 string ci hash procedure string ci hash STRING BOUND For use with string ci as a hash table equivalence function 23 2 7 eq hash procedure eq hash OBJECT BOUND For use with eq as ahash table equivalence function 23 2 8 eqv hash procedure eqv hash OBJECT BOUND For use with eqv as ahash table equivalence function 23 2 9 equal hash procedure equal hash OBJECT BOUND For use with equal as ahash table equivalence function 23 2 10 hash procedure hash OBJECT BOUND Synonym for equal hash 23 2 5 string hash 135 CHICKEN User s Manual The User s Manual 23 2 11 hash by identity procedure hash by identity OBJECT BOUND Synonym for eq hash Previous Unit srfi 14 Next Unit match 23 2 11 hash by identity 136 24 Unit match The runtime support code for the Pattern Matching extensions Note that to use the macros in normal compiled code it is not required to declare this unit as used It is only necessary to do so if forms containing these macros are to be expanded at runtime Previous Unit srfi 14 Next Unit regex 24 Unit match 137 25 Unit regex This library unit provides support for regular expressions The regular expression package used is PCRE Perl Compatible Regular Expressions written by Philip Hazel See http www pcre org for information about the particular regexp
3. The invocation of install extension provides the files that are to be copied into the extension repository and a metadata list that specifies that the extension g lass is a syntax extension and that if it is declared to be used by other code either with the require extension or require for syntax form then client code should perform an implicit require glass support at startup 39 5 Examples for extensions 254 CHICKEN User s Manual The User s Manual This can be conveniently packaged as an egg tar cfz glass egg glass setup glass scm glass support scm And now we use it chicken setup glass csi quiet 1 gt require extension glass loading usr local lib chicken 1 glass scm loading usr local lib chicken 1 glass support so 2 gt define foo glass lambda x y x y 3 gt glass lambda set foo y 99 4 gt foo 33 132 39 6 chicken setup reference Available options h help Show usage information and exit V version Display version and exit R repository PATHNAME When used without an argument the path of the extension repository is displayed on standard output When given an argument the repository pathname and the repository path parameter will be set to PATHNAME for all subsequent operations The default repository path is the installation library directory usually usr local lib chicken or if set the directory given in the environment variable CHICKEN REPOSITORY PATH
4. Removes breakpoints Ke Continues execution from the last invoked breakpoint breakall Enable breakpoints for all threads this is the default breakonly THREAD Enable breakpoints only for the thread returned by the expression THREAD info Lists traced procedures and breakpoints Step EXPR Evaluates EXPR in single stepping mode On each procedure call you will be presented with a menu that allows stepping to the next call leaving single stepping mode or triggering a breakpoint Note that you will see some internal calls and unsafe or heavily optimized compiled code might not be stepped at all Single stepping mode is also possible by invoking the singlestep procedure You can define your own toplevel commands using the top Level command procedure 5 4 toplevel command procedure toplevel command SYMBOL PROC HELPSTRING Defines or redefines a toplevel interpreter command which can be invoked by entering SYMBOL PROC will be invoked when the command is entered and may read any required argument via read or read Line If the optional argument HELPSTRING is given it will be listed by the command 5 5 History access The interpreter toplevel accepts the special object INDEX which returns the result of entry number INDEX in the history list If the expression for that entry resulted in multiple values the first result or an unspecified value for no values is returned If no INDEX is given and if a whitespace or c
5. define external foo int foreign lambda void c pointer int ip ip 123 location foo foo This facility is especially useful in situations where a C function returns more than one result value gt 36 Locations 233 CHICKEN User s Manual The User s Manual include lt math h gt lt define modf foreign lambda double modf double c pointer double let location i double let f modf 1 99 location i print iz i f f See location and c string for a tip on returning a C St ring type location returns a value of type C pointer when given the name of a callback procedure defined with define external Previous Callbacks Next Other support procedures 36 3 location 234 37 Other support procedures 37 1 argc argv procedure argctargv Returns two values an integer and a foreign pointer object representing the argc and argv arguments passed to the current process Previous Locations Next C interface 37 Other support procedures 235 38 C interface The following functions and macros are available for C code that invokes Scheme or foreign procedures that are called by Scheme 38 1 C save C macro void C save C word x Saves the Scheme data object X on the temporary stack 38 2 C restore C macro void C restore Pops and returns the topmost value from the temporary stack 38 3 C fix C macro C word C fix int integer 38 4 C make ch
6. i edzsnavecseansnesticnsevideonvdoadeve leagues tee teedndeadusnes sade ane rada eee te Eee Ane YER eeu ded 161 Ee E 161 21 8 4 PLOCESS CKECULE Lien AER eue et Jankicssaccasedsaaatedguccesusauausessancveuaenedadeseidedas sexe 161 PARERE PLOCES STORK o eege eege eege ee E ege 161 21 8 0 PLOCESS TUMN AE TETA bs ose lg ee eee deeg 162 21 8 7 process signal ioci e OO OPERE eebe EES sees 162 PENDISSE 162 21829 PLOCESS REED LITTLE 162 PA E LUV IS ERECTO TEILEN 163 SR TE IDCM M A 163 218 12 createssessIOTO EEN 163 27 9 Hard and symbolic hinks hoe rte he utu ee te easet deed E E 163 xii CHICKEN User s Manual The User s Manual Chicken User s Manual 27 Unit posix 27 9 1 symbohic hmk E 163 27 92 Create SYMBOlC ON 164 21 9 3 El TEE 164 NS Fe E 164 27 10 Retrieving user amp group oformaon eee ececeececeeeeesneceeseeceaceceeceeeeeeeaaeceeaceceaeeceeeeaeeeeaaeceeaeceeeeeesas 164 2 10 1 Current set id EEN 164 27 10 2 c rrent efftectrve ser 1d EE 164 21 10 B TS er FOTIA OM EE 165 21 10 4 current gro p Id esseeri rene er ek e tee Pede de dedu e sede une rada eene Eee Ane EE een ded 165 ZCTIO03eurenteffectve geroup 20 eene ether enenet ensis en tenen tentes 165 27 10 6 group informatiOn e rore trae eue ette Ere eee ERES ERE ERR HET a aee EEN ec 165 PA E Ot EE 165 27 11 Changing user amp group information sse eene eene enne
7. procedure sort SEQUENCE LESS Sort SEQUENCE which should be a list or a vector Sort is the destructive version of sort 16 3 3 sorted procedure sorted SEQUENCE LESS Returns true if the list or vector SEQUENCE is already sorted 16 4 Random numbers 16 4 1 random seed procedure random seed SEED Seeds the random number generator with SEED an exact integer or current seconds if SEED is not given 16 5 Strings 16 5 1 conc procedure conc X Returns a string with the string represenation of all arguments concatenated together CONC could be implemented as define conc args apply string append map gt string args 16 3 2 sort 103 CHICKEN User s Manual The User s Manual 16 5 2 string procedure gt string X Returns a string representation of X 16 5 3 string chop procedure string chop STRING LENGTH Returns a list of substrings taken by chopping STRING every LENGTH characters d string chop one two three 4 gt one two thre e 16 5 4 string chomp procedure string chomp STRING SUFFIX If STRING ends with SUFFIX then this procedure returns a copy of its first argument with the suffix removed otherwise returns STRING unchanged SUFFIX defaults to Xn 16 5 5 string compare3 procedure string compare3 STRING1 STRING2 procedure string compare3 ci STRING1 STRING2 Perform a three way comparison between the STRING1 and ST
8. 12 6 bound to procedure 59 CHICKEN User s Manual The User s Manual 12 12 emit external prototypes first declaration specifier emit external prototypes first Emit prototypes for callbacks defined with de fine external before any other foreign declarations Equivalent to giving the emit external prototypes first option to the compiler 12 13 disable interrupts declaration specifier disable interrupts declaration specifier not interrupts enabled Disable timer interrupts checks in the compiled program Threads can not be preempted in main or library units that contain this declaration 12 14 disable warning declaration specifier disable warning CLASS Disable warnings of type CLASS equivalent to the disable warning CLASS compiler option 12 15 import declaration specifier import SYMBOL OR STRING Adds new imports to the list of externally available toplevel variables Arguments to this declaration may be either strings designating exports files without the file extension or symbols which directly designate imported variables 12 16 inline inline not inline inline IDENTIFIER not inline IDENTIFIER declaration specifier declaration specifier declaration specifier declaration specifier nnan If given without an identifier list inlining of known procedures is enabled this is equivalent to the inline compiler option When an identifier list is given th
9. 5 eie ttrr t etre tenente LI Pape eb ene Ee eR CEDERE PORRE ST RSS 111 17 2 3 with immput from sString sessio eee cts Gaertn i reete e Page eine LES EN ERE EP eee ee ERE e eee ede 111 LUI24wtb outputto stng nennen enne nenne TEE AAE entes entes etes tenet ness inen en nene 111 17 3 Port iterator S E 112 17 3 port tor each a iie or Reo i eret E EVHRE CREER ERE REESE ONES EE ER ERR 112 T732 vut e c 112 IAS 0 a E D 112 17 4 Funky e E 112 RSC Bert ele EE Te 112 17 4 2 make copncatenated port 112 SE Kitten ee 114 18 1 Formatted output ier rrt here ee er Pee EE ERR NS EUIS EE E tees 114 18 1 1 dee EE 114 18 el E 114 18 13 Sprintti eise rper tet rere i e deett eee Seed ee et 114 18 1 reg e EE 115 18 2 Rand Oni numbers gedet ee ENNEN ENEE EES 115 18 21 ratidomc seed eee ttr teo ety eo eere cere ve vespa ee 115 18 22 e 115 18 2 5 t nd KE 116 18 3 Input O tput EXTENSIONS EE 116 1831 pretty pritt E ie riere eroa o EEE E EEE EN S E EENES 116 18 5 2 pretty print Width E 116 18 33 te d nac DERE 116 ES EE EE 116 18 E Wor EE 116 183 OUS tere re 117 Be Ee ITIII 117 18 3 8 B Er 117 185329 TAGS CIN Gy 117 18 53 10 E E EE 117 18 3 11 write SUtlp ecco nios t E REEL E GERE RPG OREERT 117 18 312 S EI INNEREN 118 viii CHICKEN User s Manual The User s Manual Chicken User s Manual MSP Umit ND 119 S ue ST
10. Specifies version string 39 4 1 4 documentation extension property documentation FILENAME The filename of a HTML document containing extension specific documentation This file should be given in the file list passed to instal l extension and a link to it will be automatically included in the index page accessible via chicken setup docindex 39 4 1 5 examples extension property examples FILENAME Copies the given files into the examples directory which is usually prefix share chicken examples or make pathname chicken home examples Note that the files listed in this property should not be listed in the normal list of files to install passed to install extension This is the only exception other files that are installed in the repository must be given in the file list 39 4 1 6 exports extension property exports EXPORT Add export information to the generated extension information EXPORT may be a symbol naming an exported toplevel variable or a string designating a file with exported variables as generated by the emit exports option or the emit exports declaration specifier 39 4 1 7 static extension property static STRING If the extension also provides a static library then STRING should contain the name of that library Used by 39 4 1 install extension 247 CHICKEN User s Manual The User s Manual CSC when compiling with the static extensions option 39 4 1 8 static options
11. The HASH TABLE equivalence function 23 1 5 hash table hash function procedure hash table hash function HASH TABLE The HASH TABLE hash function 23 1 6 hash table min load procedure hash table min load HASH TABLE The HASH TABLE minimum load factor 23 1 7 hash table max load procedure hash table max load HASH TABLE The HASH TABLE maximum load factor 23 1 8 hash table weak keys procedure hash table weak keys HASH TABLE Does the HASH TABLE weak references for keys 23 1 9 hash table weak values procedure hash table weak values HASH TABLE Does the HASH TABLE weak references for values 23 1 4 hash table equivalence function 129 CHICKEN User s Manual The User s Manual 23 1 10 hash table has initial procedure hash table has initial HASH TABLE Does the HASH TABLE have a default initial value 23 1 11 hash table initial procedure hash table initial HASH TABLE The HASH TABLE default initial value 23 1 12 hash table keys procedure hash table keys HASH TABLE Returns a list of the keys in the HASH TABLE population 23 1 13 hash table values procedure hash table values HASH TABLE Returns a list of the values in the HASH TABLE population 23 1 14 hash tablealist procedure hash table gt alist HASH TABLE Returns the population of the HASH TABLE as an association List 23 1 15 alisthash table procedure alist gt hash table ASSOCIATION LIST MAK
12. cat quickrep dat xyzabcghi abxawxcgh foonly csi ss quickrep scm quickrep dat a c A xyzAghi Agh foonly 2 6 The Read Eval Print loop CHICKEN User s Manual The User s Manual The SS option sets several options that work smoothly together to execute a script You can make the command directly executable from the shell by inserting a shebang line at the beginning of the program regex the regular expression library is one of the libraries included with Chicken use regex define process line line re rplc string substitute re rplc line all define quickrep re rplc let line read line if not eof object line begin display process line line re rplc newline quickrep re rplc Does a lousy job of error checking define main args quickrep regexp car args cadr args The SS option arranges to call a procedure named main with the command line arguments packed in a list as its arguments There are a number of ways this program could be made more idiomatic Chicken Scheme see the rest of the manual for details 2 7 The compiler There are several reasons you might want to compile your code Compiled code executes substantially faster than interpreted code You might want to deploy an application onto machines where the users aren t expected to have Chicken installed compiled applications can be self contained The Chicken compiler is provided as the command
13. procedure port X Returns t if X is a port object or f otherwise 14 15 2 print procedure print EXP1 Outputs the optional arguments EXP1 using display and writes a newline character to the port that is the value of current output port Returns void 14 15 3 print procedure print EXP1 Similar to print but does not output a terminating newline character and performs a f Lush output after writing its arguments 14 16 User defined named characters 14 16 1 char name procedure char name SYMBOL OR CHAR CHAR This procedure can be used to inquire about character names or to define new ones With a single argument the behavior is as follows If SYMBOL OR CHAR is a symbol then char name returns the character with this name or f if no character is defined under this name If SYMBOL OR CHAR is a character then the name of the character is returned as a symbol or f if the character has no associated name If the optional argument CHAR is provided then SYMBOL OR CHAR should be a symbol that will be the new name of the given character If multiple names designate the same character then the write will use the character name that was defined last char name space gt space char name space gt Space char name bell gt f char name integer gt char 7 gt f char name bell integer gt char 7 char name bell gt bell char gt integer char
14. CHICKEN User s Manual The User s Manual 29 14 tcp write timeout parameter tcp write timeout Determines the timeout for TCP write operations in milliseconds A timeout of f disables timeout checking The default write timeout is 60000 i e 1 minute 29 15 tcp connect timeout parameter tcp connect timeout Determines the timeout for tcp connect operations in milliseconds A timeout of f disables timeout checking and is the default 29 16 tcp accept timeout parameter tcp accept timeout Determines the timeout for tcp accept operations in milliseconds A timeout of f disables timeout checking and is the default 29 17 Example A very simple example follows Say we have the two files client scm and server scm client scm declare uses tcp define values i o tcp connect iocalhost 4242 write line Good Bye o print read line i Server scm declare uses tcp define l tcp listen 4242 define values i o tcp accept 1 write line Hello o print read line i close input port i close output port o csc server scm 96 csc client scm Server A 29 14 tcp write timeout 193 CHICKEN User s Manual The User s Manual client Good Bye Hello Previous Unit utils Next Unit lolevel 29 17 Example 194 30 Unit lolevel This unit provides a number of handy low level operations Use at your own risk This unit uses the srfi 4 and extras units 30 1
15. Similar to system sprintf FORMATSTRING ARGUMENTI but signals an error if the invoked program should return a nonzero exit status 28 8 Reading a file s contents 28 6 Iterating over input lines and files 188 CHICKEN User s Manual The User s Manual 28 8 1 read all procedure read all FILE OR PORT If FILE OR PORT is a string then this procedure returns the contents of the file as a string If FILE OR PORT is a port all remaining input is read and returned as a string The port is not closed If no argument is provided input will be read from the port that is the current value of current input port Previous Unit posix Next Unit tcp 28 8 1 read all 189 29 Unit tcp This unit provides basic facilities for communicating over TCP sockets The socket interface should be mostly compatible to the one found in PLT Scheme This unit uses the extras unit All errors related to failing network operations will raise a condition of kind exn i o network 29 1 tcp listen procedure tcp listen TCPPORT BACKLOG HOST Creates and returns a TCP listener object that listens for connections on TCPPORT which should be an exact integer BACKLOG specifies the number of maximally pending connections and defaults to 4 If the optional argument HOST is given and not f then only incoming connections for the given host or IP are accepted 29 2 tcp listener procedure tcp listener X Returns t if X is a TCP
16. procedure procedure data PROCEDURE Returns the data object contained in the extended procedure PROCEDURE or f if it is not an extended procedure 30 3 4 set procedure data procedure set procedure data PROCEDURE X Changes the data object contained in the extended procedure PROCEDURE to X define foo letrec f lambda procedure data x x 4f set x extend procedure f 123 x foo gt 123 set procedure data foo hello foo gt hello 30 4 Data in unmanaged memory 30 4 1 object evict procedure object evict X ALLOCATOR Copies the object X recursively into the memory pointed to by the foreign pointer object returned by ALLOCATOR which should be a procedure of a single argument the number of bytes to allocate The freshly copied object is returned This facility allows moving arbitrary objects into static memory but care should be taken when mutating evicted data setting slots in evicted vector like objects to non evicted data is not allowed It is possible to set characters bytes in evicted strings or byte vectors though It is advisable not to evict ports because they might be mutated by certain file operations object evict is able to handle circular and shared structures but evicted symbols are no longer unique a fresh copy of the symbol is created so define x foo 30 3 2 extended procedure 201 CHICKEN User s Manual The User s Manual define y object evict foo
17. ptr csc Top sch bar c o foo foo This is callout 1 2 3 This is callin 1 2 3 123 38 49 Notes Scheme procedures can call C functions and C functions can call Scheme procedures but for every pending C stack frame the available size of the first heap generation the nursery will be decreased because the C stack is identical to the nursery On systems with a small nursery this might result in thrashing since the C code between the invocation of C from Scheme and the actual calling back to Scheme might build up several stack frames or allocates large amounts of stack data To prevent this it is advisable to increase the default nursery size either when compiling the file using the nursery option or when running the executable using the S runtime option Calls to Scheme C may be nested arbitrarily and Scheme continuations can be invoked as usual but keep in mind that C stack frames will not be recovered when a Scheme procedure call from C does not return normally When multiple threads are running concurrently and control switches from one thread to another then the continuation of the current thread is captured and saved Any pending C stack frame still active from a callback will remain on the stack until the threads is re activated again This means that in a multithreading situation when C callbacks are involved the available nursery space can be smaller than expected So doing many nested SchemeCS
18. 42 5 9 How can I increase the size of the trace shown when runtime errors are detected 271 42 6 EE ee 271 42 6 1 How can I obtain smaller eecutahles eene nennen 271 42 6 2 How can I obtain faster execut bles esses enne enne enn 271 42 6 3 Which non standard procedures are treated specially when the extended bindings or usual integrations declaration or compiler option is sed 272 42 6 4 Can I load compiled code at runtme enne 272 42 7 Garbage collection EE 273 42 7 1 Why does a loop that doesn t cons still trigger garbage collections 273 42 7 2 Why do finalizers not seem to work in simple cases in the interpeter 273 42 8 Interpretet ione etr P Hen e PR GENRES PERI OR RE C O Ue REESE REESE ERE LET RR ba Sep Mea Eye e XE EN re ER aes 274 42 8 1 Does CSI support history and autocompletion essere 274 42 8 2 Does code loaded with load run compiled or wmterprered 274 22 0 EXtOBSIOPBS er e dE EE 274 42 9 1 How can I install Chicken eggs to a non default Location 0 0 eeecceseeceeeeeseeeeeteceeneeeeeeeeaees 274 42 9 2 Can I install chicken eggs as a non root user 275 AS ACK IO WCU SIC NES EET ETT ree ee ee Soe 276 A BIbIloSESDI eege 278 xxii 1 The User s Manual This is the user s manual for the Chicken Scheme compiler version 3 3 0 Getting started What is CHICKEN and how do I use it Basic mode of operatio
19. compiler 9 Visual Studio users will want to install the Unix Utilities available at http www call with current continuation org tarballs UnxUtils zip in order to get suitable versions of make tar gZip and similar commands Refer to the README file for the version you re installing for more information on the installation process 2 5 Development environments The simplest development environment is a text editor and terminal window Windows Command Prompt OSX Terminal Linux Unix xterm for using the interpreter and or calling the compiler If you install the readline egg you have all the benefits of command history in the interpreter Emacs or vi compatible line editing and customization You will need a text editor that knows Scheme it s just too painful with editors that don t do parenthesis matching and proper indentation Some editors allow you to execute Scheme code directly in the editor This makes programming very interactive you can type in a function and then try it right away This feature is very highly recommended 2 4 Installing Chicken 5 CHICKEN User s Manual The User s Manual As programmers have very specific tastes about editors the editors listed here are shown in alphabetic order We aren t about to tell you which editor to use and there may be editors not shown here that might satisfy your needs We would be very interested in reports of other editors that have been used with Chicken especially th
20. file access time FILE procedure file change time FILE procedure file modification time FILE Returns time in seconds of the last access modification or change of FILE FILE may be a filename or a file descriptor If the file does not exist an error is signaled 27 6 4 file stat procedure file stat FILE LINK Returns a 13 element vector with the following contents inode number mode as with file permissions number of hard links uid of owner as with file owner gid of owner size as with file size and access change and modification time as with file access time file change time and file modification time device id device type for special file inode 27 5 10 open output file 157 CHICKEN User s Manual The User s Manual blocksize and blocks allocated On Windows systems the last 4 values are undefined If the optional argument LINK is given and not f then the file statistics vector will be resolved for symbolic links otherwise symbolic links are not resolved Note that for very large files the fi Le Size value may be an inexact integer 27 6 5 file position procedure file position FILE Returns the current file position of FILE which should be a port or a file descriptor 27 6 6 file size procedure file size FILENAME Returns the size of the file designated by FILE FILE may be a filename or a file descriptor If the file does not exist an error is signaled Note that for very large f
21. gc x x define external baz int i double sqrt i return to host cat y c ZE NC include chicken bs include lt assert h gt extern double baz int int main char buffer 256 int status C word val C SCHEME UNDEFINED C word data 1 data 0 aval CHICKEN run C toplevel status CHICKEN read bar 99 amp val assert status C gc protect data 1 printf data 08x n val status CHICKEN eval string to string bar buffer 255 assert status CHICKEN get error message buffer 255 printf ouch s n buffer status CHICKEN eval string to string bar 23 buffer 255 assert status printf gt s n buffer printf data 08x n val status CHICKEN eval to string val buffer 255 assert status printf gt s n buffer printf gt g n baz 22 return 0 34 14 CHICKEN_ yield 227 CHICKEN User s Manual The User s Manual CSC x scm y c embedded It is also possible to re enter the computation following the call to return to host by calling CHICKEN continue 34 15 CHICKEN continue C function C word CHICKEN continue C word k Re enters Scheme execution k is the continuation received from the previous invocation of CHICKEN run or CHICKEN continue When return to host is called again this function returns another continuation that can be used to restart again If you invoke callbacks prior to c
22. in this case saying that the function takes one integer argument the int after the function name and that it returns an integer result the int before Now we can invoke Xf ib as though it were an ordinary Scheme function gcc c fib c csc o fib user fib o fib user scm fib user 01123598 13 21 34 55 Those who are interfacing to substantial C libraries should consider using the easyffi egg or SWIG Back to index html Next Basic mode of operation 2 9 Accessing C libraries 11 3 Basic mode of operation The compiler translates Scheme source code into fairly portable C that can be compiled and linked with most available C compilers CHICKEN supports the generation of executables and libraries linked either statically or dynamically Compiled Scheme code can be loaded dynamically or can be embedded in applications written in other languages Separate compilation of modules is fully supported The most portable way of creating separately linkable entities is supported by so called units A unit is a single compiled object module that contains a number of toplevel expressions that are executed either when the unit is the main unit or if the unit is used To use a unit the unit has to be declareed as used like this declare uses UNITNAME The toplevel expressions of used units are executed in the order in which the units appear in the uses declaration Units may be used multiple times and uses declarations may be circular
23. the value of unbound identifiers the undefined value void and end of file Bits 1 4 are equal to C SPECIAL BITS bits 5 to 8 contain an identifying number for this type of object The following constants are defined C SCHEME END OF LIST C SCHEME UNDEFINED C SCHEME UNBOUND C SCHEME END OF FILE Collectively bits 1 and 2 are known as the immediate mark bits When bit 1 is set the object is a fixnum as described above and bit 2 is part of its value When bit 1 is clear but bit 2 is set it is an immediate object other than a fixnum If neither bit 1 nor bit 2 is set the object is non immediate as described below 40 2 Non immediate objects Non immediate objects are blocks of data represented by a pointer into the heap The pointer s immediate mark bits bits 1 and 2 must be zero to indicate the object is non immediate this guarantees the data block is aligned on a 4 byte boundary at minimum Alignment of data words is required on modern architectures anyway so we get the ability to distinguish between immediate and non immediate objects for free The first word of the data block contains a header which gives information about the type of the object The header has the size of a machine word usually 32 bits 64 bits on 64 bit architectures Bits 1 to 24 contain the length of the data object which is either the number of bytes in a string or byte vector or the the number of elements for a vector or for a structure type Bits 25
24. 10 pointerobject procedure pointer gt object PTR Returns the Scheme object pointed to by the pointer PTR 30 1 5 null pointer 196 CHICKEN User s Manual The User s Manual 30 1 11 pointer offset procedure pointer offset PTR N Returns a new pointer representing the pointer PTR increased by N 30 1 12 pointer u8 ref procedure pointer u8 ref PTR Returns the unsigned byte at the address designated by PTR 30 1 13 pointer s8 ref procedure pointer s8 ref PTR Returns the signed byte at the address designated by PTR 30 1 14 pointer u16 ref procedure pointer ul6 ref PTR Returns the unsigned 16 bit integer at the address designated by PTR 30 1 15 pointer s16 ref procedure pointer sl16 ref PTR Returns the signed 16 bit integer at the address designated by PTR 30 1 16 pointer u32 ref procedure pointer u32 ref PTR Returns the unsigned 32 bit integer at the address designated by PTR 30 1 11 pointer offset 197 CHICKEN User s Manual The User s Manual 30 1 17 pointer s32 ref procedure pointer s32 ref PTR Returns the signed 32 bit integer at the address designated by PTR 30 1 18 pointer f32 ref procedure pointer f32 ref PTR Returns the 32 bit float at the address designated by PTR 30 1 19 pointer f64 ref procedure pointer f64 ref PTR Returns the 64 bit double at the address designated by PTR 30 1 20 pointer u8 set procedure pointer u8 set PTR N procedur
25. 120 20 1 TAKE EE 120 PAESE UT T T T 120 203 SOVECLOLDI NEEDED a Ee Cadde Ae e 120 DOA UI OVECCOEDIOD RTT TIT UE vdua sy va unes ao dansk sao avanbontaraberabacgeawanscneeaaneseenenes 120 20 5 LOVECLOLDIOD EE 120 STE RA ele 120 2O ASS Le 121 20 8 132vectorDlob E 121 20 9 f64 vectorbloD cei teet a taco ot e eoa ede EDT OE Ev ee e ERA EDEN ee 121 20 10 u xvectorblob ebhared nennen neneneme e emen nemen n nnn nnne sn E E a 121 20 11 s vectorblobicbhared nennen emememe meme menn n n nnne n iei eia 121 20 12 lovectorblob shated epi aeree reet tra br neu RE ex ae EUR Du ve ERR Pee epe ENE 121 20 13 sT6yvectorblob shared ier rrt tero pote veda eee Doe ea got e Eee Eve AER DER SOR PA suds ERA CE Deve Cu RN R C vR REN ud 121 20 14 u ivectorblob ehared nennen emen nemen meme e enn EEEN KONSE ais 121 20 15 s32vectorblob shared uieceess erede ovo e aeo dva avo tour a tua err eth n n EK PER EY REX Ema HEY AER 121 20 16 P32 VeECtOrblOb Shared DE 121 20 17 fo4vectorblob shared 2 ina a cacssadeseseiacevesstesvess ta ere es Tea PRI ER ERRAT X CREER ER TUR LR pa ERR CHR Ra Gv 121 20 18 DIObDUS ESIOEEITT TD TT UU mM 122 GAB e re 122 20 20 blobulOVectotL su eer ere rere cued ee berries 65 ep sass ons aee E oa eap cree Ee Rege NER ERE EE ER RREAE 122 20 21 DIODSTOVE E EE 122 20 22 DIOHUS2ZVECCOF EE 122 20 23 DIODSS ZV ECON EE 122 20 24 DIODIS TE 122 20 25 DIODIG4AVECIOR EE 123 20 26 blobu vectotiebared rirerire aaa EEEE SEE E
26. 186 28 2 10 pathname replace CXteMSlON eene enne ennt tenni netten nene 186 28 2 11 pathname strip directory iiiter rette nee tert aeta cet ee erae HR n ene eate He Ee aee aed 186 28 2 12 pathname stup extension enne enne enter ENE EE EEE inen enne 186 28 2 1 3 directory RUN 186 28 3 T mporary tiles o ie EE ER E P EE EEA EE EEE A TET EEE 186 E Eu TE EE 187 28 4 Deleting a file without signalling an error ennemi terere nns 187 25 4 L delete le oro Ee ee Ce aun EE 187 28 5 File INO VE RC M 187 PB En ET T 187 25 5 2 EU ue 187 28 6 Iterating over input lines and les 188 28 6 1 for e ch lifie id ee erret re roe Zeg ins pave ug ov vo unes TRO EE RO eege ER Ee RE Pe vue eve VN HERES 188 ere EE TEE 188 28 7 Executing shell commands with formatstring and error checkg esee 188 PME BE E 188 28 5 Reading BE EE 188 GEI EP oisinn niea a a e a e aA saavaud Sunda cavataceraverssdanvacebhareaceeasaees 189 ZO TEE rrn n A TN T Ga Te Te 190 EE EE 190 29 2 tcp liSten r EE 190 29 9 tCD ClOSE reote Icom E E E E E E 190 20 4 e E 190 Re dE LE 191 29 6 tcp list n r port aste ett erii Age avi ivenscdantecduaecednestevaanaaaesdaesesdencrersivdacevaacese 191 29 T tep liste er ET 191 XV CHICKEN User s Manual The User s Manual Chicken User s Manual 29 Unit tcp ee 191 20 0 tcp ad
27. 3016 3 ALO Br I ER E AE A E E E E A 204 30 7 Ee EE 205 307l de NIU TITIUS 205 30 7 2 ee 205 DOT SOD ICC COP Ne ebe 205 30 7 4 make record instance ccccccccccccccccccececccccccscsesescseseeesessseseseseccccceececeeseaeaeasaeaeeeaeaesceeeceeess 205 30 7 5 MOVE MEMOLY EE 206 30 7 6 number of Dyt s EE 206 3057 7 ii tuniere mE 206 30 7 S EECH ENEE EE 206 LUNA MO SERT ITI UI 206 30 8 Procedure call and variable reference books 207 30 8 1 set invalid procedure call handler essere 207 30 8 2 onbound varable value eene nennen nemen mener n nn in inn n nnns asses sess seen 207 30 9 Magic E 207 30 9 l ObjeCt DeCOme ELE 207 30 9 2 m tate procedUute sesdersahsadedadscdiatsestecesaseecacasstee ssnteeensivensensdadierssdesinsadenecensddeesaatesttesedetevnansan 208 31 Interface to external functions and Variables scccsssscccsssscccsssssccssssccccsssscccesssccecessccecessscccscssceecess 209 32 ACCESSING external oeb eofs au aiio pp E EREUREREEERE EUER EE HU EREEREEM SER RREREE EUR EE REERE HERE uae EAE AFER ER EUUR 210 32 Toreigne code E 210 SMOD G 210 32 3 RENE EE 210 32 A CEMNE TOTEIOM LY PO caetstevsissizasssdacensnscsudvsnsieessndesavansadedenndeass sepodGenededeevnnd eauninsateauancdanvardetceslaveevaaasan 210 SE RETTEN EE 211 32 6 detine forelen reCOEd 5 oerte ER HOT EE gis REPRE ET E EE EEEE T
28. 33 17 MOMMUTL BL OD EE 219 33 18 u8vector ul 6vector u32vector s8vector sl6vector s32vector f32vector T hvectot 219 33 19 nonnull u8vector nonnull ul 6vector nonnull u32vector nonnull s8vector nonnull s16vector nonnull s32vector nonnull f32vector nonnull f64vector 220 KEE UE 220 33 21 nonn ll C SttTtig e reor eee ere nr rH gea eee denen e eei ined e aea e ee UI eaae eate Eee ela Veo i vua eun 220 33 22 nonnull ER 220 33 23 nonnull unsigned c string eseeeseeseeeseeeee ener ener enne 220 SERA Hei uM PEINE EE 220 33 25 csstring EE 221 33 2O VOI ERROR TEE 221 332 const E GA Fal EE 221 33 28 enum NAMB E 221 33 29 c pointer LY UE 221 33 30 e RUE enk det e dE 221 33 3l tet TYPE EE 221 33 32 Strict NAME Jc EE 222 33 33 template TY PE ARGTY PE e eise eee cett eoe dede Pee eie ense en eden e loeo on na eta 222 33 34 mon E EE 222 33 35 instance CNAME SCHEMECT ASS 222 23 20pGnstance refCNAMESCHEMECL ASS 222 33 37 function RESULTTYPE ARGUMENTTYPE1 CALLCONY enne 222 EE TEE 223 H Embed TI T m 224 34 1 CHICKEN parse command Je 224 34 2 CHICKEN ifitialiZe beer ettet eege ti eie ees 224 34 3 CHICKEN fim rinin EE 224 SE EE e EE 225 34 5 CHICKEN valoisa ee ENEE Se NEE ed Sech eu 225 34 6 CHICKEN eval Stein E 225 34 7 CHICKEN Vall e EE 225 34 8 CHICKEN eval string to SIN eseri eroe Eees eene eene enne nnno nne etn tenente a e st en
29. 47 55 57 60 63 66 69 72 78 85 and 95 Lightweight threads based on first class continuations Pattern matching with Andrew Wright s match package Record structures Extended comment and string literal syntaxes e Libraries for regular expressions string handling UNIX system calls and extended data structures Create interpreted or compiled shell scripts written in Scheme for UNIX or Windows Compiled C files can be easily distributed Allows the creation of fully self contained statically linked executables On systems that support it compiled code can be loaded dynamically Chicken has been used in many environments ranging from embedded systems through desktop machines to large scale server deployments The number of language extensions or eggs will soon reach 400 including extended language features development tools such as documentation generators debugging and automated testing libraries e interfaces to other languages such as Java Python and Objective C 2 2 Chicken CHICKEN User s Manual The User s Manual e interfaces to database systems GUIs and other large scale libraries network applications such as servers and clients for ftp smtp pop3 irc and http web servers and related tools including URL parsing HTML generation AJAX and HTTP session management data formats including XML JSON and Unicode support Chicken is supported by SWIG Simplified Wrapper and Interface Gen
30. AR e SEE 68 14 1 2 Binary ite Ser e EE 68 IN EUER RE 68 LA Sb EARN RR TT E 68 14 1 5 Arithmetic fixnum Operations enne ennt nenen terrens 69 14 1 6 Arithmetic floating point operatons eene 69 VA er e HA 70 EE SE 70 14 2 File Input Output E 70 14 2 1 current outp tspOFt EE 70 14 2 2 Cure mt errOr E 70 14 2 3 tl sh zOUtpUt EE 70 14 2 4 e EE 71 14 2 5 port poSIHOn TE 71 I BAM iar i EEA UTEM E E E 71 E B T LERES E EA S A E O A TE EA AET E T EST O EN 71 143 l Cle ete TE 71 143 2 AE ENEE 71 1453 5 EE 72 14 4 Siint e E 72 14 4 1 Pet OUIPUTES RT 72 14 4 2 TEE Ee 72 14 4 3 OPEN OUUDULES RE 72 14 5 Feature WERT EE 72 14 5 1 TEAMS S 2 estere teint Dae e Pa tendo odds veda v IR EU entered rite dea PE POI EBD 73 GE 73 E WE E 73 14 SEET 73 14 6 Rey wOrdS 53 teta o er ERR EE REX X ERR ap Rege E RE E TRETEN S sas E T EEEE aSa 73 14 6 1 S6t KEY ERE 73 I See 74 IC See 74 14 64 StriN SKEV Word ITI 74 14 7 EX CE D EL E 74 14 71 ere Aer Ee 74 E Ee RT E 75 14 8 Environment information and system Interface He UE WT He IGNES UNERETERHTT He E Wee EE TT 14 8 4 Chic E TT TT ER RONE NEEDED UTE TT JU Meu A EA ES TT iv CHICKEN User s Manual The User s Manual Chicken User s Manual 14 Unit library UE WEE TEE TT 14 8 8 m chime typa eiie tert Da e ERE LEER EO CERES GEAR EO TELF in ee
31. EE 266 42 3 1 How do I run custom startup code before the runtime system is Ipvoked 267 42 3 2 How can I add compiled user pass entente 267 42 Aert EE re EE 268 42 4 1 Why is define macro complaining about unbound vapables sess 268 42 4 2 Why isn t load properly loading my library of macros 268 42 4 3 Why is include unable to load my hygienic maCrOs sese 268 xxi CHICKEN User s Manual The User s Manual Chicken User s Manual 42 FA 42 4 4 Why are macros not visible outside of the compilation unit in which they are defined 268 42 5 Warnings Be CT 268 42 5 1 Why does my program crash when I use callback functions from Scheme to C and back tO Scheme ADANY orreee eee E EE ate eaten E E E EEE NE E A 268 42 5 2 Why does the linker complain about a missing function C toplevel 269 42 5 3 Why does the linker complain about a missing function C toplevel 269 42 5 4 Why does my program crash when I compile a file with unsafe or unsafe declarations 269 42 5 5 Why do I get a warning when I define a global variable named match 269 42 5 6 Why don t toplevel continuations captured in interpreted code work 270 42 5 7 Why does define reader ctor not work in my compiled program 270 42 5 8 Why do built in units such as srfi 1 srfi 18 and posix fail to load 270
32. EOE NEEE E EEES EEEE ASEE 1 16 5 A SIN e E 1 16 5 5 string compare enient oiie iaiia iin i tied Vase ee E i a oaa en 1 eer E 1 e ERT EE 1 16 5 9 string translate iio reiten YR ee Ee one YS ESSERE eR SNR EUER UC RURP ER EN NERO ores E Ex e dR 1 16 59 string translate ruere ert ertet ert ende ehe ee veedndandua es vide an eade ed eate Eee aa eve vadens 1 e EN AR Hee 1 ef EN WE Hee E 1 16 6 WE 1 ege 1 16 62 EE 1 16 6 3 Tu EE 1 16 64 COMPOSE coe Ito reto tege iae eerie Seek ene eua ashes seen Uses esae aua etd eire ea Pee nhau ted esae h RES 1 16 6 5 COM OI EE 1 16 6 6 CIS OL EE 1 16565 ECAC EEN 1 eet 1 Vil CHICKEN User s Manual The User s Manual Chicken User s Manual 16 Unit data structures 16 6 9 EE EE 108 16 6 10 ere E 108 16 6 RB EECH 108 166 PAIRE 108 1G 6 EEN 108 1627 Binary Sar UE 109 ee WE E e NEE 109 k n E 110 17 1 Input output port extensions ee eccccesceceeeessecessaeceeaeeeeaeeceeecaeeeeaaeceeneceeeeeceaeesaeceeaaeceaeeceeeeees 110 17 1 1 Ee een 110 17 1 2 make impu tzpott ee coe tre daienedusecachsasns ta tadedcalegedeesudivawesssuueneassteueaed ene e x EE RR HS 110 17 1 3 make output pott 11 23 c enitn tetti eae eed de het e nete Ree ee pneus 110 17 1 4 wtb eror output to p0ort enne enene enne nenen tenens 110 17 1 5 withzinput from port 5 ettet reete nete ene teet eene ena i de ean a das 111 17 2 reen Ee E 111 REN RE EE EE 111 17 2 2 call with output Sttitig
33. FILE OR PORT If no argument is given input is read from the port that is the current value of current input port After all expressions are read and if the argument is a port then the port will not be closed The READER argument specifies the procedure used to read expressions from the given file or port and defaults to read The reader 18 2 3 randomize 116 CHICKEN User s Manual The User s Manual procedure will be called with a single argument an input port If MAXCOUNT is given then only up to MAXCOUNT expressions will be read in 18 3 6 read line 18 3 7 write line procedure read line PORT LIMIT procedure write line STRING PORT Line input and output PORT defaults to the value of Current input port and current output port respectively If the optional argument LIMIT is given and not f then read Line reads at most LIMIT characters per line read Line returns a string without the terminating newline and write line adds a terminating newline before outputting 18 3 8 read lines procedure read lines PORT MAX Read MAX or fewer lines from PORT PORT defaults to the value of Current input port PORT may optionally be a string naming a file Returns a list of strings each string representing a line read not including any line separation character s 18 3 9 read string 18 3 10 read string 18 3 11 write string procedure read string NUM PORT procedure read stri
34. If the first argument is a symbol then this procedure is equivalent to set read syntax 14 22 5 copy read table procedure copy read table READ TABLE Returns a copy of the given read table You can access the currently active read table with current read table 14 22 2 set read syntax 89 CHICKEN User s Manual The User s Manual 14 23 Property lists As in other Lisp dialects CHICKEN supports property lists associated with symbols Properties are accessible via a key that can be any kind of value but which will be compared using eq 14 23 1 get procedure get SYMBOL PROPERTY DEFAULT Returns the value stored under the key PROPERTY in the property list of SYMBOL If no such property is stored returns DEFAULT The DEFAULT is optional and defaults to f 14 23 2 put procedure put SYMBOL PROPERTY VALUE setter set get SYMBOL PROPERTY VALUE Stores VALUE under the key PROPERTY in the property list of SYMBOL replacing any previously stored value 14 23 3 remprop procedure remprop SYMBOL PROPERTY Deletes the first property matching the key PROPERTY in the property list of SYMBOL Returns t when a deletion performed and f otherwise 14 23 4 symbol plist procedure symbol plist SYMBOL setter set symbol plist SYMBOL LST Returns the property list of SYMBOL or sets it 14 23 5 get properties procedure get properties SYMBOL PROPERTIES Searches the property list of SYMBOL
35. RGB color syntax set read syntax 14 21 Setters 88 CHICKEN User s Manual The User s Manual Lambda port apply vector map cut string gt number lt gt 16 string chop read string 6 port 2 with input from string 1 2 fOfO0fO 3 read gt 1 2 240 240 240 3 If CHAR OR SYMBOL is a symbol then a so called read mark handler is defined In that case the handler procedure will be called when a character sequence of the form SYMBOL is encountered You can undo special handling of read syntax by passing f as the second argument if the syntax was previously defined via set read syntax Note that all of CHICKEN s special non standard read syntax is handled directly by the reader To disable built in read syntax define a handler that triggers an error for example 14 22 3 set sharp read syntax procedure set sharp read syntax CHAR OR SYMBOL PROC Similar to set read syntax but allows defining new lt CHAR gt reader syntax If the first argument is a symbol then this procedure is equivalent to set read syntax 14 22 4 set parameterized read syntax procedure set parameterized read syntax CHAR OR SYMBOL PROC Similar to set sharp read syntax but intended for defining reader syntax of the form lt NUMBER gt lt CHAR gt The handler procedure PROC will be called with two arguments the input port and the number preceding the dispatching character
36. The names that should not be rebound or shadowed are null pair number string symbol boolean char procedure vector list equal car cdr cadr cdddr vector length vector ref reverse length call cc Additionally the code generated to match a structure pattern like Foo pat 1 pat n refers to the name Foo This name also should not be shadowed Previous Non standard macros and special forms Next Declarations 11 5 Code Generation 57 12 Declarations 12 1 declare syntax declare DECLSPEC Process declaration specifiers Declarations always override any command line settings Declarations are valid for the whole compilation unit source file the position of the declaration in the source file can be arbitrary Declarations are ignored in the interpreter but not in code evaluated at compile time by eval when or in syntax extensions loaded via require extension or require for syntax DECLSPEC may be any of the following 12 2 always bound declaration specifier always bound SYMBOL Declares that the given variables are always bound and accesses to those have not to be checked 12 3 block declaration specifier block Assume global variables are never redefined This is the same as specifying the block option 12 4 block global 12 5 hide declaration specifier block global SYMBOL declaration specifier hide SYMBOL Declares that the toplevel bindings for SYMBOL shou
37. User s Manual 30 5 5 locative set procedure locative set LOC X procedure set locative ref LOC X Changes the element to which the locative LOC refers to X If the containing object has been reclaimed by garbage collection an error is signalled 30 5 6 locativeobject procedure locative gt object LOC Returns the object that contains the element referred to by LOC or f if the container has been reclaimed by garbage collection 30 6 Accessing toplevel variables 30 6 1 global bound procedure global bound SYMBOL Returns t if the global toplevel variable with the name SYMBOL is bound to a value or f otherwise 30 6 2 global ref procedure global ref SYMBOL Returns the value of the global variable SYMBOL If no variable under that name is bound an error is signalled Note that it is not possible to access a toplevel binding with global ref or global set if it has been hidden in compiled code via declare hide orif the code has been compiled in block mode 30 6 3 global set procedure global set SYMBOL X procedure set global ref SYMBOL X Sets the global variable named SYMBOL to the value X 30 5 5 locative set 204 CHICKEN User s Manual The User s Manual 30 7 Low level data access 30 7 1 block ref procedure block ref BLOCK INDEX Returns the contents of the INDEXth slot of the object BLOCK BLOCK may be a vector record structure pair or symbol 30 7 2
38. a call to Load the code will be loaded at runtime and if the file loaded is a Scheme source code file instead of a shared object it will be interpreted even if the caller program is compiled 42 9 Extensions 42 9 1 How can install Chicken eggs to a non default location You can just set the CHICKEN REPOSITORY environment variable It should contain the path where you want eggs to be installed export CHICKEN REPOSITORY chicken chicken setup extensionname In order to make programs including csi see these eggs you should set this variable when you run them Alternatively you can call the repository path Scheme procedure before loading the eggs as in repository path home azul chicken use format modular Note however that using repository path as above hard codes the location of your eggs in your source files While this might not be an issue in your case it might be safe to keep this configuration outside of the source code that is specifying it as an environment variable to make it easier to maintain 42 8 Interpreter 274 CHICKEN User s Manual The User s Manual 42 9 2 Can install chicken eggs as a non root user Yes just install them in a directory you can write Previous Bugs and limitations Next Acknowledgements 42 9 2 Can I install chicken eggs as a non root user 275 43 Acknowledgements Many thanks to Nico Amtsberg William Annis Marc Baily Peter Barabas Jonah Beckford Arto
39. a flat closure representation is used flonums a byte vector object type bits C FLONUM BITS Slots one and two or a single slot on 64 bit architectures contain a 64 bit floating point number in the representation used by the host systems C compiler symbols a vector object type bits C SYMBOL TYPE Slots one and two contain the toplevel variable value and the print name a string of the symbol respectively ports a special vector object type bits C PORT TYPE The first slot contains a pointer to a file stream if this is a file pointer or NULL if not The other slots contain housekeeping data used for this port structures a vector object type bits C STRUCTURE TYPE The first slot contains a symbol that specifies the kind of structure this record is an instance of The other slots contain the actual record items pointers a special vector object type bits C POINTER TYPE The single slot contains a machine pointer tagged pointers similar to a pointer type bits C TAGGED POINTER TYPE but the object contains an additional slot with a tag an arbitrary data object that identifies the type of the pointer Data objects may be allocated outside of the garbage collected heap as long as their layout follows the above mentioned scheme But care has to be taken not to mutate these objects with heap data i e non immediate objects because this will confuse the garbage collector For more information see the header file chi
40. and special forms 10 1 Making extra libraries and extensions available 10 1 1 require extension syntax require extension ID syntax use ID This form does all the necessary steps to make the libraries or extensions given in ID available It loads syntactic extensions if needed and generates code for loading linking with core library modules or separately installed extensions USE is just a shorter alias for requi re extension This implementation of require extension is compliant with SRFI 55 see the SRFI 55 document for more information During interpretation evaluation requi re extension performs one of the following If ID names a built in feature chicken srfi 0 srfi 2 srfi 6 srfi 8 srfi 9 srfi 10 srfi 17 srfi 23 srfi 30 srfi 39 srfi 55 then nothing is done e If ID names one of the syntactic extensions chicken more macros chicken ffi macros then this extension will be loaded o If ID names one of the core library units shipped with CHICKEN then a Load library ID will be performed o If ID names an installed extension with the syntax or require at runtime attribute then the equivalent of require for syntax ID is performed probably followed by require for any run time requirements Otherwise require extension ID is equivalent to require ID During compilation one of the following happens instead If ID names a built in feature chicken srfi 0 srfi 2 srfi 6 srfi 8 srfi 9 srfi 1
41. as Load foo so and run CSC shared Top sch to produce foo so from foo scm at which point foo scm will no longer be required 42 7 Garbage collection 42 7 1 Why does a loop that doesn t cons still trigger garbage collections Under CHICKENs implementation policy tail recursion is achieved simply by avoiding to return from a function call Since the programs are CPS converted a continuous sequence of nested procedure calls is performed At some stage the stack space has to run out and the current procedure and its parameters including the current continuation are stored somewhere in the runtime system Now a minor garbage collection occurs and rescues all live data from the stack the first heap generation and moves it into the the second heap generation Then the stack is cleared using a Long j mp and execution can continue from the saved state With this method arbitrary recursion in tail or non tail position can happen provided the application doesn t run out of heap space The difference between a tail and a non tail call is that the tail call has no live data after it invokes its continuation and so the amount of heap space needed stays constant 42 7 2 Why do finalizers not seem to work in simple cases in the interpeter Consider the following interaction in CSI 1 gt define x 1 2 3 2 gt define yammer x print x is dead 3 gt set finalizer x yammer 12 3 4 gt gc Zt 157812 5
42. available options The accumulate profile option is similar to profile but the resulting profile information will be appended to any existing PROFILE file chicken profile will merge and sum up the accumulated timing information if several entries for the same procedure calls exist profile name FILENAME Specifies name of the generated profile information which defaults to PROFILE Implies profile prologue FILENAME Includes the file named FILENAME at the start of the compiled source file The include path is not 4 1 Compiler command line format 16 CHICKEN User s Manual The User s Manual searched This option may be given multiple times quiet Disables output of compile information raw Disables the generation of any implicit code that uses the Scheme libraries that is all runtime system files besides runtime c and chicken h require extension NAME Loads the extension NAME before the compilation process commences This is identical to adding require extension NAME at the start of the compiled program If uses NAME is also given on the command line then any occurrences of require extension NAME are replaced with declare uses NAME Multiple names may be given and should be separated by run time macros Makes macros also available at run time By default macros are not available at run time to stdout Write compiled code to standard output instead of creating a C file unit NAME Compile this file as a library
43. backslash in quoted string constants V denotes the newline character V carriage return V backspace V TAB V vertical TAB Va alarm Y formfeed WXX a character with the code XX in hex and wXXXX and UXXXXXXXX a unicode character with the code XXXX The latter is encoded in UTF 8 format The third argument to subst ring is optional and defaults to the length of the string 6 4 force called with an argument that is not a promise returns that object unchanged Captured continuations can be safely invoked inside before and after thunks of a dynamic wind form and execute in the outer dynamic context of the dynamic wind form Implicit non multival continuations accept multiple values by discarding all but the first result Zero values result in the continuation receiving an unspecified value Note that this slight relaxation of the behaviour of returning mulitple values to non multival continuations does not apply to explicit continuations created with call with current continuation 6 5 The second argument to eval is optional and defaults to the value of interaction environment scheme report environment and nul l environment accept an optional 2nd parameter if not f which is the default toplevel bindings to standard procedures are mutable and new toplevel bindings may be introduced 6 6 The tilde character is automatically expanded in pathnames Additionally if a pathname starts with VARIABLE then the prefix is rep
44. block set procedure block set BLOCK INDEX X procedure set block ref BLOCK INDEX X Sets the contents of the INDEXth slot of the object BLOCK to the value of X BLOCK may be a vector record structure pair or symbol 30 7 3 object copy procedure object copy X Copies X recursively and returns the fresh copy Objects allocated in static memory are copied back into garbage collected storage 30 7 4 make record instance procedure make record instance SYMBOL ARG1 Returns a new instance of the record type SYMBOL with its slots initialized to ARG1 To illustrate define record point x y expands into something quite similar to begin define make point x y make record instance point x y define point x and record instance x eq point block ref x 0 define point x p block ref p 1 30 7 Low level data access 205 CHICKEN User s Manual The User s Manual define point x set p x block set p 1 x define point y p block ref p 2 define point y set p y block set p 1 y 30 7 5 move memory procedure move memory FROM TO BYTES FROM OFFSET TO OFFSET Copies BYTES bytes of memory from FROM to TO FROM and TO may be strings primitive byte vectors SRFI 4 byte vectors see ref Unit srfi 4 memory mapped files foreign pointers as obtained from a call to foreign lambda for example or locatives if BYTES is not given and the size of the source or
45. by compiler Marc Feeley pretty printer Aubrey Jaffer implementation of dynamic wind Richard O Keefe sorting routines Olin Shivers implementation of Let optionals and reference implementations of SRFI 1 SRFI 13 and SRFI 14 43 Acknowledgements 276 CHICKEN User s Manual The User s Manual Andrew Wilcox queues Andrew Wright pattern matcher Alex Shinn scheme complete el emacs tab completion Previous FAQ Next Bibliography 43 Acknowledgements 277 44 Bibliography Henry Baker CONS Should Not CONS Its Arguments Part II Cheney on the M T A http home pipeline com hbaker1 CheneyMTA html Revised 5 Report on the Algorithmic Language Scheme http www schemers org Documents Standards R5RS Previous Acknowledgements 44 Bibliography 278
46. declaration specifier unused SYMBOL Disables any warnings when the global variable SYMBOL is not defined but used or defined but never used and not exported 12 35 uses declaration specifier uses SYMBOL Gives a list of used library units Before the toplevel expressions of the main module are executed all used units evaluate their toplevel expressions in the order in which they appear in this declaration If a library unit A uses another unit B then B s toplevel expressions are evaluated before A s Furthermore the used symbols are registered as features during compile time so cond expand knows about them Previous Pattern matching Next Parameters 12 33 unsafe 64 13 Parameters Certain behavior of the interpreter and compiled programs can be customized via parameters where a parameter is a procedure of zero or one arguments To retrieve the value of a parameter call the parameter procedure with zero arguments To change the setting of the parameter call the parameter procedure with the new value as argument define foo make parameter 123 foo gt 123 foo 99 foo gt 99 Parameters are fully thread local each thread of execution owns a local copy of a parameters value CHICKEN implements SRFI 39 13 1 make parameter procedure make parameter VALUE GUARD Returns a procedure that accepts zero or one argument Invoking the procedure with zero arguments returns VALUE Invoki
47. ee TEE 27 BEE ee RE 28 5 7 Auto completion and Cditiom EE 28 Se Eu E Te 28 Re BUSES ioi diee tie repens T nd I M I MUN MI quM E M ME 30 T Deviations from the Stondai liue oaov ero curre tak eU bc rE FEkK HE PEEVE THEE EYE SEE PEE y C EE IEEE SEE MERE U EE PERYESE PERUESEE SEEK UE MKEKUEPEE 31 Extensions to thre SAM CLE 33 D NO rer POA E 37 9 1 Multiline Block ert EE 37 9 2 Expression Otter edd i ede ene E SE e eee eR e Ee CERE ENEE EEN 37 9 3 EORR SIENTE 37 OLA Syntax TEE E 37 9 5 Location er 37 9 0 AORTA 38 9 7 Multiline String Constant etit ere eorr ina eese enne rae eoe Rees eaae n ege RE a xaT e eR RES 38 9 8 Multiline String Constant with Embedded Expressions essent 38 9 9 Foreign RE E 39 9 10 Sharp Prefixed Symbol ertet tete tee tiet te Pure eH ERR ENEE ee 39 I TISBaBe soror needs E 39 CHICKEN User s Manual The User s Manual Chicken User s Manual 9 Non standard read syntax 9 1 iG ere EE 39 9 11 2 Bot OD Ject io oo erre PEOR HU GRE SHEER HEU GEO UG ERAS OR RED IR 39 9 11 3 DSSSL Formal Parameter List Anpnotaton nnn 39 9 11 4 Read Mark Inxvoecapon enne nemen nnne ene REKE EEEE 39 VEER e A0 9 13 Case Insensitive E e sauneeciecsvunagayeetones ERE CREER AREE YRE ESTEE NE ERE EE R 40 9 14 Conditional EE ET EE A0 10 Non standard macras and Special formigi eronsa erger 41 10 1 Making extra libraries and extensions available 41 10 1 1 et E e 41 10 12 EE 42 10 2 Binding
48. environment CHICKEN is free and can be freely distributed including its source code CHICKEN offers better performance than nearly all interpreter based implementations but still provides full Scheme semantics As far as we know CHICKEN is the first implementation of Scheme that uses Henry Baker s Cheney on the M T A concept 42 1 2 Why call it Chicken According to felix Well it s pretty boring really when I started the project and needed some name the first thing that met my eyes was the chicken actually a disguised penguin from the Wallace Gromit movie And then there is of course the ever occurring chicken and egg problem with bootstrapped compilers 42 1 3 What should do if find a bug Send e mail to felix 9 call with current continuation org with some hints about the problem like version build of the compiler platform system configuration code that causes the bug etc 42 FAQ 262 CHICKEN User s Manual The User s Manual 42 1 4 Why are values defined with define foreign variable or define constant Or define inline not seen outside of the containing source file Accesses to foreign variables are translated directly into C constructs that access the variable so the Scheme name given to that variable does only exist during compile time The same goes for constant and inline definitions The name is only there to tell the compiler that this reference is to be replaced with the actual value 4
49. fault 27 18 12 errno busy 27 18 13 errno notdir 27 18 14 errno isdir 27 18 15 errno inval 27 18 16 errno mfile 27 18 17 errno nospc 27 18 18 errno spipe 27 18 19 errno pipe 27 18 20 errno again 27 18 21 errno rofs 27 18 11 errno fault 176 CHICKEN User s Manual The User s Manual 27 18 22 errno exist 27 18 23 errno wouldblock These variables contain error codes as returned by errno 27 19 Finding files 27 19 1 find files procedure find files DIRECTORY PREDICATE ACTION IDENTITY LIMIT Recursively traverses the contents of DIRECTORY which should be a string and invokes the procedure ACTION for all files in which the procedure PREDICATE is true PREDICATE may me a procedure of one argument or a regular expression string ACTION should be a procedure of two arguments the currently encountered file and the result of the previous invocation of ACTION or if this is the first invocation the value of IDENTITY ACTION defaults to cons IDENTITY defaults to LIMIT should be a procedure of one argument that is called for each nested directory and which should return true if that directory is to be traversed recursively LIMIT may also be an exact integer that gives the maximum recursion depth For example a depth of H means that only files in the top level specified directory are to be traversed In this case all nested directories are ignored LIMIT may also be f the default which is equivalent
50. first will become the next runnable thread The dynamic environment of a thread consists of the following state The current input output and error port The current exception handler The values of all current parameters created by make parameter Any pending dynamic wind thunks The following procedures are provided in addition to the procedures defined in SRFI 18 26 1 thread signal procedure thread signal THREAD X This will cause THREAD to signal the condition X once it is scheduled for execution After signalling the condition the thread continues with its normal execution 26 2 thread quantum procedure thread quantum THREAD Returns the quantum of THREAD which is an exact integer specifying the approximate time slice of the thread in milliseconds 26 Unit srfi 18 144 CHICKEN User s Manual The User s Manual 26 3 thread quantum set procedure thread quantum set THREAD QUANTUM Sets the quantum of THREAD to QUANTUM 26 4 thread suspend procedure thread suspend THREAD Suspends the execution of THREAD until resumed 26 5 thread resume procedure thread resume THREAD Readies the suspended thread THREAD 26 6 thread wait for i o procedure thread wait for i o FD MODE Suspends the current thread until input MODE is input output MODE is output or both MODE is ZZ al Dis available FD should be a file descriptor not a port open for input or output r
51. for the cdr Vectors have one slot for each element 38 38C u i car C macro C word C u i car C word x 38 39 C u i cdr C macro C word C u i cdr C word x Aliases for C block item x andC block item x 1 respectively 38 40 C data pointer C macro void C data pointer C word x Returns a pointer to the data section of a non immediate Scheme object 38 35 C header size 241 CHICKEN User s Manual The User s Manual 38 41 C_make_header C macro C word C make header C word bits C word size A macro to build a Scheme object header from its bits and size parts 38 42 C_mutate C function C word C mutate C word slot C word val Assign the Scheme value val to the location specified by slot If the value points to data inside the nursery the first heap generation then the garbage collector will remember to handle the data appropriately Assigning nursery pointers directly will otherwise result in lost data Note that no copying takes place at the moment when C mutate is called but later at the next minor garbage collection 38 43 C symbol value C macro C word C symbol value C word symbol Returns the global value of the variable with the name Symbol If the variable is unbound C SCHEME UNBOUND is returned You can set a variable s value with C mutate amp C symbol value SYMBOL VALUE 38 44 C gc protect C function void C gc protect C word ptrs int n Registers n variables at address
52. foreign variable defined by define foreign variable define external foo int 42 foreign lambda int C return foo gt 42 Note don t be tempted to assign strings or bytevectors to external variables Garbage collection moves those objects around so it is very bad idea to assign pointers to heap data If you have to do so then copy the data object into statically allocated memory for example by using obj ect evict Results of type scheme object returned by define external are always allocated in the secondary heap that is not in the stack 35 Callbacks 231 CHICKEN User s Manual The User s Manual 35 2 C_callback C function C word C callback C word closure int argc This function can be used to invoke the Scheme procedure closure argc should contain the number of arguments that are passed to the procedure on the temporary stack Values are put onto the temporary stack with the C save macro 35 3 C callback adjust stack C function void C callback adjust stack C word ptr int size The runtime system uses the stack as a special allocation area and internally holds pointers to estimated limits to distinguish between Scheme data objects inside the stack from objects outside of it If you invoke callbacks at wildly differing stack levels these limits may shift from invocation to invocation Callbacks defined with define external will perform appropriate adjustments automatically but if you invoke C call
53. forms for optional arguments siseenergia es ii ii oiiaii 43 UA WETTER 43 102 2 Case lambda sssssdeveccsasacavarese twee EAEE saasbusdeasacavesuads uuuvads tawaddeateeadeneeneees 43 10 2 3 NET EE 43 10 2 4 A Gelee EE 44 10 3 Other binding CT E 44 103 RE DE EE 44 AR 2 E 44 LU Se E EA EE 44 103 4 define LEE 45 103 5 SR re EE 45 10 3 6 let Vales EE 45 10 3 SME E 45 10 38 Ne 45 ILE EMSISESBERETOEOEOOIISLOSLON ELE 46 LASS ASSERIT TT UU 46 TOS E e BERGER UR EE E 46 10 4 Substitution forms and mac 46 AE EE 46 104 2 E EE 47 10 4 5 define TidefO EE 47 10 44 define forssynt x oreet ede davuaciansaneasaycosaseannc ed E ORAE RENTRER ERAN dS 47 10 5 Conditional CURES gie See EENEG EEGENEN 47 LA WT 48 10 5 2 MIMICS Ss ee E E 48 10 5 3 WHEN EE 48 10 6 Record str ct res E e 48 10 6 Ve fime LECOT EE 48 10 6 2 Gefine record printer innere rt rer et eut erred kdo ee daupeleudssayebeesctecddeesdiadvextdedses 49 10 6 3 defime record type dose e ee EHE PO Ea GRE POR EGRE ER UR daa eee E Ha EUER edd 40 10 7 Other POMS oec iori eet ett ener etcetera reca Pese eoo Dat edd 49 IUVARET MM 40 10 7 2 COMA EX PAN E 50 MARLEN E E EE ES SE E E 50 10 74 eva NEE 50 10 75 MCAS eesieriseeriieeroriei eas oiia EE T E EEE EEEO TON ENEAS E EEEE ANE 51 IOT Oni vae e Ee e E e a EE e 51 TOT UE rrer ninen ria a de vag days vasa E A E a EEE E N EEEE 51 CHICKEN
54. gt define x f 6 gt gc Zt 157812 7 gt While you might expect objects to be reclaimed and 2 3 is dead printed it won t happen the literal list gets held in the interpreter history because it is the result value of the set finalizer call Running this in a normal program will work fine When testing finalizers from the interpreter you might want to define a trivial macro such as define macro v x begin print x void and wrap calls to set finalizer init 42 6 4 Can I load compiled code at runtime 273 CHICKEN User s Manual The User s Manual 42 8 Interpreter 42 8 1 Does CSI support history and autocompletion CSI doesn t support it natively but it can be activated with the http www call with current continuation org eggs readline html egg After installing the egg add the following to your CSirc or equivalent file require extension readline current input port make gnu readline port gnu history install file manager string append or getenv HOME Users of nix like systems including Cygwin may also want to check out rlwrap This program lets you wrap another process e g rLwrap csi with the readline library giving you history autocompletion and the ability to set the keystroke set Vi fans can get vi keystrokes by adding set editing mode vi to their inputrc file 42 8 2 Does code loaded with load run compiled or interpreted If you compile a file with
55. id of the started sub process Blocking reads and writes to or from the ports returned by process only block the current thread not other threads executing concurrently The single parameter version passes the string COMMANDL INE to the host system s shell that is invoked as a subprocess 27 8 6 process run 162 CHICKEN User s Manual The User s Manual The multiple parameter version directly invokes the COMMAND as a subprocess The ARGUMENT LIST is directly passed as is ENVIRONMENT LIST Not using the shell may be preferrable for security reasons 27 8 10 process procedure process COMMANDLINE procedure process COMMAND ARGUMENT LIST ENVIRONMENT LIST Like process but returns 4 values an input port from which data written by the sub process can be read an output port from which any data written to will be received as input in the sub process the process id of the started sub process and an input port from which data written by the sub process to stderr can be read 27 8 11 sleep procedure sleep SECONDS Puts the process to sleep for SECONDS Returns either 0 if the time has completely elapsed or the number of remaining seconds if a signal occurred 27 8 12 create session procedure create session Creates a new session if the calling process is not a process group leader and returns the session ID 27 9 Hard and symbolic links 27 9 1 symbolic link procedure symbolic link FILENAME Re
56. is also the case every time you install software via sudo make instaLL so this is not specific to the CHICKEN extension mechanism Security conscious users should never run Chicken setup as root A simple remedy is to set the environment variable CHICKEN REPOSITORY which will transparently place the repository at an arbitrary user selected location Alternatively obtain write execute access to the default location of the repository usually usr local Llib chicken to avoid running as root 39 9 Other modes of installation Itis possible to install extensions directly from a Subversion repository or from a local checkout by using the Svn or Local options By using either the Svn client program which must be installed or file system operations all necessary files will be copied into the current directory creating a subdirectory named EXTENSIONNAME egg dir built and subsequently installed Dependency information which is necessary to ensure required extensions are also installed is downloaded automatically If you have no internet connection or don t want to connect you can also use a local file containing the necessary dependency information The fetch tree option retrieves the canonical repository file at http www call with current continuation org eggs repository writing it to stdout Redirecting this output into a file and passing the file via the t ree option to chicken setup allows you now to use the local reposito
57. it crashes Code compiled into a DLL to be loaded dynamically must be linked with the same runtime system as the loading application That means that all dynamically loaded entities including extensions built and installed with chicken setup must be compiled with the windows CSC option 42 2 6 On Windows csc exe seems to be doing something wrong The Windows development tools include a C compiler with the same name Either invoke CSC exe with a full pathname or put the directory where you installed CHICKEN in front of the MS development tool path in the PATH environment variable 42 2 7 On Windows source and or output filenames with embedded whitespace are not found There is no current workaround Do not use filenames with embedded whitespace for code However command names with embedded whitespace will work correctly 42 3 Customization 42 2 3 Compiling very large files under Windows with the Microsoft C compiler fails with a message indicaG g insuff CHICKEN User s Manual The User s Manual 42 3 1 How do l run custom startup code before the runtime system is invoked When you invoke the C compiler for your translated Scheme source program add the C compiler option DC EMBEDDED or pass embedded to the CSC driver program so no entry point function will be generated main When your are finished with your startup processing invoke CHICKEN main argc argv C toplevel where C_ toplevel is the entry point i
58. list to infer what features are provided Predefined features are chicken and the SRFIs Scheme Request For Implementation provided by the base system Srfi 23 srfi 30 srfi 39 Ifthe eval unit is used the default the features srfi 0 srfi 2 srfi 6 srfi 8 srfi 9and srfi 10 are defined When compiling code during compile time the feature compi Ling is registered When evaluating code in the interpreter csi the feature CSi is registered 14 3 3 rename file 72 CHICKEN User s Manual The User s Manual 14 5 1 features procedure features Returns a list of all registered features that will be accepted as valid feature identifiers by cond expand 14 5 2 feature procedure feature ID Returns t if all features with the given feature identifiers ID are registered 14 5 3 register feature procedure register feature FEATURE Register one or more features that will be accepted as valid feature identifiers by cond expand FEATURE may be a keyword string or symbol 14 5 4 unregister feature procedure unregister feature FEATURE Unregisters the specified feature identifiers FEATURE may be a keyword string or symbol 14 6 Keywords Keywords are special symbols prefixed with that evaluate to themselves Procedures can use keywords to accept optional named parameters in addition to normal required parameters Assignment to and bindings of keyword symbols is not allowed The parameter
59. listener object or f otherwise 29 3 tcp close procedure tcp close LISTENER Reclaims any resources associated with LISTENER 29 4 tcp accept procedure tcp accept LISTENER Waits until a connection is established on the port on which LISTENER is listening and returns two values an input and output port that can be used to communicate with the remote process The current value of tcp accept timeout is used to determine the maximal number of milliseconds if any to wait until a connection is established When a client connects any read and write operations on the returned ports will use the current values at the time of the connection of tcp read timeout and tcp write timeout respectively to determine the maximal number of milliseconds to wait for input output before a timeout error is signalled Note this operation and any I O on the ports returned will not block other running threads 29 Unit tcp 190 CHICKEN User s Manual The User s Manual 29 5 tcp accept ready procedure tcp accept ready LISTENER Returns t if there are any connections pending on LISTENER or f otherwise 29 6 tcp listener port procedure tcp listener port LISTENER Returns the port number assigned to LISTENER If you pass 0 to tcp listen then the system will choose a port number for you 29 7 tcp listener fileno procedure tcp listener fileno LISTENER Returns the file descriptor associated with LISTENER 29 8 tcp co
60. nnne nene nennen sten sientes innen 166 2711 1 set groupsL secs a OO REPRE PERSE REPERI RNS EE INFERIORE TER EES 166 27 V1 2 EE EE 166 E RE et ee D ME 166 21 AD e Bee TE 166 E Ml Ce OG EE 166 2112 2 tale l ck blockins eot t Gere tte eee iiai E E aE E iiae 167 PER PA KI Ee 167 21 12 4 KUTTEN 167 RRE ECHTEN EE 167 PER E ET E Er e EE 167 ABERAT GIAI BIET vasederansedensndedes A Mveevnassue 167 27 19 3 s19nal hatidlet eere oreet esee ere Pei e teda e aE AEN a SE ia EKE iaeaea 168 EE ENEE E 168 21 13 5 SiS AL MAS EE 168 E EE Ee Ee 168 PA 7 S1gnalstnaskl uie tier tet eee tte te etes deste ex E End eed eedued esie dig te tee ete eode vio eeu ta dn 168 27 13 8 EE e 168 PAN Sisal MEL EE 169 ZF AB AQ SiStial A 2 ssssesssrsesvasscesuancssesnreasedsnrsasdecsacsccdantedensacdasaacntediasecaddensdeatdnstendsevabestasetaevteavseutesendes 169 DF NS AA SISAL LO EE 169 211312 Signal MUP BEE 169 27 13 13 SIGMA EE 169 ZEAB AA Si ST Al UE 169 Def ASAD EE 169 RE EE LE E 169 Dd V3 REEL DEE 169 ZL AB AS Sigtial Quits ssscccsntesvasscctuacowseersessonsesaasecasandesevantecedoandsvasocdediavesadderandendylassdeavessdeasenteteestsewasonses 169 EE WEE EI E 169 27 13 20 siremial Vitale E 170 PA EE Ltr EE 170 QE AB D2 SUSTIALIG EEE E N sna cdadvatedsedstadsats T 170 PI A323 Si SMA Te 170 27 13 24 signal chld iecit eee er i AREE RE ER RESET ER XE guabedeesbhecssdeudeseaaoaeds 170 EE EE COME PETRO 170 EE EE LE e 170 2 A321 SIGM
61. of bytes for the primary heap symbols contains the size of the symbol table Passing 0 to one or more of these parameters will select a default size toplevel should be a pointer to the toplevel entry point procedure You should pass C toplevel here In any subsequent call to CHICKEN run you can simply pass NULL Calling this function more than once has no effect If enough memory is available and initialization was successful then 1 is returned otherwise this function returns 0 34 3 CHICKEN run C function C word CHICKEN run void toplevel Starts the Scheme program Call this function once to execute all toplevel expressions in your compiled Scheme program If the runtime system was not initialized before then CHICKEN initialize is called with default sizes top Level is the toplevel entry point procedure you usually pass C toplevel here The result value is the continuation that can be used to re invoke the Scheme code from the point after it called return to host see below If you just need a Scheme interpreter you can also pass CHICKEN default toplevel as the toplevel procedure which just uses the default library units Once CHICKEN run has been called Scheme code is executing until all toplevel expressions have been evaluated or until return to host is called inside the Scheme program 34 Embedding 224 CHICKEN User s Manual The User s Manual 34 4 return to host procedure return to host Exits the Scheme code and r
62. otherwise Returns the index of the found value or f otherwise Previous Unit eval Next Unit ports 16 7 Binary searching 109 17 Unit ports This unit contains various extended port definitions This unit is used by default unless the program is compiled with the explicit use option 17 1 Input output port extensions 17 1 1 with output to port procedure with output to port PORT THUNK Call procedure THUNK with the current output port temporarily bound to PORT 17 1 2 make input port procedure make input port READ READY CLOSE PEEK Returns a custom input port Common operations on this port are handled by the given parameters which should be procedures of no arguments READ is called when the next character is to be read and should return a character or eof READY is called when char ready is called on this port and should return t or f CLOSE is called when the port is closed PEEK is called when peek char is called on this port and should return a character or eof if the argument PEEK is not given then READ is used instead and the created port object handles peeking automatically by calling READ and buffering the character 17 1 3 make output port procedure make output port WRITE CLOSE FLUSH Returns a custom output port Common operations on this port are handled by the given parameters which should be procedures WRITE is called when output is sent to the port and receives a single ar
63. prefix downloads Ignore all following arguments Note that the options are processed exactly in the order in which they appear in the command line 39 6 chicken setup reference 256 CHICKEN User s Manual The User s Manual 39 7 Windows notes chicken setup works on Windows when compiled with Visual C but depends on the tar and gunzip tools to extract the contents of an egg The best way is to download an egg either manually or with chicken setup fetch and extract its contents with a separate program like winzip the CHICKEN REPOSITORY environment variable has to be set to a directory where your compiled extensions should be located The setup scripts will not always work under Windows and the extensions may require libraries that are not provided for Windows or work differently Under these circumstances it is recommended to perform the required steps to build an extension manually The required UNIX tools are also available as Windows binaries Google or ask on the CHICKEN mailing list if you need help locating them 39 8 Security When extensions are downloaded and installed one is executing code from potentially compromised systems This applies also when chicken setup executes system tests for required extensions As the code has been retrieved over the network effectively untrusted code is going to be evaluated When chicken setup is run as root the whole system is at the mercy of the build instructions note that this
64. property To actually link with the static version of my ext do csc static extensions my program scm uses my ext The compiler will try to do the right thing but can not handle all extensions since the ability to statically link eggs is relatively new Eggs that support static linking are designated as being able to do so If you require a statically linkable version of an egg that has not been converted yet contact the extension author or the CHICKEN mailing list Previous Interface to external functions and variables Next Data representation 39 9 Other modes of installation 258 40 Data representation Note In all cases below bits are numbered starting at 1 and beginning with the lowest order bit There exist two different kinds of data objects in the CHICKEN system immediate and non immediate objects 40 1 Immediate objects Immediate objects are represented by a single machine word which is usually of 32 bits length or 64 bits on 64 bit architectures The immediate objects come in four different flavors fixnums that is small exact integers where bit 1 is set to 1 This gives fixnums a range of 31 bits for the actual numeric value 63 bits on 64 bit architectures characters where bits 1 4 are equal to C CHARACTER BITS The Unicode code point of the character is encoded in bits 9 to 32 booleans where bits 1 4 are equal to C BOOLEAN BITS Bit 5 is one for t and zero for f other values the empty list
65. signal usr1 171 CHICKEN User s Manual The User s Manual 27 15 Memory mapped UO 27 15 1 memory mapped file pocedure memory mapped file X Returns t if X is an object representing a memory mapped file or f otherwise 27 15 2 map file to memory procedure map file to memory ADDRESS LEN PROTECTION FLAG FILENO OFFSET Maps a section of a file to memory using the C function mmap ADDRESS should be a foreign pointer object or f LEN specifies the size of the section to be mapped PROTECTION should be one or more of the flags prot read prot write prot exec or prot none bitwise iored together FLAG should be one or more of the flags map fixed map shared map private map anonymous or map file FILENO should be the file descriptor of the mapped file The optional argument OFFSET gives the offset of the section of the file to be mapped and defaults to 0 This procedure returns an object representing the mapped file section The procedure move memo ry can be used to access the mapped memory 27 15 3 memory mapped file pointer procedure memory mapped file pointer MMAP Returns a machine pointer to the start of the memory region to which the file is mapped 27 15 4 unmap file from memory procedure unmap file from memory MMAP LEN Unmaps the section of a file mapped to memory using the C function munmap MMAP should be a mapped file as returned by the procedure map file to memory The optional argument L
66. srfi 14 21 Unit srfi 13 126 22 Unit srfi 14 Character set library see the documentation for SREI 14 On systems that support dynamic loading the S rf i 14 unit can be made available in the interpreter CSi by entering require extension srfi 14 This library provides only the Latin 1 character set Previous Unit srfi 13 Next Unit srfi 69 22 Unit srfi 14 127 23 Unit srfi 69 CHICKEN implements SRFI 69 with SRFI 90 extensions For more information see SRFI 69 and SRFI 90 23 1 Hash Table Procedures 23 1 1 make hash table procedure make hash table TEST HASH SIZE TEST HASH SIZE INITIAL Returns a new HASH TABLE with the supplied configuration TEST The equivalence function HASH The hash function SIZE The expected number of table elements INITIAL The default initial value MIN LOAD The minimum load factor A f Lonum in 0 0 1 0 MAX LOAD The maximum load factor A f Lonum in 0 0 1 0 WEAK KEYS Use weak references for keys Ignored WEAK VALUES Use weak references for values Ignored No the keyword parameters are not uppercase 23 1 2 hash table procedure hash table OBJECT Is the OBJECT a hash table 23 1 3 hash table size procedure hash table size HASH TABLE The HASH TABLE size 23 Unit srfi 69 128 CHICKEN User s Manual The User s Manual 23 1 4 hash table equivalence function procedure hash table equivalence function HASH TABLE
67. symbols case insensitive The default is to read case sensitive in violation of R5RS This option registers the case insensitive feature identifier b batch Quit the interpreter after processing all command line options e eval EXPRESSIONS Evaluate EXPRESSIONS This option implies batch and quiet so no startup message will be printed and the interpreter exits after processing all eval options and or loading files given on the command line p print EXPRESSIONS Evaluate EXPRESSIONS and print the results of each expression using print Implies batch and quiet P pretty print EXPRESSIONS Evaluate EXPRESSIONS and print the results of each expression using pretty print Implies batch and quiet D feature SYMBOL Registers SYMBOL to be a valid feature identifier for cond expand and feature h help Write a summary of the available command line options to standard output and exit I include path PATHNAME Specifies an alternative search path for files included via the include special form This option may be given multiple times If the environment variable CHICKEN INCLUDE PATH is set it should contain a list of alternative include pathnames separated by k keyword style STYLE Enables alternative keyword syntax where STYLE may be either prefix as in Common Lisp or suffix as in DSSSL Any other value is ignored n no init Do not load initialization file If this option is not given and the file cSirc or HO
68. the same arguments The default behavior is to evaluate the argument expression and to ignore the second parameter 13 8 force finalizers If true force and execute all pending finalizers before exiting the program either explicitly by exit or implicitly when the last toplevel expression has been executed Default is t 13 9 implicit exit handler A procedure of no arguments When the last toplevel expression of the program has executed then the value of this parameter is called The default behaviour is to invoke all pending finalizers 13 10 keyword style Enables alternative keyword syntax where STYLE may be either prefix as in Common Lisp or Suffix as in DSSSL Any other value disables the alternative syntaxes 13 11 load verbose A boolean indicating whether loading of source files compiled code if available and compiled libraries should display a message 13 5 current read table 66 CHICKEN User s Manual The User s Manual 13 12 program name The name of the currently executing program This is equivalent to Car argv for compiled programs or the filename following the SCript option in interpreted scripts 13 13 repl prompt A procedure that should evaluate to a string that will be printed before reading interactive input from the user in a read eval print loop Defaults to Lambda N gt 13 14 reset handler A procedure of zero arguments that is called via reset The default behavior in
69. the prompt You can use this pretty much like any other Scheme system e g 1 gt define twice f lambda x f f x 2 gt twice lambda n n 10 3 2 5 Development environments 6 CHICKEN User s Manual The User s Manual 300 Suppose we have already created a file fact SCm containing a function definition define fact n if n 0 1 n fact n 1 We can now load this file and try out the function 3 gt load fact scm loading fact scm 4 gt fact 3 6 The read eval print loop REPL is the component of the Scheme system that reads a Scheme expression evaluates it and prints out the result The REPL s prompt can be customized see the Using the Interpreter but the default prompt showing the number of the form is quite convenient The REPL also supports debugging commands input lines beginning with a comma are treated as special commands See the full list We can trace fact to see how it works 5 gt tr fact 5 gt fact 3 fact 3 fact 2 fact 1 fact 0 fact gt 1 fact gt 1 fact gt 2 fact gt 6 6 The command number didn t increment because the t r command isn t actually a Scheme form 2 6 1 Scripts You can use the interpreter to run a Scheme program from the command line Here we create a program that does a quick search and replace on an input file the arguments are a regular expression and a replacement string
70. the system though he still takes a strong interest in it and participates actively Chicken includes e a Scheme interpreter that supports almost all of RSRS Scheme with only a few relatively minor omissions and with many extensions acompatible compiler whose target is C thus making porting to new machines and architectures relatively straightforward e the C support allows Scheme code to include embedded C code thus making it relatively easy to invoke host OS or library functions a framework for language extensions library modules that broaden the functionality of the system This package is distributed under the BSD license and as such is free to use and modify Scheme cognoscenti will appreciate the method of compilation and the design of the runtime system which follow closely Henry Baker s CONS Should Not CONS Its Arguments Part II Cheney on the M T A paper and expose a number of interesting properties Consing creation of data on the heap is relatively inexpensive because a generational garbage collection scheme is used in which short lived data structures are reclaimed extremely quickly e Moreover call with current continuation is practically for free and Chicken does not suffer under any performance penalties if first class continuations are used in complex ways The generated C code is fully tail recursive Some of the features supported by Chicken e SRFIs 0 1 2 4 6 19 23 25 31 37 40 42 43 45
71. the unit is initialized at most once To compile a file as a unit add a unit declaration declare unit UNITNAME When compiling different object modules make sure to have one main unit This unit is called initially and initializes all used units before executing its toplevel expressions The main unit has no unit declaration Another method of using definitions in separate source files is to include them This simply inserts the code in a given file into the current file include FILENAME Macro definitions are only available when processed by include or require for syntax Macro definitions in separate units are not available since they are defined at compile time i e the time when that other unit was compiled macros can optionally be available at runtime see def ine macro in Substitution forms and macros On platforms that support dynamic loading of compiled code Windows most ELF based systems like Linux or BSD MacOS X and others code can be compiled into a shared object dll so dy lib and loaded dynamically into a running application Previous Getting started Next Using the compiler 3 Basic mode of operation 12 4 Using the compiler The interface to Chicken is intentionally simple System dependent makefiles shell scripts or batch files should perform any necessary steps before and after invocation of chicken A program named CSC provides a much simpler interface to the Scheme and C compilers and lin
72. to constantly zt Note that ACTION is called with the full pathname of each file including the directory prefix 27 20 Getting the hostname and system information 27 20 1 get host name procedure get host name Returns the hostname of the machine that this process is running on 27 20 2 system information procedure system information 27 18 22 errno exist 177 CHICKEN User s Manual The User s Manual Invokes the UNIX system call uname and returns a list of 5 values system name node name OS release OS version and machine 27 21 Setting the file buffering mode 27 21 1 set buffering mode procedure set buffering mode PORT MODE BUFSIZE Sets the buffering mode for the file associated with PORT to MODE which should be one of the keywords full Line or none If BUFSIZE is specified it determines the size of the buffer to be used if any 27 22 Terminal ports 27 22 1 terminal name procedure terminal name PORT Returns the name of the terminal that is connected to PORT 27 22 2 terminal port procedure terminal port PORT Returns t if PORT is connected to a terminal and f otherwise 27 23 How Scheme procedures relate to UNIX C functions change directory chdir change file mode chmod Change file owner chown create directory mkdir create fifo 27 20 2 system information 178 CHICKEN User s Manual The User s Manual mkfifo create pipe pipe create session s
73. to 28 contain the type code of the object Bits 29 to 32 contain miscellaneous flags used for garbage collection or internal data type dispatching These flags are C GC FORWARDING BIT 40 Data representation 259 CHICKEN User s Manual The User s Manual Flag used for forwarding garbage collected object pointers C_BYTEBLOCK_BIT Flag that specifies whether this data object contains raw bytes a string or byte vector or pointers to other data objects C_SPECIALBLOCK_BIT Flag that specifies whether this object contains a special non object pointer value in its first slot An example for this kind of objects are closures which are a vector type object with the code pointer as the first item C_8ALIGN_BIT Flag that specifies whether the data area of this block should be aligned on an 8 byte boundary floating point numbers for example The actual data follows immediately after the header Note that block addresses are always aligned to the native machine word boundary Scheme data objects map to blocks in the following manner pairs vector like object type bits C PAIR TYPE where the car and the cdr are contained in the first and second slots respectively vectors vector object type bits C VECTOR TYPE strings byte vector object type bits C STRING TYPE procedures special vector object type bits C CLOSURE TYPE The first slot contains a pointer to a compiled C function Any extra slots contain the free variables since
74. unit Equivalent to prelude declare unit NAME unsafe Disable runtime safety checks unsafe libraries Marks the generated file for being linked with the unsafe runtime system This should be used when generating shared object files that are to be loaded dynamically If the marker is present any attempt to load code compiled with this option will signal an error uses NAME Use definitions from the library unit NAME This is equivalent to prelude declare uses NAME Multiple arguments may be given separated by no usual integrations Specifies that standard procedures and certain internal procedures may be redefined and can not be inlined This is equivalent to declaring not usual integrations version Prints the version and some copyright information and exit the compiler verbose Prints progress information to standard output during compilation The environment variable CHICKEN OPTIONS can be set to a string with default command line options for the compiler 4 2 Runtime options After successful compilation a C source file is generated and can be compiled with a C compiler Executables generated with CHICKEN and the compiler itself accept a small set of runtime options WK Shows a list of the available runtime options and exits the program aNUMBER Specifies the length of the buffer for recording a trace of the last invoked procedures Defaults to 16 b Enter a read eval print loop when an error is e
75. with the name ID All files given in the list of strings FILELIST will be copied to the extension repository It should be noted here that the extension id has to be identical to the name of the file implementing the extension The extension may load or include other files or may load other extensions at runtime specified by the require at runtime property FILELIST may be a filename a list of filenames or a list of pairs of the form SOURCE DEST if you want to copy into a particular sub directory the destination directory will be created as needed If DEST is a relative pathname it will be copied into the extension repository The optional argument INFOLIST should be an association list that maps symbols to values this list will be stored as ID setup info at the same location as the extension code Currently the following properties are used 39 4 1 1 syntax extension property syntax Marks the extension as syntax only No code is compiled the extension is intended as a file containing macros to be loaded at compile macro expansion time 39 4 1 2 require at runtime extension property require at runtime ID 39 2 1 Installing extensions that use libraries 246 CHICKEN User s Manual The User s Manual Specifies extensions that should be loaded via require at runtime This is mostly useful for syntax extensions that need additional support code at runtime 39 4 1 3 version extension property version STRING
76. y gt foo eq x y gt JH define z object evict bar bar eq car z cadr z gt Ft The ALLOCATOR defaults to allocate 30 4 2 object evict to location procedure object evict to location X PTR LIMIT As object evict but moves the object at the address pointed to by the machine pointer PTR If the number of copied bytes exceeds the optional LIMIT then an error is signalled specifically a composite condition of types exn and evict The latter provides a Limit property which holds the exceeded limit Two values are returned the evicted object and a new pointer pointing to the first free address after the evicted object 30 4 3 object evicted procedure object evicted X Returns t if X is a non immediate evicted data object or f otherwise 30 4 4 object size procedure object size X Returns the number of bytes that would be needed to evict the data object X 30 4 5 object release procedure object release X RELEASER Frees memory occupied by the evicted object X recursively RELEASER should be a procedure of a single argument a foreign pointer object to the static memory to be freed and defaults to f ree 30 4 6 object unevict procedure object unevict X FULL 30 4 1 object evict 202 CHICKEN User s Manual The User s Manual Copies the object X and nested objects back into the normal Scheme heap Symbols are re interned into the symbol table Strings and byte vectors are not
77. 0 srfi 17 srfi 23 srfi 30 srfi 39 srfi 55 then nothing is done e If ID names one of the syntactic extensions chicken more macros chicken ffi macros then this extension will be loaded at compile time making the syntactic extensions available in compiled code If ID names one of the core library units shipped with CHICKEN or if the option uses ID has been passed to the compiler then a declare uses ID is generated o If ID names an installed extension with the syntax or require at runtime attribute then the equivalent of require for syntax ID is performed and code is emitted to require any needed run time requirements Otherwise require extension ID is equivalent to require ID To make long matters short just use require extension and it will normally figure everything out for dynamically loadable extensions and core library units ID should be a pure extension name and should not contain any path prefixes for example dir lib is illegal ID may also be a list that designates an extension specifier Currently the following extension specifiers are defined 10 Non standard macros and special forms 41 CHICKEN User s Manual The User s Manual e srfi NUMBER is required for SRFI 55 compatibility and is fully implemented e version ID NUMBER is equivalent to ID but checks at compile time whether the extension named ID is installed and whether its version is equal or higher than NUMBER NUMBER may be a
78. 12 25 DOSC DEOG SS ete teer tranh reps aede NER denge xe acea ra deus E erus gege EA 62 12 26 numberstyp amp gie eode ee e Eeer EE ineat eon toss De Eege ee edd 62 12 27 KO Tee TE 62 12 28 run trmie e EE 63 12 29 Eege Ee e EC 63 12 30 extended Dindings unire doit eerte eset ee riie iii iae sai en edere oaeiai ee edes 63 UR AE EE e 63 232 E ee e ee 63 1233 EE siscosesev vsveedinvacsicdensceedarsestesr undated nensseseandedesaategedenndesseaededeesededdevesdersovavedes vuesduavawsosiandlavecasateee 64 RE GE EE 64 VD e RTE 64 ED PAP ANAC t PIE E ET 65 13 1 ue EE 65 RE EE 65 13 3 een ere 65 13 4 command Iine argumients ee ioeccis ertet e hortos rase nee Ee o ER Fa Pe Pe eh ea Ree aae da Eh EYES 65 15 5 current readstablg EE 66 13 6 exithiandler sine cte rto De Pen Peru ety a Cer ree dang vari Pete sie esa tulo na e Oe Perd Deep ene Pura ba esa ROTEN 66 13 7 eV al handli anesini e cxcsostcied uve tees vvneicsssviadessed estes dada vadncndncanacdserbuecdsabavaseversbevavascecsed 66 13 8 fotce frnaltZers EE 66 iii CHICKEN User s Manual The User s Manual Chicken User s Manual 13 Parameters 13 Bue tee Ee E E 66 13 10 Bee Ee E 66 1 3 IV EE e 66 PS AD Peo Siam E E 67 13 13 LEP EE 67 13 14 r set h ndler oorr bere e ra e gege ae MESE RR Paper eie Peyvuveesevrk eese bb edis 67 ERR Ch e ISI o EUER 68 CAHDU oreet eere e hehe oreet Urn rte reae Ee ERRARE PUE sues EORR dra Row ECL Env EE RR Eed 68 ERC
79. 16 6 ERR EE 174 ZENO of EN TOLE T E E enden eet Ee 174 PAIS RAW CK EE 174 DMP WEE 174 DIAS ERRNO Values nini TE 175 ZL AS S su AMSU TETTE STILO LL LLL 175 27 18 2 6 607 BOE Hoz eet EE 175 27 18 9 ER au coi cives Cover D E ERE RR EE Ot ad dtd eese tuia rv e Eat c dog en Sae ET e TRE Pet 175 27 18 Lerrho Itt 5 encore eae tod snebe dade e b E aaa TR ER EE PEE E E Ee a ove o Ra eve ved pua s 175 PEE EREMO ER 175 PAM E Rex eunte Mio o ee OT TNT 175 27 18 7 ertno D adt err EE oe ip ue ip Saas rrr pori D P aea TREE 175 PABEE Reuse fenlo ERI TNI m 175 27 18 9 leet otio eiie vavvsiaoavnnsaasavacerasddasasanveddanadeddansdsesdanes sau Vo eoa oed on var va saves 175 PAM ELMO n mote Pee PERENNE OON 175 EEN WE EE EE 176 RER Oe EE 176 27 18 13 le Ce 176 21 18 VA CTEM e EI ER 176 27 18 15 EMMO NV EE 176 27 18 16 errno mfile egenen ee EENEG 176 27 18 17 errno n OSspG tret rrt yu eee cher E deed geed lasedenvacsdeacanieteentaveetaaanes 176 27 18 18 e ERREUR T 176 2 18 19 errno pip rete prre n n od desea pais sevaas NOR S ERRORREE ARR daa O iri RE EY Red epo odes 176 27 18 20 errno agatn EE 176 Re CO E 176 SEELEN Ee ee 177 27 18 23 emmo wouldblock 3 pre rr te he eeh buc ep ins sage Pire er ashes aae rRe race rae aea 177 PFZEPBSUIUCEU RESISTE 177 27 19 1 find files uite otio uti oveleavevansabansunsavacevavavesasaevesi anadegdensivessannvesie doesnt o
80. 2 23 1 29 hash table cleat isse riti Lir ere uad EP vce EE EIE ER NER EORR ESTERNA TnE 132 E EE ET 133 23 1 27 hashb table m rge l e entere eerte ee da ey ab secede suceeded averse svaemecdeebuaieeanzeasoniesaseses 133 23 1 28 Nash table Map E 133 23 1 29 hash table fold EE 133 23 1 30 bhasb able Zor each nnn nnt nan nr nt nenne essa essa ee 133 Z3132lbhasbh able walk 134 23 2 Hashing PUNCH OMS ereescht ee SEENEN Peta om ted ee ege dee 134 23 2 1 number MASH E 134 ER ENT Ee E EE EE 134 EE le TEE 134 23 24 EE 134 PASE Paid 135 23 2 6 string cr ha sh EE 135 QB DA RE EE UIT LE 135 DF DO S ELIGE CREER 135 23 2 9 equal h sb roster ee OR HEU EXER EE SFORREOE PATET ERE ne OPERE EE UTR NU dSS 135 SEET 135 23211 hash by identity i secsedeantenssdtadsetscnseesvecursbaecensaysnacacsutesdedecadsedsdushivdessseussdentassacsdeedsteswredeans 136 ee WUE E EE 137 Ao IL vOEPX i od ainsi mina eee BEE 138 PEN OVC EE 138 25 2 BIODLE an E 138 RE 138 PE Bid e a A EAE EEEE E A E E E ATE AE E E 139 CHICKEN User s Manual The User s Manual Chicken User s Manual 25 Unit regex DD E E 139 25 6 WE SEKI NN 140 E RER TEE 140 25 8 SUMS MACH ss iso e eeh ee 140 e RN Ee a E TEE 141 e E Eu 141 25 11 Eeer TEE 141 25 12 strinp splitsfields osito eter ornare one he EUR ei e SEEN E NEEESE EEEIEE 141 25 13 Ee e E E 142 25 14 string substitut e E 142 25 15 TELEX EE 142 25 16 Bn S
81. 2 1 5 How does cond expand know which features are registered in used units Each unit used via declare uses is registered as a feature and so a symbol with the unit name can be tested by cond expand during macro expansion time Features registered using the register feature procedure are only available during run time of the compiled file You can use the eval when form to register features at compile time 42 1 6 Why are constants defined by define constant not honoured in case constructs Case expands into a cascaded if expression where the first item in each arm is treated as a quoted list So the Case macro can not infer whether a symbol is to be treated as a constant name defined via define constant or a literal symbol 42 1 7 How can I enable case sensitive reading writing in user code To enable the read procedure to read symbols and identifiers case sensitive you can set the parameter case sensitivity to Zt 42 1 8 How can change match error control during compilation Use eval when like this eval when compile match error control unspecified 42 1 4 Why are values defined with define foreign variable or define constant or define inline not seen out2fal of the c CHICKEN User s Manual The User s Manual 42 1 9 Why doesn t CHICKEN support the full numeric tower by default The short answer chicken setup numbers csi q 1 gt use numbers The long answer There are a number of reas
82. 2 1 7 How can I enable case sensitive reading writing in user code 263 42 1 8 How can I change match error control during compilation 263 42 1 9 Why doesn t CHICKEN support the full numeric tower by default 264 42 1 10 How can I specialize a generic function method to match instances of every el ESSERE RH 264 42 1 11 Does CHICKEN support native read 264 42 1 12 Does CHICKEN support Unicode strings seen 265 42 1 13 Why do I get an Error invalid syntax using match and syntax case 265 42 2 Platform Specific tei Dee tereti ote ere e Dn een Ce EVER Ue eee eas Code eon ER HR ER eee Eee Pane Ress 265 42 2 1 How do I generate a DLL under MS Windows mm 265 42 2 2 How do I generate a GUI application under Wumdowstm1 265 42 2 3 Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap epace enne enne neret 266 42 2 4 When I run csi inside an emacs buffer under Windows nothing happens 266 42 2 5 I load compiled code dynamically in a Windows GUI application and it crashes 266 42 2 6 On Windows csc exe seems to be doing something wrong cc eeeceeeceeeeeceseeceeneeceeeeceeneeeees 266 42 2 7 On Windows source and or output filenames with embedded whitespace are not found 266 42 H C st mi Ter
83. A ASU veda evade ode Atos dase stuseisa ute dee votindovvdaapevedeatas Senileas Vaeshnan teddies sade ctuvedaadessavedesssaednievsadetvwededs 170 21 13 28 signal Dipe eicit ree saaesaseadeannceddg anced davuaceandebacdeassqacava saad QURE EE SERES REPRINT UA dis 170 ER EE 170 EE SO ST SMALL KAS Zs e d 170 CHICKEN User s Manual The User s Manual Chicken User s Manual 27 Unit posix E EE TE E 171 27 13 32 signal Usr2 cci REG RR IU EENS 171 2713 33 EAE AVE 171 27 14 Environment ACCESS 5 ettet e egre ee terio eas NEE e ry ates eu Eee Ense bin RR ERR eR ER KE euR 171 2714 1 CULTENt ENVIFONMEN A ene eneene emen enem ene te meten te en n n nsns nnne nens aes esse esses 171 E Ee A 171 QF VAS STEE 171 2715 Memory Mapped W O et terree ehe terea aen ese eate on ERES EKA E ENNEN EEAS EEEE EIEEE 172 KE Reger EE 172 21 152 El De Eet 172 27 15 3 memory mapped file POINtCL eee eeeeceenteeenseceeececeececeaeeeeaeceeaaeceeaeeeeeeeceseeesaeceeaaeceeaeceeaeeesas 172 27 15 4 unmap file from MeMOTY spressi sirri irise Ka eas ess E on E EEEE EEE NERES EREE 172 21 16 Date and time rOUtIMES cccccccccccssscsseccsecevevevsvssevessvavsenssvanseasssnsecuceusncsenensncesanasadesacaceseeasacsenssenseseseossseveres 172 E Eve Eileen 173 Re Bee Bra rr LEE 173 27 16 3 local timezZone abbreviatiONn ccccceceeeeescscsescsenssccceceeacacecececececsceesecsseseseceeeeseeeeeseseneneneaes 173 27 16 Ee E 174 27 10 5 Ee EE E 174 2 1
84. ALIST contains no such item then alist update returns KEY VALUE ALIST The optional argument TEST specifies the comparison procedure to search a matching pair in ALIST and defaults to eqv 16 1 3 atom procedure atom X Returns t if X is not a pair This is identical to not pair from Unit srfi 1 but kept for historical reasons 16 1 4 rassoc procedure rassoc KEY LIST TEST Similar to ASSOC but compares KEY with the cdr of each pair in LIST using TEST as the comparison procedures which defaults to eqv 16 Unit data structures 98 CHICKEN User s Manual The User s Manual 16 1 5 butlast procedure butlast LIST Returns a fresh list with all elements but the last of LIST 16 1 6 chop procedure chop LIST N Returns a new list of sublists where each sublist contains N elements of LIST If LIST has a length that is not a multiple of N then the last sublist contains the remaining elements 3 4 5 6 3 45 6 2 gt 1 2 cd abc d gt 16 1 7 compress procedure compress BLIST LIST Returns a new list with elements taken from LIST with corresponding true values in the list BLIST define nums 99 100 110 401 1234 compress map odd nums nums gt 99 401 16 1 8 flatten procedure flatten LIST1 Returns LIST1 concatenated together with nested lists removed flattened 16 1 9 intersperse procedure intersperse LIST X Returns a new list wit
85. Bendiken Peter Bex Jean Francois Bignolles Alaric Blagrave Snellpym Dave Bodenstab Fabian Boehlke T Kurt Bond Ashley Bone Dominique Boucher Terence Brannon Roy Bryant Adam Buchbinder Hans Bulfone Category 5 Taylor Campbell Naruto Canada Esteban U Caamano Castro Franklin Chen Thomas Chust Gian Paolo Ciceri John Cowan Grzegorz Chrupa amp 322 a James Crippen Tollef Fog Heen Alejandro Forero Cuervo Linh Dang Brian Denheyer dgym Don Chris Double Jarod Eells Petter Egesund Steve Elkins Daniel B Faken Will Farr Graham Fawcett Marc Feeley Fizzie Kimura Fuyuki Tony Garnock Jones Martin Gasbichler Joey Gibson Stephen C Gilardi Joshua Griffith Johannes Groedem Damian Gryski Mario Domenech Goulart Andreas Gustafsson Sven Hartrumpf Jun ichiro itojun Hagino Ahdi Hargo Matthias Heiler Karl M Hegbloom William P Heinemann Bill Hoffman Bruce Hoult Hans Huebner Markus Huelsmann Goetz Isenmann Paulo Jabardo David Janssens Christian Jaeger Dale Jordan Valentin Kamyshenko Daishi Kato Peter Keller Brad Kind Ron Kneusel Matthias Koeppe Krysztof Kowa amp 322 czyk Andre Kuehne Todd R Kueny Sr Goran Krampe David Krentzlin Ben Kurtz Micky Latowicki John Lenz Kirill Lisovsky Juergen Lorenz Kon Lovett Dennis Marti Charles Martin Bob MclIsaac Alain Mellan Eric Merrit Perry Metzger Scott G Miller Mikael Bruce Mitchener Chris Moline Eric E Moore Julian Morrison Dan Muresan Lars Nilsson Ian
86. C word C SCHEME END OF RE 236 38 7 C word C SCHEME BALSE ette iiei E EEE E a a 237 38 8 C word C SCHEME TRUE 237 38 9 E 237 38 10 ee 237 SELL e E 237 38 D CAML E EE 237 LE 237 38 IAC ee EE 238 38 15 Cint t EE 238 38 16 ESIIDIBIISONMRCUTN 238 38 17 C VECCOR EE 238 3818C iSt e rr re ST re E T 238 BS NO E EE 238 3820 C SIZEOF LIST NC 239 SR WER EIER A LEE 239 3822 C SIZEOE VECTOR EE 239 38 23 C SIZEOF INTERNED sSvMpOL ccc ccccccsesscscccecessscescesscesesseessesessesssseseesesseeseeaees 239 XIX CHICKEN User s Manual The User s Manual Chicken User s Manual 38 C interface 38 24 C SIZBOER PAIR EE 239 38 25 EECH KEE ATERT EI E AH A ME 239 38 26 C SIZBOER POINTER EE 239 38 24 C SIZBOE AL HK E 239 38 28 C SIZEOF TAGGED POINTER cc cccccccccsesesesesesssssssesesssescseeeaeaeaeseaeaeaeaeeceeeeeeuss 240 38 29 C Character Code steer rer rte ae estie PO PER sy va unes ae vansk saa avanbontaraberabacgeawanscsieantesen saees 240 SEL OUEST P e 240 38 91 C Tlonum magnit de eruere eor rene one ehe EUR ee er ARE UO RERP UR ERR ER EEIE EET 240 38 92 OE i t TAE AE stun sevideouvdoageva deaduesweeaees E danvededdesasebbeentecddy vbrteowedens 240 38 33 C n m tO EE 240 38 34 C ee 240 38 35 EES 241 38 30 C e E 241 BRAFA Elek tee EEE E EE E ET ES E A AEE ES 241 38 38 GC U Ee EE 241 38 39 C U EE 241 38 40 dat e 241 398 41 C iake E 242 38A G
87. CHICKEN User s Manual The User s Manual CHICKEN User s Manual The User s Manual Chicken User s Manual RN Us E 1 2A TEU SEAGER DE 2 GE BEE 2 22 COMICK EE 2 2 3 Chicken repositories websites and community eene entere 4 2 4 Installing e Te ecco rer rere Re EEEE RR EN RE ETRAS ERN EREERUEAE RAE T Ee dE a ELE Ra pear de 5 2 5 Development environments seprei isiin niii eed eee epe etii ena deae ne ee deae AAR 5 2 6 The Read Eval Print lo0p 5 reete onere oet ne AEEA INKER UXORES ERES ETE STEHEN REY SERRE 6 PAA ESTE e ON 7 SN NEE 8 2 6 MMS tala AMOS Sass eet err eek EA ER ee rae Eee DRE E Te ERATUM FECE MEER X NESSUN TERRENCE E 10 2 0 Accessing e 10 3 Basie mode of operatio ririri DR raon Nain PEU RRVERAR HA EIRAE B SNA NEE AS NANPA AEEA EEN ARA NECENR MAYER PRU IR REX dE 12 4 Using ihi compile KE 13 4 1 Compiler command line format 13 4 2 Runtime te 17 4 3 Re 18 4 3 1 A simple example with one source Dei 19 4 3 2 An example with multiple Des 20 A A Extending the compllet rre ren ee RR ORT TIERE REESE ERROREM eg lenevead AS REPRE EXER EY adden 21 4 5 Distrbuting compiled files eR ripe cedet a eee eterne dees tiet ve a 22 S Using the NN E mn n 24 5 1 Interpreter command line Tomat 24 25 2 Writing Scheme scripts eee ore rite EE RE Cr I Ter eee AE RP E eR Se ERR e PATE eee pas 25 5 3 Keren EE 26 DA LOPleVEl COMMANA 5 vcs ierit tte er tete feet deett ex PE need ee Ud einen ENEE dese ee 27 e EE
88. E HASH TABLE PARAMETER Returns a new HASH TABLE configured using the optional MAKE HASH TABLE PARAMETER The HASH TABLE is populated from the ASSOCIATION LIST 23 1 10 hash table has initial 130 CHICKEN User s Manual The User s Manual 23 1 16 hash table ref procedure hash table ref HASH TABLE KEY Returns the VALUE for the KEY in the HASH TABLE Aborts with an exception when the KEY is missing 23 1 17 hash table ref default procedure hash table ref default HASH TABLE KEY DEFAULT Returns the VALUE for the KEY in the HASH TABLE or the DEFAULT when the KEY is missing 23 1 18 hash table exists procedure hash table exists HASH TABLE KEY Does the KEY exist in the HASH TABLE 23 1 19 hash table set procedure hash table set HASH TABLE KEY VALUE Set the VALUE for the KEY in the HASH TABLE A setter for hash table ref is defined so set hash table ref HASH TABLE KEY VALUE is equivalent to hash table set HASH TABLE KEY VALUE 23 1 20 hash table update procedure hash table update HASH TABLE KEY UPDATE FUNCTION DEFAULT VALUE Sets or replaces the VALUE for KEY in the HASH TABLE The UPDATE FUNCTION takes the existing VALUE for KEY and returns the new VALUE The default is identity 23 1 16 hash table ref 131 CHICKEN User s Manual The User s Manual The DEFAULT VALUE FUNCTION is called when the entry for KEY is missing The default uses the hash table in
89. EN specifies the length of the section to be unmapped and defaults to the complete length given when the file was mapped 27 16 Date and time routines 27 15 Memory mapped I O 172 CHICKEN User s Manual The User s Manual 27 16 1 secondslocal time procedure seconds gt local time SECONDS Breaks down the time value represented in SECONDS into a 10 element vector of the form Seconds minutes hours mday month year wday yday dstflag timezone in the following format seconds 0 the number of seconds after the minute 0 59 minutes 1 the number of minutes after the hour 0 59 hours 2 the number of hours past midnight 0 23 mday 3 the day of the month 1 31 month 4 the number of months since january 0 11 year 5 the number of years since 1900 wday 6 the number of days since Sunday 0 6 yday 7 the number of days since January 1 0 365 dstflag 8 a flag that is true if Daylight Saving Time is in effect at the time described timezone 9 the difference between UTC and the latest local standard time in seconds west of UTC 27 16 2 local timeseconds procedure local time gt seconds VECTOR Converts the ten element vector VECTOR representing the time value relative to the current timezone into the number of seconds since the first of January 1970 UTC 27 16 3 local timezone abbreviation procedure local timezone abbreviation Returns the abbreviation for the local timezone as a st
90. ER BLOCKSIZE Moves ORIGFILE a string denoting some filename to NEWFILE with the same semantics as file copy above file move is safe across filesystems and devices unlike file rename It is possible for an error to be signalled despite partial success if NEWFILE could be created and fully written but removing ORIGFILE fails 28 3 1 create temporary file 187 CHICKEN User s Manual The User s Manual 28 6 Iterating over input lines and files 28 6 1 for each line procedure for each line PROCEDURE PORT Calls PROCEDURE for each line read from PORT which defaults to the value of current input port The argument passed to PROCEDURE is a string with the contents of the line excluding any line terminators When all input has been read from the port for each line returns some unspecified value 28 6 2 for each argv line procedure for each argv line PROCEDURE Opens each file listed on the command line in order passing one line at a time into PROCEDURE The filename is interpreted as current input port If no arguments are given on the command line it again uses the value of current input port During execution of PROCEDURE the current input port will be correctly bound to the current input source This code will act as a simple Unix cat 1 command for each argv line print 28 7 Executing shell commands with formatstring and error checking 28 7 1 system procedure system FORMATSTRING ARGUMENTI
91. ESSA 211 32 6 1 TYPENAME SLEOTNAWMLB teo aet ai ea eo sous EENS ER TR TR ER EE CN TRE ECR a Aba dao 212 32 6 2 NVRBENAME SLOTNAME sel 212 32 6 3 CONSUE 3 evaccas coawstesesvcaeecasceasdeapdedu ste E 212 E e e E 212 326 5 EE 213 SEET E E 213 32 8 TOPE Slama ME 214 32 9 foteign lambd eren etr oed ae a ia FOR FO RN ERU ER EET OR eS aea FERE LEE orae 214 32 10 foreign safe lambda 5 teret i an ha RE e eee EHE LIN deed Ee 215 32 11 toreignssate lambda eer ette oe sut ee eege E 215 CHICKEN User s Manual The User s Manual Chicken User s Manual 32 Accessing external objects 32 12 f t ign primitive Em 215 Ja Eer 217 33 l scheme ObjJECt EE 217 BSD DOO EE 217 33 3 byte nsigned Dyte E 217 REENEN 217 33 5 SHOTUUMSIGNED SHOL EE 217 33 6 int unsigned int int32 UNSIGNEC INt32 0 eee ceceeseeceeceeeececeeeeeaeceeaaeceececeeeeecaeeeaeceeaaeceaeeceeeeees 217 33 7 integer unsigned integer integer32 unsigned integer32 integer64 ssssssssss 218 33 8 long unsigned long eee ertet ette eee deed EXE HET a aee E ERE ec 218 33 9 TO at double eere etre nee ey balsa neo eve oratore oe sate dei eR Edee 218 33 OUT DET eene cos 218 BSLV SYMON EE 218 33 12 Ee EE 218 33 13 nonnull Schem poiiter Lucius etn r stehe ea tnes neke Heg esae EE EERE ESTEN EEE en eee nn ESEE agn 219 PEE Ke LOr MET NN 219 SET e EE 219 B36 DIGI E 219
92. Foreign pointers 30 1 1 addresspointer procedure address gt pointer ADDRESS Creates a new foreign pointer object initialized to point to the address given in the integer ADDRESS 30 1 2 allocate procedure allocate BYTES Returns a pointer to a freshly allocated region of static memory This procedure could be defined as follows define allocate foreign lambda c pointer malloc integer 30 1 3 free procedure free POINTER Frees the memory pointed to by POINTER This procedure could be defined as follows define free foreign lambda c pointer free integer 30 1 4 null pointer procedure null pointer Another way to say address gt pointer 0 30 Unit lolevel 195 CHICKEN User s Manual The User s Manual 30 1 5 null pointer procedure null pointer PTR Returns t if PTR contains a NULL pointer or f otherwise 30 1 6 objectpointer procedure object gt pointer X Returns a pointer pointing to the Scheme object X which should be a non immediate object Note that data in the garbage collected heap moves during garbage collection 30 1 7 pointer procedure pointer X Returns t if X is a foreign pointer object and f otherwise 30 1 8 pointerz procedure pointer PTR1 PTR2 Returns t if the pointer like objects PTR1 and PTR2 point to the same address 30 1 9 pointeraddress procedure pointer gt address PTR Returns the address to which the pointer PTR points 30 1
93. Keyword style and the compiler interpreter option keyword style can be used to allow an additional keyword syntax either compatible to Common LISP or to DSSSL 14 6 1 get keyword procedure get keyword KEYWORD ARGLIST THUNK Returns the argument from ARGLIST specified under the keyword KEYWORD If the keyword is not found then the zero argument procedure THUNK is invoked and the result value is returned If THUNK is not given f is returned 14 5 1 features 73 CHICKEN User s Manual The User s Manual define increase x args x get keyword amount args Lambda 1 increase 123 gt 124 increase 123 amount 10 gt 133 Note the KEYWORD may actually be any kind of object 14 6 2 keyword procedure keyword X Returns t if X is a keyword symbol or f otherwise 14 6 3 keywordstring procedure keyword gt string KEYWORD Transforms KEYWORD into a string 14 6 4 stringkeyword procedure string gt keyword STRING Returns a keyword with the name STRING 14 7 Exceptions CHICKEN implements the currently withdrawn SREL 12 exception system For more information see the SRFI 12 document 14 7 1 condition case syntax condition case EXPRESSION CLAUSE Evaluates EXPRESSION and handles any exceptions that are covered by CLAUSE where CLAUSE should be of the following form CLAUSE VARIABLE KIND BODY If provided VARIABLE will be bound to the signale
94. ME csirc exists then it is loaded before the read eval print loop commences W no warnings Disables any warnings that might be issued by the reader or evaluated code q quiet Do not print a startup message Also disables generation of call trace information for interpreted code s script PATHNAME 5 Using the interpreter 24 CHICKEN User s Manual The User s Manual This is equivalent to batch quiet no init PATHNAME Arguments following PATHNAME are available by using command Line arguments and are not processed as interpreter options Extra options in the environment variable CST OPTIONS are ignored ss PATHNAME The same as s PATHNAME but invokes the procedure main with the value of command line arguments as its single argument If the main procedure returns an integer result then the interpreter is terminated returning the integer as the status code back to the invoking process Any other result terminates the interpreter with a zero exit status R require extension NAME Equivalent to evaluating require extension NAME v version Write the banner with version information to standard output and exit 5 2 Writing Scheme scripts Since UNIX shells use the notation for starting scripts anything following the characters is ignored with the exception of the special symbols optional key rest and eof The easiest way is to use the script option like this cat foo usr local bin csi scri
95. MODE which defaults to procedure perm irwxu perm irwxg perm irwxo 27 4 2 fifo procedure fifo FILENAME Returns t if the file with the name FILENAME names a FIFO 27 3 9 with input from pipe 154 CHICKEN User s Manual The User s Manual 27 5 File descriptors and low level I O 27 5 1 duplicate fileno procedure duplicate fileno OLD NEW If NEW is given then the file descriptor NEW is opened to access the file with the file descriptor OLD Otherwise a fresh file descriptor accessing the same file as OLD is returned 27 5 2 file close procedure file close FILENO Closes the input output file with the file descriptor FILENO 27 5 3 file open procedure file open FILENAME FLAGS MODE Opens the file specified with the string FILENAME and open flags FLAGS using the C function open On success a file descriptor for the opened file is returned FLAGS should be a bitmask containing one or more of the open values ored together using b itwise ior or simply added together The optional MODE should be a bitmask composed of one or more permission values like pe rm irusr and is only relevant when a new file is created The default mode is perm irwxu perm irgrp perm iroth 27 5 4 file mkstemp procedure file mkstemp TEMPLATE FILENAME Create a file based on the given TEMPLATE FILENAME in which the six last characters must be XXXXXX These will be replaced with a string that makes the filename un
96. Manual 34 9 CHICKEN_apply C macro int CHICKEN apply C word func C word args C word result Applies the procedure passed in func to the list of arguments args writing the result value to result 34 10 CHICKEN apply to string C macro int CHICKEN apply to string C word func C word args char result Applies the procedure passed in func to the list of arguments args writing a textual representation of the result into result 34 11 CHICKEN read C macro int CHICKEN read char str C word result Reads a Scheme object from the string Str writing the result value to result 34 12 CHICKEN load C macro int CHICKEN load char filename Loads the Scheme file filename either in source form or compiled 34 13 CHICKEN get error message C macro void CHICKEN get error message char result int size Returns a textual description of the most recent error that occurred in executing embedded Scheme code 34 14 CHICKEN yield C macro int CHICKEN yield int status If threads have been spawned during earlier invocations of embedded Scheme code then this function will run the next scheduled thread for one complete time slice This is useful for example inside an idle handler in a GUI application with background Scheme threads Note that the s rf 1 18 library unit has to be linked in for this 34 9 CHICKEN apply 226 CHICKEN User s Manual The User s Manual An example cat x scm 121 X SCm define bar x
97. NAME should be an absolute pathname P program path PATHNAME When used without an argument the path for executables is displayed on standard output When given an argument the program path for installing executables and scripts will be set to PATHNAME for all subsequent operations PATHNAME should be an absolute pathname h host HOSTNAME PORT Specifies alternative host for downloading extensions optionally with a TCP port number which defaults to 80 u uninstall EXTENSION Removes all files that were installed for EXTENSION from the file system together with any metadata that has been stored l list NAME List all installed extensions or show extension information r run FILENAME Load and execute given file S script FILENAME Executes the given Scheme source file with all remaining arguments and exit The she bang shell script header is recognized so you can write Scheme scripts that use chicken setup just as with CS1 e eval EXPRESSION Evaluates the given expression s v verbose Display additional debug information 39 6 chicken setup reference 255 CHICKEN User s Manual The User s Manual k keep Keep temporary files and directories c csc option OPTION Passes OPTION as an extra argument to invocations of the compiler driver CSC this works only if CSC is invoked as run csc d dont ask Do not ask the user before trying to download required extensions n no install Do not install ge
98. NATION when supplied performs a sprintf fora f a printf fora t and a fprintf for an output port When missing a Sprint f is performed 18 2 Random numbers 18 2 1 random seed procedure random seed SEED Seeds the random number generator with SEED an exact integer or current seconds if SEED is not given 18 2 2 random procedure random N Returns an exact random integer from 0 to N 1 18 1 3 sprintf 115 CHICKEN User s Manual The User s Manual 18 2 3 randomize procedure randomize X Set random number seed If X is not supplied the current time is used On startup when the extras unit is initialized the random number generator is initialized with the current time 18 3 Input Output extensions 18 3 1 pretty print procedure pretty print EXP PORT procedure pp EXP PORT Print expression nicely formatted PORT defaults to the value of current output port 18 3 2 pretty print width Parameter Specifies the maximal line width for pretty printing after which line wrap will occur 18 3 3 read byte 18 3 4 write byte procedure read byte PORT procedure write byte BYTE PORT Read write a byte to the port given in PORT which default to the values of current input port and current output port respectively 18 3 5 read file procedure read file FILE OR PORT READER MAXCOUNT Returns a list containing all toplevel expressions read from the file or port
99. NES EEs 78 ER E E 78 14 8 10 software tvpe teet erem e eret eoo es n aote ree uae ae usen eae eee eh 78 I4SUlsoftware vergion ene eneneneene emen nennen memes ene te ne n i aiee ieia sensns esie 78 E Ee Te EE 79 14 8 15 system E 79 14 9 Exec ti on e 79 E WC NEE 79 UE e ee Ee E 79 14 9 3 current EE 80 14 94 c rrent gc Mii second EE 80 14 10 Interrupts and error handling iieri rre tenete rr rnit ae il ene e oiiaee 80 UE WAREN Oe 80 LA ui EE 80 14 10 E etaed e ad 80 14 104 print call chati EE 81 14 105 erte E 81 14 10 6 procedure 1nfOrmMatiOn E 81 TATO T e EE 81 IC LORS ANAE t EE 81 14 109 singlestep EE 81 14 11 Garbage collection EE 82 ERD WE ER 14 11 2 memioEy StatistiCs EE ER 1411 3 SE GEI RE ER UE WR Ee e GE ER ERAN ER E WEE ere 83 14 13 e ere EE 83 14 13 1 EE 83 14 14 Generating uninterned svmbols ee eeceeseecesseceeseeceeeeceaeceeaaeceaneceeaeececessaeceeaaeneaeeceeeeeeeseaaeceeaeceeaeeceaees 83 IC DAA EE 83 14 14 2 stringuninterned symbol 00 2 ce eeecceneeceeeeeseeceesaecseaceceaeeceeeeaeeseaaecseneceeaeeceaeeseaeeseaaeceaaeceeeeeeees 83 14 15 Standard Input Output irre rrr tee NEES e ane Eee ERE ue Ont eee eaae eee eroe aeo 83 E SE sl rrt eet etie e eate ette e e E raesent eau te ete eee apa 84 IC S ERA Pint PP 84 14153 pint REI I 84 14 16 Us
100. Oversby o t Gene Pavlovsky Levi Pearson Nicolas Pelletier Carlos Pita Robin Lee Powell Pupeno Davide Puricelli Doug Quale Eric Raible Ivan Raikov Joel Reymont Eric Rochester Andreas Rottman David Rush Lars Rustemeier Daniel Sadilek Oskar Schirmer Burton Samograd Reed Sheridan Ronald Schroeder Spencer Schumann Alex Shinn Ivan Shmakov Shmul Tony Sidaway Jeffrey B Siegal Andrey Sidorenko Michele Simionato Volker Stolz Jon Strait Dorai Sitaram Robert Skeels Jason Songhurst Clifford Stein Sunnan Zbigniew Szadkowski Rick Taube Mike Thomas Minh Thu Christian Tismer Andre van Tonder John Tobey Henrik Tramberend Vladimir Tsichevsky Neil van Dyke Sander Vesik Jaques Vidrine Panagiotis Vossos Shawn Wagner Peter Wang Ed Watkeys Brad Watson Thomas Weidner Goeran Weinholt Matthew Welland Joerg Wittenberger Peter Wright Mark Wutka Richard Zidlicky and Houman Zolfaghari for bug fixes tips and suggestions CHICKEN uses the PCRE regular expression package http www pcre org which is written by Philip Hazel Special thanks to Brandon van Every for contributing the now defunct CMake support and for helping with Windows build issues Also special thanks to Benedikt Rosenau for his constant encouragement Thanks to Dunja Winkelmann for putting up with all of this CHICKEN contains code from several people Eli Barzilay some performance tweaks used in TinyCLOS Mikael Djurfeldt topological sort used
101. RE REE EEE O E Ea 123 20 27 blobs vectorisbared reidansen eon eE i i ereis Eese 123 20 28 blobulovector shiared eterne EEEE EEE NEE NON R TEATES E 123 20 29 blobsT6vector shared 5 peces eret eve Saee dyes EENEG Ee 123 20 30 blobu Zvectotifehared eee s stike st asks memet n EENEN nn ese nnn ne ess nsns es 123 20 31 blobs32vector shared oer eere eo eee od eo xo Seu xv E vet E E ssusseavadaddunvdeaduradurdearstacacabacadeonesens 123 20 32 blobt32vector sh ted etr eei eei et Tete er Deeper e tee ERE RERUM ER S PRA ENN 123 20 33 blobfo4vector shared 5 ctio pore eene e aont e eoe e ee Sue CREER PR ER CREER ER Tu ER BR pn Ce VR ER EAR Ra as 123 20 34 ebe eege ELTE E EE 124 E e Se Re e 124 SEU e TEE 124 20 37 SUDSSVECLOEF s iiio EE EES SE EE ees 124 20338 SUDSTOVECIOL scccsasndacexevsactassasieseaseeessdenaesidesses edevosviegsveosdess ond ede vonesanvabdeeandavadernsmadeasandesdeasdecssdesaces 124 239 SUBS E EE 124 20 40 SUBS RA LTE 124 20 41 SUDIO4 VECIOE E 124 ERD Eet 125 EE EES 125 20 44 WHITE 18 EE 125 PARUT SCD KE 126 SA EE E E 127 1X CHICKEN User s Manual The User s Manual Chicken User s Manual SE Ee 128 23 1 Hash Tabl e ProCedures s isesccccscascesssoascsesevedecssts cesses ere et 6 ei eR ER VR Pn REN ERU ERE AUR EERR ESTE CA Fa cR e RR Niens 128 23 1 13m ke hashetable iier rrt eod tio FE Pe GE Po Par aes Fa eoe EENS 128 23 1 2 hash table eerte ee ee ee Eege 128 23 1 3 ha
102. RING2 returning either 1 if STRINGI is lexicographically less than STRING2 0 if it is equal or 1 if it s greater string compare3 ci performs a case insensitive comparison 16 5 6 string intersperse procedure string intersperse LIST STRING Returns a string that contains all strings in LIST concatenated together STRING is placed between each concatenated string and defaults to string intersperse one two three is equivalent to apply string append intersperse one two three 16 5 2 string 104 CHICKEN User s Manual The User s Manual 16 5 7 string split procedure string split STRING DELIMITER STRING KEEPEMPTY Split string into substrings separated by the given delimiters If no delimiters are specified a string comprising the tab newline and space characters is assumed If the parameter KEEPEMPTY is given and not f then empty substrings are retained string split one two three gt one two three string split foo bar baz t gt foo bar baz 16 5 8 string translate procedure string translate STRING FROM TO Returns a fresh copy of STRING with characters matching FROM translated to TO If TO is omitted then matching characters are removed FROM and TO may be a character a string or a list If both FROM and TO are strings then the character at the same position in TO as the matching character in FROM is substituted 16 5 9 string
103. ST ENVIRONMENT LIST EXACT FLAG procedure process COMMAND ARGUMENT LIST ENVIRONMENT LIST EXACT FLAG 1 The optional parameter EXACT FLAG default f When f any argument string with embedded whitespace will be wrapped in quotes When t no such wrapping occurs 27 24 2 Unsupported Definitions The following definitions are not supported for native Windows builds compiled with the Microsoft tools or with MinGW open noctty open nonblock open fsync open sync perm isvtx perm isuid perm isgid file select file control Signal except signal term signal int signal fpe signal ill signal segv set signal mask signal mask signal masked signal mask signal unmask user information group information get groups set groups initialize groups errno wouldblock change file owner current user id current group id current effective user id current effective set user id set group id create session process group id set process group id create symbolic link read symbolic link file truncate file lock file lock blocking file unlock file test lock create fifo fifo prot map map file to memory unmap file from memory memory mapped file pointer memory set alarm terminal port terminal name process fork process signal parent process id set root directory utc time gt seconds 27 24 1 Procedure Changes 182 CHICKEN User s Manual The User s Manual 27 24 3 Additional Definitions Only available for Wind
104. UNC Calls FUNC for all entries in HASH TABLE with the key and value of each entry Returns a list of the results of each call 23 1 29 hash table fold procedure hash table fold HASH TABLE FUNC INIT Calls FUNC for all entries in HASH TABLE with the key and value of each entry and the current folded value The initial folded value is INIT Returns the final folded value 23 1 30 hash table for each procedure hash table for each HASH TABLE PROC Calls PROC for all entries in HASH TABLE with the key and value of each entry 23 1 26 hash table merge 133 CHICKEN User s Manual The User s Manual 23 1 31 hash table walk procedure hash table walk HASH TABLE PROC Calls PROC for all entries in HASH TABLE with the key and value of each entry 23 2 Hashing Functions All hash functions return a fixnum in the range 0 BOUND 23 2 1 number hash procedure number hash NUMBER BOUND For use with as a hash table equivalence function 23 2 2 object uid hash procedure object uid hash OBJECT BOUND Currently a synonym for equal hash 23 2 3 symbol hash procedure symbol hash SYMBOL BOUND For use with eq as a hash table equivalence function 23 2 4 keyword hash procedure keyword hash KEYWORD BOUND For use with eq as a hash table equivalence function 23 1 31 hash table walk 134 CHICKEN User s Manual The User s Manual 23 2 5 string hash procedure string hash STRING BOUND
105. User s Manual The User s Manual Chicken User s Manual 1i Pattern mat iN ia RHR ieee 52 11 1 Pattern Matching Expressions cccccccessecesseesseeesaeceesceseaeeceeeeeaeeseaaecseaeceeaeeceaeesaeeseaaeceaaeceeneenses 52 11 52 SE E 54 T13 Match F ilute EE 56 114 Record Structures Patter E 56 11 5 Code GeneratlOn eere etre arant sosvedsesocessvevesecseovsdsvssbuasisavavaussavacacuvavacdnencencesanscacdoareceses 57 RAN E 58 PASS SPEI RCRUM 58 12 2 always bound eerte edente taie rien aae iea cade ONU ee Ent are eade eL AR Heer 58 12 9 DIOGE ee RFE leere uL De SOTO Mid 58 12 4 block slobal eite eere ee e e tank ERUIT ed AE 58 HAST EE ms 58 12 6 boundzto procedure iier eter re rte tono eer enne Ue e C E a oiiae pia etse 59 12 7 le E 59 UE EE EE 59 T2 RTE ET 59 TD AO CX er 59 RRE e CT 59 12 12 emit ext rmal prototypes frSt vic ssccccsssssensissieveescaencs sand isennsderdaccusa inia anii A aeaieie 60 12 AB EE E 60 12 AA ERI SAEI 60 T215 re E 60 UE Re EE 60 12 17 age WAAL cies secscevievsceveesedevevvsutesccdesesvosededs 61 12 18 EE EE E e E rrr eet eee seein ned eite eode Ln Pe dea ee ERE VELA Nen dee qud 61 12 19 keenp zhadowed macros eene enne E nnne stesse tenen tenerent 61 UR AEN lee EE EE 61 I2 2T ee 61 12 22 EE 62 12 23 no bound checks repr R EEEE E A EE ERA 62 12 24 no procedure checks EE 62
106. a eek e En TE erat aeo te tae eU dhesusedbsiweieds 251 EREECHEN ET 251 394 22 required chacken Version E 251 39 4 23 reguired eXtension verston 252 30 4 24 CrOSS CHICKED cccccccvasaccsarconsecacscacsoacsscsesoeseseesdsecsvecevecesvessoesonsssavnsneseanacasuvasacdearsencesanscacscacscas 252 394 25 host eXtenslOB EE 252 39 5 Examples for extensions Ire Teresita Dr he Yee Te e eee a eeu E pete E e e eO E dtes 252 39 6 chickeri setup reference deter eren Nene aee oe e E ERR SEERE eK geed edd eessen See 255 39 Windows EE 257 39 8 SOCULILY soree irer ERR 257 39 9 Other modes of nistallatiOM 63 ccccc0sccssesecssovssevesoveecssnscansavacasardvncsdarsvacdearecacedasecaccdessesesscecece oa va ee ooa da rasa raras 257 39 10 Linking Ee 258 d Data representaatiot EE 259 40 1 ue Ee Ee EE 259 40 2 Nom 1mMe diate E E 259 di Bugs and TE 261 UR QVIS eem T 262 LEN EIS CITROEN 262 42 1 1 Why yet another Scheme implementation sese 262 42 1 2 Whi Call it Chick n EE 262 42 1 3 What should I do if I find abuel nenne 262 42 1 4 Why are values defined with define foreign variable or define constant or define inline not seen outside of the containing source De sse 263 42 1 5 How does cond expand know which features are registered in used units 263 42 1 6 Why are constants defined by define constant not honoured in case constructs 263 4
107. a ien gave v eves 177 27 20 Getting the hostname and system form aton enne enne entente nenne 177 RE Re EE E 177 ER EE E TE e 177 27 21 Setting the file buffering mode rere eee ei eria trees evo ket vi esu eue ne eet epa aad 178 xlv CHICKEN User s Manual The User s Manual Chicken User s Manual 27 Unit posix 21 21 1 set buffermg mode eet rere eerta ete th eege ees Dee EAR EE 178 21 22 Terminal er EC 178 PAP TREIE ERREUR 178 21 222 earen 178 27 23 How Scheme procedures relate to UNIX C functions essent 178 21 24 Windows specific e 181 27 24 1 Procedure NEE 181 21 24 2 Unsupported Definitions oorr rettet retos AE KESKE ES NEEESE ege geesde 182 27 24 3 Additional A Rn Te E 183 21 24 4 PrOCESS SPA WI TE 183 ek IR 184 25 1 Environment QUEyV 2 erected ette ete en arie oi Eoi EOE aaO AEE EEEE pi oiei 184 28 1 l apropos ern vices OD D EP EE E EE EPI ERI E ENTE Res 184 28 1 2 apropos list TE 184 28 2 EEN E 184 GN WE e ge 184 28 2 2 GECOMPOSE Path Ee 185 28 23 Ee path Mame sees Eege TL ILL LL 185 28 2 4 make absolute oathuame eene neret nnn tentes snnt innen 185 20 2 5 pathnaime dIrectory EE 185 e EE 185 28 2 7 ENEE Ee 185 28 2 8 Pathname re place GITEClOLY saves saccsusvsesieds vasederaassdeasnudedws sepestesededeeseadeausiinversevgnsdenaavasties Teen RE add 186 25 2 9 p thname replace tfil iiie ene or eee een e etri Pee ke ee ore edo te Eee ER VUE i rue ded
108. ach PROC is equivalent to PROC and each is equivalent to noop 16 6 4 compose 107 CHICKEN User s Manual The User s Manual 16 6 8 flip procedure flip PROC Returns a two argument procedure that calls PROC with its arguments swapped flip PROC lt gt lambda x y PROC y x 16 6 9 identity procedure identity X Returns its sole argument X 16 6 10 project procedure project N Returns a procedure that returns its Nth argument starting from 0 16 6 11 list of procedure list of PRED Returns a procedure of one argument that returns t when applied to a list of elements that all satisfy the predicate procedure PRED or f otherwise list of even 1 2 3 gt f list of number 1 2 3 gt st 16 6 12 noop procedure noop X Ignores it s arguments does nothing and returns an unspecified value 16 6 13 0 procedure o PROC A single value version of compose slightly faster 0 is equivalent to identity 16 6 8 flip 108 CHICKEN User s Manual The User s Manual 16 7 Binary searching 16 7 1 binary search procedure binary search SEQUENCE PROC Performs a binary search in SEQUENCE which should be a sorted list or vector PROC is called to compare items in the sequence should accept a single argument and return an exact integer zero if the searched value is equal to the current item negative if the searched value is ess than the current item and positive
109. acro int C SIZEOF LOCATIVE 38 20 C SIZEOF LIST 239 CHICKEN User s Manual The User s Manual 38 28 C SIZEOF TAGGED POINTER C macro int C SIZEOF TAGGED POINTER These are macros that return the size in words needed for a data object of a given type 38 29 C character code C macro int C character code C word character 38 30 C unfix C macro int C unfix C word fixnum 38 31 C flonum magnitude C macro double C flonum magnitude C word flonum 38 32 C c string C function char C c string C word string 38 33 C num to int C function int C num to int C word fixnum or flonum 38 34 C pointer address C function void C pointer address C word pointer These macros and functions can be used to convert Scheme data objects back to C data Note that C c string returns a pointer to the character buffer of the actual Scheme object and is not zero terminated 38 28 C SIZEOF TAGGED POINTER 240 CHICKEN User s Manual The User s Manual 38 35 C header size C macro int C header size C word x 38 36 C header bits C macro int C header bits C word x Return the number of elements and the type bits of the non immediate Scheme data object X 38 37 C block item C macro C word C block item C word x int index This macro can be used to access slots of the non immediate Scheme data object X index specifies the index of the slot to be fetched starting at 0 Pairs have 2 slots one for the car and one
110. ading Users vmanis local lib chicken 3 synch support so loading Users vmanis local lib chicken 3 lookup table so loading Users vmanis local lib chicken 3 misc extn control support so 2 gt uri host uri http www foobar org blah www foobar org 2 9 Accessing C libraries Because Chicken compiles to C and because a foreign function interface is built into the compiler interfacing to a C library is quite straightforward This means that nearly any facility available on the host system is accessible from Chicken with more or less work 2 8 Installing an egg 10 CHICKEN User s Manual The User s Manual Let s create a simple C library to demonstrate how this works Here we have a function that will compute and return the nth Fibonacci number This isn t a particularly good use of C here because we could write this function just as easily in Scheme but a real example would take far too much space here int fib int n int prev 0 curr 1 int next int i for 120 i lt n i next prev curr prev curr curr next return curr Now we can call this function from Chicken gt extern fib int n lt define xfib foreign lambda int fib int do i i 1 i 10 printf A xfib i newline The syntax gt lt allows you to include literal C typically external declarations in your Chicken code We access fib by defining a foreign lambda for it
111. age STRING defaults to Error 14 10 6 procedure information procedure procedure information PROC Returns an s expression with debug information for the procedure PROC or f if PROC has no associated debug information 14 10 7 reset procedure reset Reset program Invokes reset handler 14 10 8 warning procedure warning STRING EXP Displays a warning message if warnings are enabled with enable warnings and continues execution 14 10 9 singlestep procedure singlestep THUNK Executes the code in the zero procedure THUNK in single stepping mode 14 10 4 print call chain 81 CHICKEN User s Manual The User s Manual 14 11 Garbage collection 14 11 1 gc procedure gc FLAG Invokes a garbage collection and returns the number of free bytes in the heap The flag specifies whether a minor f or major t GC is to be triggered If no argument is given t is assumed An explicit t argument will cause all pending finalizers to be executed 14 11 2 memory statistics procedure memory statistics Performs a major garbage collection and returns a three element vector containing the total heap size in bytes the number of bytes currently used and the size of the nursery the first heap generation Note that the actual heap is actually twice the size given in the heap size because CHICKEN uses a copying semi space collector 14 11 3 set finalizer procedure set finalizer X PROC Register
112. al The User s Manual procedure u32vector gt blob U32VECTOR procedure s32vector gt blob S32VECTOR procedure f32vector gt blob F32VECTOR procedure f64vector gt blob F64VECTOR procedure u8vector gt blob shared U8VECTOR ul6vector gt blob shared s16vector blob shared u32vector blob shared s32vector gt blob shared f32vector gt blob shared f64vector gt blob shared procedure procedure procedure procedure procedure procedure Each of these procedures return the contents of the given vector as a packed blob The byte order in that procedure s8vector gt blob shared S8VECTOR U16VECTOR S16VECTOR U32VECTOR S32VECTOR F32VECTOR FO4VECTOR ws ws ws ee vector is platform dependent for example little endian on an Intel processor The Shared variants return a blob that shares memory with the contents of the vector 20 18 blobu8vector 20 19 blobs8vector 20 20 blobu16vector 20 21 blobs16vector 20 22 blobu32vector 20 23 blobs32vector 20 24 blobf32vector 20 17 f64vectorblob shared 122 CHICKEN User s Manual The User s Manual 20 25 blobf64vector 20 26 blobu8vector shared 20 27 blobs8vector shared 20 28 blobu16vector shared 20 29 blobs16vector shared 20 30 blobu32vector shared 20 31 blobs32vector shared 20 32 blobf32vector shared 20 33 blobf64vector shared procedure procedure procedure procedu
113. al The User s Manual 27 3 3 Close input pipe 27 3 4 close output pipe procedure close input pipe PORT procedure close output pipe PORT Closes the pipe given in PORT and waits until the connected subprocess finishes The exit status code of the invoked process is returned 27 3 5 create pipe procedure create pipe The fundamental pipe creation operator Calls the C function pipe and returns 2 values the file descriptors of the input and output ends of the pipe 27 3 6 open input pipe procedure open input pipe CMDLINE MODE Spawns a subprocess with the command line string CMDLINE and returns a port from which the output of the process can be read If MODE is specified it should be the keyword text the default or binary 27 3 7 open output pipe procedure open output pipe CMDLINE MODE Spawns a subprocess with the command line string CMDLINE and returns a port Anything written to that port is treated as the input for the process If MODE is specified it should be the keyword text the default or binary 27 3 8 pipe buf This variable contains the maximal number of bytes that can be written atomically into a pipe or FIFO 27 3 3 close input pipe 153 CHICKEN User s Manual The User s Manual 27 3 9 with input from pipe 27 3 10 with output to pipe procedure with input from pipe CMDLINE THUNK MODE procedure with output to pipe CMDLINE THUNK MODE Temporarily set
114. al The User s Manual can also download and install eggs from an arbitrary HTTP server Alternatively you can pass a full URL including the http prefix Note that no dependency checks are done when downloading eggs directly with the URL syntax Finally a somewhat more complex example We want to package a syntax extension with additional support code that is to be loaded at run time of any Scheme code that uses that extension We create a glass lambda a procedure with free variables that can be manipulated from outside i377 glass scm define macro glass lambda llist vars body Low level macros are fun let lvar gensym svar gensym x gensym y gensym yn gensym let map lambda v list v f vars define svar x y let yn pair y and yn cat yyY case x lethdp v if yn v set v y et 3 3 vars else efror variable not found x define lvar lambda llist body extend procedure lvar svar Here some support code that needs to be loaded at runtime glass support scm require extension lolevel define glass lambda accessor procedure data define glass lambda ref gl v procedure data gl v define glass lambda set gl v x procedure data gl v x The setup script looks like this compile s glass support scm install extension glass glass scm glass support so syntax require at runtime glass support
115. al argument OPTIONS must be a list of option symbols The optional argument TABLES must be a character definitions table not defined here Option Symbols caseless Character case insensitive match multiline Equivalent to Perl s m option dotall Equivalent to Perl s s option extended Ignore whitespace anchored Anchor pattern match dollar endonly metacharacter in the pattern matches only at the end of the subject string extra Currently of very little use notbol First character of the string is not the beginning of a line noteol End of the string is not the end of a line ungreedy Inverts the greediness of the quantifiers so that they are not greedy by default notempty The empty string is not considered to be a valid match utf8 UTF 8 encoded characters no auto capture Disables the use of numbered capturing parentheses no utf8 check Skip valid UTF 8 sequence check auto callout Automatically inserts callout items not defined here partial 25 4 regexp 139 CHICKEN User s Manual The User s Manual Partial match ok firstline An unanchored pattern is required to match before or at the first newline dupnames Names used to identify capturing subpatterns need not be unique newline cr Newline definition is wi newline lf Newline definition is wi newline crlf Newline definition is wn newline anycrlf Newline definition is any of r wl or r n newline any Newline definition is any Unicode newline s
116. alling CHICKEN continue make sure that the continuation is not reclaimed by garbage collection This can be avoided by using C gc protect or gc roots Another example cat x scm require extension srfi 18 define m make mutex define t mutex lock m thread sleep 1 print thread name current thread mutex unlock m t thread start make thread t PING thread start make thread t PONG let loop return to host thread yield loop cat y c include chicken bs int main C word k CHICKEN run C toplevel for k CHICKEN continue k return 0 34 15 CHICKEN continue 228 CHICKEN User s Manual The User s Manual CSC x scm y c embedded It is advisable not to mix repeated uses of CHICKEN continue return to host as in the example above with callbacks Once return to host is invoked the runtime system and any Scheme code executed prior to the invocation is initialized and can be conveniently used via callbacks A simpler interface For handling GC safe references to Scheme data are the so called gc roots 34 16 CHICKEN new gc root C function void CHICKEN new gc root Returns a pointer to a GC root which is an object that holds a reference to a Scheme value that will always be valid even after a garbage collection The content of the gc root is initialized to an unspecified value 34 17 CHICKEN delete gc root C function void CHICKEN delete gc
117. applies The following modes are supported Signal an error This is the default 1 error Signal an error and output the offending form 1 match Omits pair tests when the consequence is to fail in Car or Cdr rather than to signal an error 1 fail unspecified Non matching expressions will either fail in Car or Cdr or return an unspecified value This mode applies to files compiled with the unsafe option or declaration When an error is signalled the raised exception will be of kind exn match procedure match error procedure match error procedure PROCEDURE Sets or returns the procedure called upon a match error The procedure takes one argument the value which failed to match When the error control mode is match a second argument the source form of the match expression is available 11 4 Record Structures Pattern The pattern handles native record structures and SREL 9 records transparently Currently it is required that SREI 9 record predicates are named exactly like the record type name followed by a question mark character 11 3 Match Failure 56 CHICKEN User s Manual The User s Manual 11 5 Code Generation Pattern matching macros are compiled into i f expressions that decompose the value being matched with standard Scheme procedures and test the components with standard predicates Rebinding or lexically shadowing the names of any of these procedures will change the semantics of the match macros
118. aracter C macro C word C make character int char code 38 5 C SCHEME END OF LIST C macro C SCHEME END OF LIST 38 6 C word C SCHEME END OF FILE C macro C SCHEME END OF FILE 38 C interface 236 CHICKEN User s Manual The User s Manual 38 7 C word C SCHEME FALSE C macro C SCHEME FALSE 38 8 C word C SCHEME TRUE C macro C SCHEME TRUE These macros return immediate Scheme data objects 38 9 C string C function C word C string C word ptr int length char string 38 10 C string2 C function C word C string2 C word ptr char zero terminated string 38 11 C intern2 C function C word C intern2 C word ptr char zero terminated string 38 12 C intern3 C function C word C intern3 C word ptr char zero terminated string C wo 38 13 C pair C function C word C pair C word ptr C word car C word cdr 38 7 C word C SCHEME FALSE 237 CHICKEN User s Manual The User s Manual 38 14 C flonum C function C word C flonum C word ptr double number 38 15 C int to num C function C word C int to num C word ptr int integer 38 16 C mpointer C function C word C mpointer C word ptr void pointer 38 17 C vector C function C word C vector C word ptr int length 38 18 C list C function C word C list C word ptr int length These functions allocate memory from ptr and initialize a fresh data object The new data object is returned p
119. as in ARC set invalid procedure call handler Lambda proc args cond string proc vector proc else error c apply string ref proc args apply vector ref proc args f ll of non procedure proc a hello 4 gt 0 This facility does not work in code compiled with the unsafe setting 30 8 2 unbound variable value procedure unbound variable value X Defines the value that is returned for unbound variables Normally an error is signalled use this procedure to override the check and return X instead To set the default behavior of signalling an error call unbound variable value with no arguments This facility does not work in code compiled with the unsafe setting 30 9 Magic 30 9 1 object become procedure object become ALIST 30 7 9 recordvector 207 CHICKEN User s Manual The User s Manual Changes the identity of the value of the car of each pair in ALIST to the value of the cdr Both values may not be immediate i e exact integers characters booleans or the empty list define x i used to be a string define y and now i am a vector object become list cons x y x gt and now i am a vector y gt and now i am a vector eq x y gt gt Note this operation invokes a major garbage collection The effect of using object become on evicted data see object evict is undefined 30 9 2 mutate procedure procedure mutate
120. ase The built in match macro is incompatible with syntax case Use the matchable egg instead 42 2 Platform specific 42 2 1 How do I generate a DLL under MS Windows tm Use CSC in combination with the dll option C gt csc foo scm dll 42 2 2 How do generate a GUI application under Windows tm Invoke CSC with the windows option Or pass the DC WINDOWS GUI option to the C compiler and link with the GUI version of the runtime system that s Libchicken gui static lib The GUI runtime displays error messages in a message box and does some rudimentary command line parsing 42 1 12 Does CHICKEN support Unicode strings 265 CHICKEN User s Manual The User s Manual 42 2 3 Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space It seems that the Microsoft C compiler can only handle files up to a certain size and it doesn t utilize virtual memory as well as the GNU C compiler for example Try closing running applications If that fails try to break up the Scheme code into several library units 42 2 4 When I run csi inside an emacs buffer under Windows nothing happens Invoke CSi with the C runtime option Under Windows the interpreter thinks it is not running under control of a terminal and doesn t print the prompt and does not flush the output stream properly 42 2 5 load compiled code dynamically in a Windows GUI application and
121. ation return could be implemented like this define continuation return k vals continuation graft k lambda apply values vals 14 20 1 call cc 87 CHICKEN User s Manual The User s Manual 14 21 Setters SRFI 17 is fully implemented For more information see SRFI 17 14 21 1 setter procedure setter PROCEDURE Returns the setter procedure of PROCEDURE or signals an error if PROCEDURE has no associated setter procedure Note that set setter PROC fora procedure that has no associated setter procedure yet is a very slow operation the old procedure is replaced by a modified copy which involves a garbage collection 14 21 2 getter with setter procedure getter with setter GETTER SETTER Returns a copy of the procedure GETTER with the associated setter procedure SETTER Contrary to the SRFI specification the setter of the returned procedure may be changed 14 22 Reader extensions 14 22 1 define reader ctor procedure define reader ctor SYMBOL PROC Define new read time constructor for read syntax For further information see the documentation for SRFI 10 14 22 2 set read syntax procedure set read syntax CHAR OR SYMBOL PROC When the reader encounters the non whitespace character CHAR while reading an expression from a given port then the procedure PROC will be called with that port as its argument The procedure should return a value that will be returned to the reader A simple
122. b1 fx fx fx fx fxmod fx fx fx gt fixnum fxneg fxmax fxmin fxand fxior fxxor fxnot fxshl fxshr flonum fp fp fp fp atom fp fp fp fpneg fpmax fpmin arithmetic shift signum f lush output thread specific thread specific set not pair null list print print u8vector gt blob shared s8vector gt blob shared ul6vector gt blob shared sl6vector gt blob shared u32vector gt blob shared s32vector gt blob shared f32vector gt blob shared f64vector gt blob shared block ref blob size u8vector length s8vector length ul6vector length s16vector length u32vector length s32vector length f32vector length f64vector length u8vector ref s8vector ref ul6vector ref sl6vector ref u32vector ref s32vector ref f32vector ref f64vector ref u8vector set s8vector set ul6vector set sl6vector set u32vector set s32vector set hash table ref block set number of slots first second third fourth null pointer pointer gt object make record instance locative ref locative set locative locative object identity cpu time error call cc any substring substring ci substring index substring index ci 42 6 4 Can load compiled code at runtime Yes You can load compiled at code at runtime with Load just as well as you can load Scheme source code Compiled code will of course run faster 42 6 2 How can I obtain faster executables 272 CHICKEN User s Manual The User s Manual To do this pass to Load a path for a shared object Use a form such
123. back manually you should performa C callback adjust stack to make sure the internal limits are set properly ptr should point to some data object on the stack and size is the number of words contained in the data object or some estimate The call will make sure the limits are adjusted so that the value pointed to by ptr is located in the stack Previous Embedding Next Locations 35 2 C callback 232 36 Locations It is also possible to define variables containing unboxed C data so called locations It should be noted that locations may only contain simple data that is everything that fits into a machine word and double precision floating point values 36 1 define location syntax define location NAME TYPE INIT Identical to define external NAME TYPE INIT but the variable is not accessible from outside of the current compilation unit it is declared static 36 2 let location syntax let location NAME TYPE INIT BODY Defines a lexically bound location 36 3 location syntax location NAME syntax location X This form returns a pointer object that contains the address of the variable NAME If the argument to location is not a location defined by define Location define external or Let Location then location X is essentially equivalent to make locative X See the manual chapter or Locatives for more information about locatives Note that Location X may be abbreviated as X
124. batim into header of generated file 32 4 define foreign type syntax define foreign type NAME TYPE ARGCONVERT RETCONVERT 1 Defines an alias for TYPE with the name NAME a symbol TYPE may be a type specifier or a string naming a C type The namespace of foreign type specifiers is separate from the normal Scheme namespace The optional arguments ARGCONVERT and RETCONVERT should evaluate to procedures that map argument and result values to a value that can be transformed to TYPE define foreign type char vector nonnull c string compose list string vector gt list compose list gt vector string gt list define strlen 32 Accessing external objects 210 CHICKEN User s Manual The User s Manual foreign lambda int strlen char vector strlen a b c gt 3 define memset foreign lambda char vector memset char vector char int memset 4 X 3 gt X X X Foreign type definitions are only visible in the compilation unit in which they are defined so use include to use the same definitions in multiple files 32 5 define foreign variable syntax define foreign variable NAME TYPE STRING Defines a foreign variable of name NAME a symbol STRING should be the real name of a foreign variable or parameterless macro If STRING is not given then the variable name NAME will be converted to a string and used instead All references and assignments via Set are modified to c
125. ble by default as compared to the extras unit This unit uses the extras and regex units 28 1 Environment Query 28 1 1 apropos procedure apropos SYMBOL PATTERN ENVIRONMENT MACROS Displays symbols amp type matching SYMBOL PATTERN in the ENVIRONMENT on the current output port SYMBOL PATTERN A symbol string or regex When symbol or string substring matching is performed ENVIRONMENT An environment When missing the interaction environment is assumed 3t MACROS Keyword argument A boolean Include macro symbols When missing f is assumed 28 1 2 apropos list procedure apropos list SYMBOL PATTERN ENVIRONMENT MACROS Like apropos but returns a list of matching symbols 28 2 Pathname operations 28 2 1 absolute pathname procedure absolute pathname PATHNAME Returns t if the string PATHNAME names an absolute pathname and returns f otherwise 28 Unit utils 184 CHICKEN User s Manual The User s Manual 28 2 2 decompose pathname procedure decompose pathname PATHNAME Returns three values the directory filename and extension components of the file named by the string PATHNAME For any component that is not contained in PATHNAME f is returned 28 2 3 make pathname 28 2 4 make absolute pathname procedure make pathname DIRECTORY FILENAME EXTENSION SEPARATOR procedure make absolute pathname DIRECTORY FILENAME EXTENSION SEPARATOR Returns a str
126. bol A symbol which will be passed to foreign code as a zero terminated string When declared as the result of foreign code the result should be a string and a symbol with the same name will be interned in the symbol table and returned to the caller 33 12 scheme pointer An untyped pointer to the contents of a non immediate Scheme object not allowed as return type The value f is also allowed and is passed as a NULL pointer Don t confuse this type with C pointer which means something different a machine pointer object 33 7 integer unsigned integer integer32 unsigned integer32 integer64 218 CHICKEN User s Manual The User s Manual 33 13 nonnull scheme pointer As scheme pointer but guaranteed not to be f Don t confuse this type with nonnull c pointer which means something different a machine pointer object 33 14 c pointer An untyped operating system pointer or a locative The value f is also allowed and is passed as a NULL pointer If uses as the type of a return value a NULL pointer will be returned as f 33 15 nonnull c pointer As C pointer but guaranteed not to be f NULL 33 16 blob A blob object passed as a pointer to its contents Arguments of type b Lob may optionally be f which is passed as a NULL pointer This is not allowed as a return type 33 17 nonnull blob As blob but guaranteed not to be f 33 18 u8vector u16vector u32vector s8vector s16vector s32vector f32ve
127. bols into its numeric value number gt SCHEMENAME takes one argument and converts a numeric value into its scheme value Note that the specification of a scheme value override SCHEME VALUE means the mapping may not be closed number gt SCHEMENAME SCHEMENAME number SCHEMENAME may not equal SCHEMENAME Here a heavily contrived example gt enum foo a foo 4 b foo c foo enum foo bar enum foo x printf sd n x return b foo lt define foreign enum foo enum foo a foo b foo c c foo define bar foreign lambda foo bar foo pp bar pp bar a foo pp bar b foo c 32 8 foreign lambda syntax foreign lambda RETURNTYPE NAME ARGTYPE Represents a binding to an external routine This form can be used in the position of an ordinary Lambda expression NAME specifies the name of the external procedure and should be a string or a symbol 32 9 foreign lambda syntax foreign lambda RETURNTYPE ARGTYPE VARIABLE STRING 32 7 define foreign enum 214 CHICKEN User s Manual The User s Manual Similar to foreign lambda but instead of generating code to call an external function the body of the C procedure is directly given in STRING define my strlen foreign lambda int c string str feat nx C ratinrn oa n Str n C return n 0 while s int n my strlen one two three gt 13 For obscure technical reasons you should us
128. breviation for foreign declare 9 10 Sharp Prefixed Symbol Bess Reads like a normal symbol 9 11 Bang loss Interpretation depends on the directly following characters Only the following are recognized Any other case results in a read error 9 11 1 Line Comment e If followed by whitespace or a slash then everything up the end of the current line is ignored 9 11 2 Eof Object es If followed by the character sequence eof then the self evaluating end of file object is returned 9 11 3 DSSSL Formal Parameter List Annotation es If followed by any of the character sequences optional rest or key then a symbol with the same name and prefixed with is returned 9 11 4 Read Mark Invocation e If a read mark with the same name as the token is registered then its procedure is called and the result of the read mark procedure will be returned 9 9 Foreign Declare 39 CHICKEN User s Manual The User s Manual 9 12 Case Sensitive Expression Zcs Read the next expression in case sensitive mode regardless of the current global setting 9 13 Case Insensitive Expression Aci Read the next expression in case insensitive mode regardless of the current global setting 9 14 Conditional Expansion FEATURE EXPR Equivalent to cond expand FEATURE EXPR else Previous Extensions to the standard Next Non standard macros and special forms 9 12 Case Sensitive Expression 40 10 Non standard macros
129. can of course be combined into one command csc c pal proc scm csc c pal user scm csc o pal separate pal proc o pal user o pal separate level level is a palindrome 2 8 Installing an egg Installing eggs is quite straightforward on systems that support dynamic loading again that would include BSD Linux Mac OS X Solaris and Windows The command chicken setup will fetch an egg from the master Chicken repository and install it on your local system In this example we install the uri egg for parsing Uniform Resource Identifiers The installation produces a lot of output which we have edited for space reasons chicken setup uri The extension uri does not exist Do you want to download it yes no abort yes yes downloading uri egg from www call with current continuation org eggs 3 80 gzip d c uri egg tar xf Users vmanis local bin csc feature compiling extension S 02 d1 uri scm o uri so check imports emit exports uri exports lots of stuff elided rm fr Users vmanis project chicken uri egg First chicken setup asks us if we want to download the egg It then uncompresses the egg compiles the code and installs the egg in the local Chicken repository Now we can use our new egg 1 gt use uri loading Users vmanis local lib chicken 3 uri so loading Users vmanis local lib chicken 3 coerce support so loading Users vmanis Llocal lib chicken 3 misc extn list support so lo
130. cedures relate to UNIX C functions 180 CHICKEN User s Manual The User s Manual alarm set buffering mode setvbuf set file position fseek seek set groups setgroups set signal mask sigprocmask set group id setgid set process group id setpgid set user id setuid set root directory chroot setenv setenv putenv sleep sleep system information uname terminal name ttyname terminal port isatty time gt string asctime unsetenv putenv unmap file from memory munmap user information getpwnam getpwuid utc time gt seconds timegm 27 24 Windows specific notes Use of UTF8 encoded strings is for pathnames is not supported Windows uses a 16 bit UNICODE encoding with special system calls for wide character support Only single byte string encoding can be used 27 24 1 Procedure Changes Exceptions to the above procedure definitions procedure create pipe MODE 27 24 Windows specific notes 181 CHICKEN User s Manual The User s Manual The optional parameter MODE default open binary open noinherit This can be open binary or open text optionally or ed with open noinherit procedure process wait PID NOHANG process wait always returns t for a terminated process and only the exit status is available Windows does not provide signals as an interprocess communication method procedure process execute PATHNAME ARGUMENT LIST ENVIRONMENT LIST EXACT F procedure process COMMAND ARGUMENT LI
131. cheme calls can reduce the available memory up to the point of thrashing It is advisable to have only a single thread with pending C stack frames at any given time Pointers to Scheme data objects should not be stored in local or global variables while calling back to Scheme Any Scheme object not passed back to Scheme will be reclaimed or moved by the garbage collector Calls from C to Scheme are never tail recursive Continuations captured via call with current continuation and passed to C code can be invoked like any other Scheme procedure Previous Other support procedures Next chicken setup 38 48 An example for simple calls to foreign code involvingcallbacks 244 39 chicken setup 39 1 Extension libraries Extension libraries eggs are extensions to the core functionality provided by the basic CHICKEN system to be built and installed separately The mechanism for loading compiled extensions is based on dynamically loadable code and as such is only available on systems on which loading compiled code at runtime is supported Currently these are most UNIX compatible platforms that provide the Libdl functionality like Linux Solaris BSD Mac OS X and Windows using Cygwin Note Extension may also be normal applications or shell scripts but are usually libraries chicken setup will download the source code for extension automatically from the canonical server at http www call with current continuation org eggs if the requested e
132. chicken but in almost all cases you will want to use the CSC command instead CSC is a convenient driver that automates compiling Scheme programs into C compiling C code into object code and linking the results into an executable file Note in a Windows environment with Visual Studio you may find that CSC refers to Microsoft s C compiler There are a number of ways of sorting this out of which the simplest is to rename one of the two tools and or to organize your PATH according to the task at hand Compiled code can be intermixed with interpreted code on systems that support dynamic loading which includes modern versions of BSD Linux Mac OS X Solaris and Windows We can compile our factorial function producing a file named fact so shared object in Linux ese the same file type is used in OS X and Windows rather than dy lib or dll respectively chicken csc dynamic fact scm chicken csi quiet 1 gt load fact so loading fact so 2 gt fact 6 720 2 6 1 Scripts 8 CHICKEN User s Manual The User s Manual On any system we can just compile a program directly into an executable Here s a program that tells you whether its argument is a palindrome define palindrome x define check left right if gt left right t and char string ref x left string ref x right check add1 left subl right check subl string length x let arg car command line arguments dis
133. ckage directory gt string cadr spec require extension my package stuff expands into load my packag Note that the handler has to be registered at compile time if it is to be visible in compiled code 15 5 System information 15 5 1 chicken home procedure chicken home Returns a string given the installation directory usually usr local share chicken on UNIX like systems As a last option if the environment variable CHICKEN PREFIX is set then chicken home will return CHICKEN PREFIX share 15 6 Eval 15 6 1 eval procedure eval EXP ENVIRONMENT Evaluates EXP and returns the result of the evaluation The second argument is optional and defaults to the value of interaction environment Previous Unit library Next Unit extras 15 4 6 set extension specifier 97 16 Unit data structures This unit contains a collection of procedures related to data structures This unit is used by default unless the program is compiled with the explicit use option 16 1 Lists 16 1 1 alist ref procedure alist ref KEY ALIST TEST DEFAULT Looks up KEY in ALIST using TEST as the comparison function or eqv if no test was given and returns the cdr of the found pair or DEFAULT which defaults to f 16 1 2 alist update procedure alist update KEY VALUE ALIST TEST If the list ALIST contains a pair of the form KEY X then this procedure replaces X with VALUE and returns ALIST If
134. cken bh Previous chicken setup Next Bugs and limitations 40 2 Non immediate objects 260 41 Bugs and limitations Compiling large files takes too much time e If a known procedure has unused arguments but is always called without those parameters then the optimizer repairs the procedure in certain situations and removes the parameter from the lambda list e port position currently works only for input ports Leaf routine optimization can theoretically result in code that thrashes if tight loops perform excessively many mutations Previous Data representation Next FAQ 41 Bugs and limitations 261 42 FAQ This is the list of Frequently Asked Questions about Chicken Scheme If you have a question not answered here feel free to post to the chicken users mailing list if you consider your question general enough feel free to add it to this list 42 1 General 42 1 1 Why yet another Scheme implementation Since Scheme is a relatively simple language a large number of implementations exist and each has its specific advantages and disadvantages Some are fast some provide a rich programming environment Some are free others are tailored to specific domains and so on The reasons for the existence of CHICKEN are CHICKEN is portable because it generates C code that runs on a large number of platforms CHICKEN is extendable since its code generation scheme and runtime system garbage collector fits neatly into a C
135. compiled code is to invoke the value of exit handler The default behavior in the interpreter is to abort the current computation and to restart the read eval print loop Previous Declarations Next Unit library 13 12 program name 67 14 Unit library This unit contains basic Scheme definitions This unit is used by default unless the program is compiled with the explicit use option 14 1 Arithmetic 14 1 1 add1 sub1 procedure add1 N procedure sub1 N Adds subtracts 1 from N 14 1 2 Binary integer operations Binary integer operations arithmetic shift shifts the argument N1 by N2 bits to the left If N2 is negative than N1 is shifted to the right These operations only accept exact integers or inexact integers in word range 32 bit signed on 32 bit platforms or 64 bit signed on 64 bit platforms procedure bitwise and N1 procedure bitwise ior N1 procedure bitwise xor N1 procedure bitwise not N procedure arithmetic shift N1 N2 14 1 3 bit set procedure bit set N INDEX Returns t if the bit at the position INDEX in the integer N is set or f otherwise The rightmost least significant bit is bit 0 14 1 4 fixnum procedure fixnum X Returns t if X is a fixnum or f otherwise 14 Unit library 68 CHICKEN User s Manual The User s Manual 14 1 5 Arithmetic fixnum operations These procedures do not check their arguments so non fixnum parameters wil
136. copied unless FULL is given and not f 30 5 Locatives A locative is an object that points to an element of a containing object much like a pointer in low level imperative programming languages like C The element can be accessed and changed indirectly by performing access or change operations on the locative The container object can be computed by calling the location 0object procedure Locatives may be passed to foreign procedures that expect pointer arguments The effect of creating locatives for evicted data see obj ect evict is undefined 30 5 1 make locative procedure make locative EXP INDEX Creates a locative that refers to the element of the non immediate object EXP at position INDEX EXP may be a vector pair string blob SRFI 4 number vector or record INDEX should be a fixnum INDEX defaults to 0 30 5 2 make weak locative procedure make weak locative EXP INDEX Creates a weak locative Even though the locative refers to an element of a container object the container object will still be reclaimed by garbage collection if no other references to it exist 30 5 3 locative procedure locative X Returns t if X is a locative or f otherwise 30 5 4 locative ref procedure locative ref LOC Returns the element to which the locative LOC refers If the containing object has been reclaimed by garbage collection an error is signalled 30 4 6 object unevict 203 CHICKEN User s Manual The
137. cord type Call make NAME to create an instance of the structure with one initialization argument for each slot NAME STRUCT tests any object for being an instance of this structure Slots are accessed via NAME SLOTNAME STRUCT and updated using NAME SLOTNAME set STRUCT VALUE define record point x y define pl make point 123 456 point pl gt t point x pl gt 123 point y set pl 99 point y pl gt 99 10 5 1 select 48 CHICKEN User s Manual The User s Manual 10 6 2 define record printer syntax define record printer NAME RECORDVAR PORTVAR BODY syntax define record printer NAME PROCEDURE Defines a printing method for record of the type NAME by associating a procedure with the record type When a record of this type is written using display write or print then the procedure is called with two arguments the record to be printed and an output port define record foo x y zl define f make foo 1 2 3 define record printer foo x out fprintf out foo S S S foo x x foo y x foo z x define reader ctor foo make foo define s with output to string lambda write f S gt foo 12 3 equal f with input from string s read gt t define record printer works also with SRFI 9 record types 10 6 3 define record type syntax define record type NAME CONSTRUCTOR TAG PREDICATE FIELD ACCESSOR MODIFIER SRFI 9 record types For m
138. ctor f64vector A SRFI 4 number vector object passed as a pointer to its contents These type specifiers are not allowed as return types 33 13 nonnull scheme pointer 219 CHICKEN User s Manual The User s Manual 33 19 nonnull u8vector nonnull u16vector nonnull u32vector nonnull s8vector nonnull s16vector nonnull s32vector nonnull f32vector nonnull f64vector As u8vector but guaranteed not to be f 33 20 c string A C string zero terminated The value f is also allowed and is passed as a NULL pointer If uses as the type of a return value a NULL pointer will be returned as f Note that the string is copied with a zero byte appended when passed as an argument to a foreign function Also a return value of this type is copied into garbage collected memory 33 21 nonnull c string As C String but guaranteed not to be f NULL 33 22 nonnull c string Similar to nonnull c string but if used as a result type the pointer returned by the foreign code will be freed using the C libraries f ree 1 after copying This type specifier is not valid as a result type for callbacks defined with def ine external 33 23 nonnull unsigned c string Same as C string but maps to the unsigned char C type 33 24 c string list Expects a pointer to a list of C strings teminated by a NULL pointer and returns a list of strings Only valid as a result type of non callback functions 33 19 nonnull u8vector nonnul
139. ctory null procedure directory null DIRECTORY Does the DIRECTORY consist only of path separators and the period DIRECTORY may be a string or a list of strings 28 3 Temporary files 28 2 8 pathname replace directory 186 CHICKEN User s Manual The User s Manual 28 3 1 create temporary file procedure create temporary file EXTENSION Creates an empty temporary file and returns its pathname If EXTENSION is not given then tmp is used If the environment variable TMPDIR TEMP or TMP is set then the pathname names a file in that directory 28 4 Deleting a file without signalling an error 28 4 1 delete file procedure delete file FILENAME If the file FILENAME exists it is deleted and t is returned If the file does not exist nothing happens and f is returned 28 5 File move copy 28 5 1 file copy procedure file copy ORIGFILE NEWFILE optional CLOBBER BLOCKSIZE Copies ORIGFILE a string denoting some filename to NEWFILE BLOCKSIZE bytes at a time BLOCKSIZE defaults to 1024 and must be a positive integer Returns the number of bytes copied on success or errors on failure CLOBBER determines the behaviour of file copy when NEWFILE is already extant When set to f default an error is signalled When set to any other value NEWFILE is overwritten file copy will work across filesystems and devices and is not platform dependent 28 5 2 file move procedure file move ORIGFILE NEWFILE optional CLOBB
140. d 124 CHICKEN User s Manual The User s Manual Creates a number vector of the same type as the argument vector with the elements at the positions FROM up to but not including TO SRFI 17 Setters for XXXvector ref are defined 20 42 read u8vector procedure read u8vector LENGTH PORT Reads LENGTH bytes from the PORT and returns a fresh u8vector or less if end of file is encountered PORT defaults to the value of current input port If LENGTH is f the vector will be filled completely until end of file is reached 20 43 read u8vector procedure read u8vector LENGTH U8VECTOR PORT START Reads LENGTH bytes from the PORT writing the read input into UBVECTOR beginning at START or 0 if not given PORT defaults to the value of current input port If LENGTH is f the vector will be filled completely until end of file is reached This procedure returns the number of bytes read 20 44 write u8vector procedure write u8vector U8VECTOR PORT START END Writes the bytes UBVECTOR between the indices START inclusive and END exclusive to PORT PORT defaults to the value of current output port Previous Unit srfi 1 Next Unit srfi 13 20 41 subf64 vector 125 21 Unit srfi 13 String library see the documentation for SRFI 13 On systems that support dynamic loading the srfi 13 unit can be made available in the interpreter CSi by entering require extension srfi 13 Previous Unit srfi 4 Next Unit
141. d exception object BODY is executed when the exception is a property or composite condition with the kinds given KIND unevaluated If no clause 14 6 1 get keyword 74 CHICKEN User s Manual The User s Manual applies the exception is re signaled in the same dynamic context as the condition case form define check thunk condition case thunk exn file print file error exn print other error var print something else check lambda open input file gt file error check lambda some unbound variable othererror check lambda signal 99 gt something else condition case some unbound variable exn file print ignored gt Signals error 14 7 2 breakpoint procedure breakpoint NAME Programmatically triggers a breakpoint similar to the Dr top level csi command All error conditions signaled by the system are of kind exn The following composite conditions are additionally defined exn arity Signaled when a procedure is called with the wrong number of arguments exn type Signaled on type mismatch errors for example when an argument of the wrong type is passed to a built in procedure exn arithmetic Signaled on arithmetic errors like division by zero exn i o Signaled on input output errors exn i o file Signaled on file related errors exn i o net Signaled on network errors exn bounds Signaled on e
142. d features of the host system would need more configuration and build time support All this can be addressed using more elaborate build scripts makefiles or by using autoconf automake Note also that the size of the application can still be reduced by removing ext ras and eval and compiling hello scm with the explicit use option For more information study the CHICKEN source code and or get in contact with the author Previous index html 4 5 Distributing compiled C files 22 CHICKEN User s Manual The User s Manual Next Using the interpreter 4 5 Distributing compiled C files 23 5 Using the interpreter CHICKEN provides an interpreter named CSi for evaluating Scheme programs and expressions interactively 5 1 Interpreter command line format csi FILENAME OPTION where FILENAME specifies a file with Scheme source code If the extension of the source file is SCM it may be omitted The runtime options described in Compiler command line format are also available for the interpreter If the environment variable CSI OPTIONS is set to a list of options then these options are additionally passed to every direct or indirect invocation of CSi Please note that runtime options like i can not be passed using this method The options recognized by the interpreter are Ignore everything on the command line following this marker Runtime options are still recognized i case insensitive Enables the reader to read
143. d symbols By default unused and unbound symbols are not garbage collected X Raises uncaught exceptions of separately spawned threads in primordial thread By default uncaught exceptions in separate threads are not handled unless the primordial one explicitly joins them When warnings are enabled the default and X is not given a warning will be shown though The argument values may be given in bytes in kilobytes suffixed with K or K in megabytes suffixed with M or m or in gigabytes suffixed with G or g Runtime options may be combined like dC but everything following a NUMBER argument is ignored So wh64m is OK but h64mw will not enable GC of unused symbols 4 3 Examples 4 3 Examples 18 CHICKEN User s Manual The User s Manual 4 3 1 A simple example with one source file To compile a Scheme program assuming a UNIX like environment consisting of a single source file perform the following steps 4 3 1 1 Writing your source file In this example we will assume your source file is called foo scm z t foo scm define fac n if zero n s n fac n 1 write fac 10 newline 4 3 1 2 Compiling your program Compile the file foo scm csc foo scm This will produce the foo executable ls foo foo scm 4 3 1 3 Running your program To run your newly compiled executable use foo 3628800 If you geta foo command not found error you might want to try with f o0 ins
144. destination operand is known then the maximal number of bytes will be copied Moving memory to the storage returned by locatives will cause havoc if the locative refers to containers of non immediate data like vectors or pairs The additional fourth and fifth argument specify starting offsets in bytes for the source and destination arguments 30 7 6 number of bytes procedure number of bytes BLOCK Returns the number of bytes that the object BLOCK contains BLOCK may be any non immediate value 30 7 7 number of slots procedure number of slots BLOCK Returns the number of slots that the object BLOCK contains BLOCK may be a vector record structure pair or symbol 30 7 8 record instance procedure record instance X Returns t if X is an instance of a record type See also make record instance 30 7 9 recordvector procedure record gt vector BLOCK 30 7 4 make record instance 206 CHICKEN User s Manual The User s Manual Returns a new vector with the type and the elements of the record BLOCK 30 8 Procedure call and variable reference hooks 30 8 1 set invalid procedure call handler procedure set invalid procedure call handler PROC Sets an internal hook that is invoked when a call to an object other than a procedure is executed at runtime The procedure PROC will in that case be called with two arguments the object being called and a list of the passed arguments Access sequence elements
145. dresses E 192 29 10 ee El E 192 29 11 tcp abarndon pOrt oe eter reo n ast EITE CC TE TIOE E ETE 192 29 12 e KEE 192 209 13 e Eer E 192 29 14 te p write EE 193 29 15 tcp Connect DITIeOUL dis cocco eodera eee orn ae ne See oae EOE EE Reggie ed edd UR EXER ER e eR laveeveaases 193 29 16 tcpsaccept timeoUt iere rne er denke tee Pede eaa edu e dade an ea dn ee te Eee ARR e YER erue 193 POBWEs Cups M 193 UE iS DEDE m 195 30 1 qOGIAEXIOHI SERENO TO m T 195 30 1 1 addr sspointer iie nere er e PRI ERR EE EE reda Rep EEN 195 SUN BOARD 195 GAR BS 195 SODA MU POmMiE Tr RTT 195 30 1 5 null potnier E 196 SREL E 196 SUBARU ET RE 196 DO TS POTETE NE 196 30 1 9 er Tele 196 30 1 10 pornterob ect 52 13 eere rr tette et aedeagal een anb eda he dan ect even de 196 90 1 11 pointer offset ooo etti repetere on A A E eR UR NRE VAR rV I gUES Pw esee h de 197 30 1 T2 pointer 8 reL icon ir e ectetuer ee du eee elu P eae eigen 197 STORE Ree 197 SREL 197 SOM AS pointer s lO Tei EE 197 SUUS 16 ee 197 30 1 17 pointer s32 ret ee one rm evs ERE NIRE GERI EE ERE ETE REN R ER Fre PER ETRAS 198 30 1 18 enee 2 18 EE 198 CARS POmMter TOF TEL GE 198 30 1 20 pointer 8 EE 198 30 1 21 pointer s8 setl ie etr e od a PIRE OI DR EDI OT er PR RED TERME dS 198 30 1 22 pointer ul setl eite eene tete t eee Up ee
146. dure system STRING Execute shell command The functionality offered by this procedure depends on the capabilities of the host shell If the forking of a subprocess failed an exception is raised Otherwise the return status of the subprocess is returned unaltered 14 9 Execution time 14 9 1 cpu time procedure cpu time Returns the used CPU time of the current process in milliseconds as two values the time spent in user code and the time spent in system code On platforms where user and system time can not be differentiated system time will be always be 0 14 9 2 current milliseconds procedure current milliseconds Returns the number of milliseconds since process or machine startup 14 8 11 software version 79 CHICKEN User s Manual The User s Manual 14 9 3 current seconds procedure current seconds Returns the number of seconds since midnight Jan 1 1970 14 9 4 current gc milliseconds procedure current gc milliseconds Returns the number of milliseconds spent in major garbage collections since the last call of current gc milliseconds and returns an exact integer 14 10 Interrupts and error handling 14 10 1 enable warnings procedure enable warnings BOOL Enables or disables warnings depending on wether BOOL is true or false If called with no arguments this procedure returns t if warnings are currently enabled or f otherwise Note that this is not a parameter The current state whether
147. e set pointer u8 ref PTR N Stores the unsigned byte N at the address designated by PTR 30 1 21 pointer s8 set procedure pointer s8 set PTR N procedure set pointer s8 ref PTR N Stores the signed byte N at the address designated by PTR 30 1 22 pointer u16 set procedure pointer ul6 set PTR N procedure set pointer ul6 ref PTR N Stores the unsigned 16 bit integer N at the address designated by PTR 30 1 17 pointer s32 ref 198 CHICKEN User s Manual The User s Manual 30 1 23 pointer s16 set procedure pointer s16 set PTR N procedure set pointer s16 ref PTR N Stores the signed 16 bit integer N at the address designated by PTR 30 1 24 pointer u32 set procedure pointer u32 set PTR N procedure set pointer u32 ref PTR N Stores the unsigned 32 bit integer N at the address designated by PTR 30 1 25 pointer s32 set procedure pointer s32 set PTR N procedure set pointer s32 ref PTR N Stores the 32 bit integer N at the address designated by PTR 30 1 26 pointer f32 set procedure pointer f32 set PTR N procedure set pointer f32 ref PTR N Stores the 32 bit floating point number N at the address designated by PTR 30 1 27 pointer f64 set procedure pointer f64 set PTR N procedure set pointer f64 ref PTR N Stores the 64 bit floating point number N at the address designated by PTR 30 1 28 align to word procedure alig
148. e the expression define x list 1 list 2 3 match x set setit setit 4 mutates the cadadr of X to 4 so that Xis 1 2 4 get identifier matches anything and binds identifier to a procedure of zero arguments that accesses the corresponding field of the matching value This pattern is the complement to set As with set this pattern must be nested within a pair vector box or structure pattern Quasipatterns Quasiquote introduces a quasipattern in which identifiers are considered to be symbolic constants Like Scheme s quasiquote for data unquote and unquote splicing escape back to normal patterns 11 2 Patterns 55 CHICKEN User s Manual The User s Manual 11 3 Match Failure If no clause matches the value the default action is to invoke the procedure match error procedure with the value that did not match The default definition of match error procedure calls error with an appropriate message 1 gt match 1 2 2 Failed match Error no matching clause for 1 For most situations this behavior is adequate but it can be changed by altering the value of the parameter match error control procedure match error control match error control MODE Selects a mode that specifies how match macro forms are to be expanded With no argument this procedure returns the current mode A single argument specifies the new mode that decides what should happen if no match clause
149. e all i k C DH E VIP 3 gt 5 3 Toplevel commands The toplevel loop understands a number of special commands 32 Show summary of available toplevel commands J FILENAME Load files with given FILENAMEs In FILENAME Load files and print result s of each top level expression p EXP Pretty print evaluated expression EXP d EXP Describe result of evaluated expression EXP du EXP Dump contents of the result of evaluated expression EXP ur EXP N Dump N bytes of the result of evaluated expression EXP exn Describes the last exception that occurred and adds it to the result history it can be accessed using the notation q Quit the interpreter T Show system information S TEXT Execute shell command EXP Evaluate form and print elapsed time x EXP Pretty print macroexpanded expression EXP the expression is not evaluated t SYMBOL Enables tracing of the toplevel procedures with the given names 1 gt fac 10 3628800 2 gt tr fac 3 gt fac 3 fac 3 fac 2 5 2 Writing Scheme scripts 26 CHICKEN User s Manual The User s Manual fac 1 fac 0 fac gt 1 fac gt 1 fac gt 2 fac gt 6 gt 6 4 gt utr fac 5 gt fac 3 gt 6 k tr SYMBOL Disables tracing of the given toplevel procedures br SYMBOL Sets a breakpoint at the procedures named SYMBOL Breakpoint can also be trigged using the breakpoint procedure ubr SYMBOL
150. e new language features A typical Scheme system therefore complies with one of the Scheme reports plus some or all of the accepted SRFIs A good starting point for Scheme knowledge is http www schemers org There you will find the defining reports FAQs lists of useful books and other resources and the SRFIs The Chicken community is at present developing tutorials for programmers who are new to Scheme but experienced with Python Ruby or other languages These can be found on the Chicken wiki 2 2 Chicken Chicken is an implementation of Scheme that has many advantages Chicken Scheme combines an optimising compiler with a reasonably fast interpreter It supports almost all of RSRS and the important SRFIs The compiler generates portable C 2 Getting started 2 CHICKEN User s Manual The User s Manual code that supports tail recursion first class continuations and lightweight threads and the interface to and from C libraries is flexible efficient and easy to use There are hundreds of contributed Chicken libraries that make the programmer s task easier The interpreter allows interactive use fast prototyping debugging and scripting The active and helpful Chicken community fixes bugs and provides support Extensive documentation is supplied Chicken was developed by Felix L Winkelmann over the period from 2000 through 2007 In early 2008 Felix asked the community to take over the responsibility of developing and maintaining
151. e the C_ return macro instead of the normal return statement to return a result from the foreign lambda body as some cleanup code has to be run before execution commences in the calling code 32 10 foreign safe lambda syntax foreign safe lambda RETURNTYPE NAME ARGTYPE This is similar to foreign Lambda but also allows the called function to call Scheme functions and allocate Scheme data objects See Callbacks 32 11 foreign safe lambda syntax foreign safe lambda RETURNTYPE ARGTYPE VARIABLE STRING This is similar to foreign lambda but also allows the called function to call Scheme functions and allocate Scheme data objects See Callbacks 32 12 foreign primitive syntax foreign primitive RETURNTYPE ARGTYPE VARIABLE STRING This is also similar to foreign Lambda but the code will be executed in a primitive CPS context which means it will not actually return but call it s continuation on exit This means that code inside this form may allocate Scheme data on the C stack the nursery with C alloc see below If the RETURNTYPE is omitted it defaults to void You can return multiple values inside the body of the foreign primitive form by calling this C function C values N 2 C SCHEME UNDEFINED C k X1 where N is the number of values to be returned and X1 are the results which should be Scheme data objects When returning multiple values the return type should be omitted Previous Int
152. ectory procedure create directory NAME optional PARENTS Creates a directory with the pathname NAME If the PARENTS argument is given and not false any nonextant parent directories are also created 27 2 4 delete directory procedure delete directory NAME Deletes the directory with the pathname NAME The directory has to be empty 27 2 5 directory procedure directory PATHNAME SHOW DOTFILES Returns a list with all files that are contained in the directory with the name PATHNAME which defaults to the value of current directory Files beginning with are included only if SHOW DOTFILES is given and not f 27 2 6 directory procedure directory NAME Returns t if there exists a file with the name NAME and if that file is a directory or f otherwise 27 2 7 glob procedure glob PATTERN1 27 2 2 current directory 151 CHICKEN User s Manual The User s Manual Returns a list of the pathnames of all existing files matching PATTERN1 which should be strings containing the usual file patterns with matching zero or more characters and matching zero or one character Bug wildcard characters are only recognized in the rightmost portion of the pattern 27 2 8 canonical path procedure canonical path NAME Returns a canonical path for NAME which should be a string containing a path or filename The string returned by Canonical path is OS dependent it may be quoted and used in a shell o
153. ed 27 10 4 current group id procedure current group id setter set current group id GID Get or set the real group id of the current process 27 10 5 current effective group id procedure current effective group id setter set current effective group id GID Get or set the effective group id of the current process ID can be found then f is returned 27 10 6 group information procedure group information GROUP If GROUP specifies a valid group name or group id then this procedure returns a list of four values the group name the encrypted group password the group ID and a list of the names of all group members If no group with the given name or ID exists then f is returned 27 10 7 get groups procedure get groups Returns a list with the supplementary group IDs of the current user 27 10 3 user information 165 CHICKEN User s Manual The User s Manual 27 11 Changing user amp group information 27 11 1 set groups procedure set groups GIDLIST Sets the supplementrary group IDs of the current user to the IDs given in the list GIDLIST Only the superuser may invoke this procedure 27 11 2 initialize groups procedure initialize groups USERNAME BASEGID Sets the supplementrary group IDs of the current user to the IDs from the user with name USERNAME a string including BASEGID Only the superuser may invoke this procedure 27 11 3 set process group id procedure set
154. edures or all if no symbols are specified are never globally redefined If not is specified then all but the given standard bindings are assumed to be never redefined 12 30 extended bindings declaration specifier extended bindings SYMBOL declaration specifier not extended bindings SYMBOL Declares that all given non standard and CHICKEN specific procedures or all if no symbols are specified are never globally redefined If not is specified then all but the given extended bindings are assumed to be never redefined 12 31 usual integrations declaration specifier usual integrations SYMBOL declaration specifier not usual integrations SYMBOL Declares that all given standard and extended bindings or all if no symbols are specified are never globally redefined If not is specified then all but the given standard and extended bindings are assumed to be never redefined Note that this is the default behaviour unless the no usual integrations option has been given 12 32 unit declaration specifier unit SYMBOL Specify compilation unit name if this is a library 12 28 run time macros 63 CHICKEN User s Manual The User s Manual 12 33 unsafe declaration specifier unsafe declaration specifier not safe Do not generate safety checks This is the same as specifying the unsafe option Also implies declare no bound checks no procedure checks no argc checks 12 34 unused
155. egular expression wrapped in If invoked with a precompiled regular expression argument by using regexp string match is identical to string search 25 10 string search 25 11 string search positions procedure string search REGEXP STRING START RANGE procedure string search positions REGEXP STRING START RANGE Searches for the first match of the regular expression in REGEXP with STRING The search can be limited to RANGE characters 25 12 string split fields procedure string split fields REGEXP STRING MODE START 1 Splits STRING into a list of fields according to MODE where MODE can be the keyword infix REGEXP matches field separator the keyword suf f ix REGEXP matches field terminator or t REGEXP matches field which 1s the default define s this is a string 1 2 3 string split fields s gt this is a string 1 2 3 string split fields s infix gt this is a string 1 2 3 string split fields s suffix gt this is a string 1 2 3 25 9 string match positions 141 CHICKEN User s Manual The User s Manual 25 13 string substitute procedure string substitute REGEXP SUBST STRING MODE Searches substrings in STRING that match REGEXP and substitutes them with the string SUBST The substitution can contain references to subexpressions in REGEXP with the NUM notation where NUM refers to the NUMth parenthesi
156. en E 142 EU SOR LE 144 PAGE EE EE 144 26 2 TOPE Ee E TE 144 26 3 Re E E RTE 145 26 4 thread Sus E EE 145 26 5 thread feSuiIMme EEN 145 26 6 UCET VETE TT UU Tm EXT 145 Zo omemllseconds nennen enne ee eene emen ennt eniti tenete nee nn n anis anne sese aiia 145 en Ee E EE 145 EXACTES 147 Def GEET EE 147 27 1 1 File control Command sys ssccceseseseasassscsoacescoseaccsasosscacssocsesvaveeessvavscisvvevsdanvnansabnvacavanadeces 147 27 1 2 Standard I O Ge descrptors essent 147 DT MS CYP OM HEEN 148 2 LAA uo sro MUTTER 149 21 2 eer 150 21 DA CMAN C C EE 150 212 2 CUMeML GIPECUOLY AE E E E E E E 151 Ee E 151 212A delete dir ctoty id otn aet OR EGO BO FERE OI DE EUREN OY e Cr RE RED TR Ee uk dS 151 D1 DD OIE CLOLY RT 151 EE re 151 ET 151 27 28 CamOniGal path 1 edo etr eer d Ee Ee ERE spies ss vhasau E MERE CREER ES EEEE ESTEE 152 EE TE Me It poeta ied eee Gasca sei ces e E heed eade e nee eun 152 E D iecur 152 21 9 T callewith mput pipe ecce ertet eet dent e tee reed abes Feo ane rada eie te Eee Ane RE ren ded 152 E Eet E EE 152 21 3 3 ClOSE INDUL PIPE EE 153 21 3 4 close o tput pIpe onerosa er eu RN Pe geed cued cduneacesteessasteyadeaus 153 Dil B D Create DIDG eot ien Han aeter e tette tte AEE T 153 27 3 6 ET E E TE 153 27 3 7 OPED OULPUL DIDEs E 153 21 328 e e E 153 21 3 9 WAth 1PUt MOM E 154 27 3 10 wathi out
157. en inlining is enabled only for the specified global procedures The negated forms not inline and not inline IDENTIFIER disable global inlining or inlining for the given global procedures only respectively 12 12 emit external prototypes first 60 CHICKEN User s Manual The User s Manual 12 17 inline limit declaration specifier inline limit THRESHOLD Sets the maximum size of procedures which may potentially be inlined The default threshold is 10 12 18 interrupts enabled declaration specifier interrupts enabled Enable timer interrupts checks in the compiled program the default 12 19 keep shadowed macros declaration specifier keep shadowed macros Normally when a toplevel variable is assigned or defined that has the same name as a macro the macro definition will be removed in addition to showing a warning This declaration will disable the removal of the macro 12 20 lambda lift declaration specifier lambda lift Enables lambda lifting equivalent to the Lambda Lift option 12 21 link options declaration specifier link options STRING Declares additional linker compiler options that are to be passed to the subsequent compilation pass that links the generated code into an executable or library This declaration will only work if the source file is compiled with the CSC compiler driver 12 17 inline limit 61 CHICKEN User s Manual The User s Manual 12 22 no argc checks declaration s
158. entifier matches anything and binds identifier as a variab anything itself the empty List t itself f itself string an equal string 11 Pattern matching 52 CHICKEN User s Manual The User s Manual number an equal number character an equal character Ss expression an equal s expression pat 1 pat n a proper list of n elements pat 1 pat n pat n 1 a list of n or more elements pat 1 pat n pat n 1 k a proper list of n k or more elements 1 pat 1 pat n a vector of n elements pat 1 pat n pat n 1 k a vector of n k or more elements struct pat 1 pat n a structure field pat a field of a structure and pat 1 pat n if all of pat 1 through pat n match or pat 1 pat n if any of pat 1 through pat n match not pat 1 pat n if none of pat 1 through pat n match predicate pat 1 pat n if predicate true and pat 1 through pat n all matc set identifier anything and binds identifier as a setter get identifier anything and binds identifier as a getter gp a quasipattern qp itself the empty List st itself f itself string an equal string number an equal number character an equal character symbol an equal symbol qp 1 qp n a proper list of n elements qp 1 qp n qp n 1 a list of n or more elements qp 1 qp n qp n 1 k a proper list of n k or more e
159. equence bsr anycrlf NR escape sequence matches only CR LF or CRLF bsr unicode RI escape sequence matches only Unicode newline sequence dfa shortest Currently unused dfa restart Currently unused 25 6 regexp procedure regexp X Returns t if X is a precompiled regular expression or f otherwise 25 7 regexp optimize procedure regexp optimize RX Perform available optimizations for the precompiled regular expression RX Returns t when optimization performed and f otherwise 25 8 string match 25 5 regexp 140 CHICKEN User s Manual The User s Manual 25 9 string match positions procedure string match REGEXP STRING START procedure string match positions REGEXP STRING START Matches the regular expression in REGEXP a string or a precompiled regular expression with STRING and returns either f if the match failed or a list of matching groups where the first element is the complete match If the optional argument START is supplied it specifies the starting position in STRING For each matching group the result list contains either f for a non matching but optional group a list of start and end position of the match in STRING in the case of String match positions or the matching substring in the case of string match Note that the exact string is matched For searching a pattern inside a string see below Note also that st ring match is implemented by calling string search with the r
160. er an error will work unexpectedly or even crash the running application It is advisable to develop and debug a program in safe mode without unsafe declarations and use this feature only if the application works properly 42 5 5 Why do I get a warning when I define a global variable named match Even when the mat ch unit is not used the macros from that package are visible in the compiler The reason for this is that macros can not be accessed from library units only when explicitly evaluated in running code To speed up macro expansion time the compiler and the interpreter both already provide the compiled match macro definitions Macros shadowed lexically are no problem but global definitions of variables named identically to global macros are useless the macro definition shadows the global variable This problem can be solved using a different name or undefining the macro like this eval when compile eval undefine macro match 42 5 1 Why does my program crash when I use callback functions fromScheme to C and back to Scheme Ain CHICKEN User s Manual The User s Manual 42 5 6 Why don t toplevel continuations captured in interpreted code work Consider the following piece of code define k call with current continuation lambda k k k k When compiled this will loop endlessly But when interpreted k k will return to the read eval print loop This happens because the continuation captured will event
161. er defined named characterg e eene nennen ee enen eene n nennen nente tenete nene ne nennen 84 14 161 EE EE 84 VA MP En 85 1417 Ee EE 85 14 172 ee 85 EAS Me ee EE 85 E WE EC ee Gr E 85 14 175 Stati g DIOD E 85 ER e Reie 86 14 18 e e 86 1418 L vector Copy EE 86 14 RER E 86 14 19 The unspecttied E 86 VA MO e EE 86 CHICKEN User s Manual The User s Manual Chicken User s Manual 14 Unit library Ee OOM CIM ET EE 86 VA 20 Ae 87 1420 2 COMMMU ler ET 87 1420 3 Ser E LR 87 E Wel Eeler E 87 14 205 COntINUAtLOM Pe EE 87 TAS 2D Setters ER 88 IPAE T 88 14 21 2 etter WIith SGtt amp t uiis ette retra den tk eate eee ee eiei e e ae enne dee nee e bete Re svi ene eue 88 14 22 el E EE 88 14 22 Leet Eelere ege ee 88 14 222 SEU TEAG S VMAX E 88 14 22 5 set sh rp read syfitaxl iue eet rtt iniii oreet Ue te C ene ene oia piaia etse 80 14 22 4 set parameterized read SyMtax lo eterne nennen enne en nennen 80 14 22 5 Ee E EE 89 14 23 Property EE 90 E GE 90 1423 2 TT 90 1423 3 TEMIPLOD E 90 14 23 Asy mbob E EE 90 1423 ET 90 EI EE 92 15 1 Beie e 92 LESEN ME Co DEE 92 B Aere Dee E VE 92 15 1 3 ME E TEE 93 DMA WO APHID e EE 93 15 1 5 set dynamic load mode esses esent enne 93 Ee Re EE Eer 94 INA EE 94 15 3 MACOS ENT uu 94 Jet MUM ESE seened eet see eh Sege erg Ee e eege 94 Be ge See e E 94 15 3 3 MACCOEK EE 94 l5 AMmacroe
162. erator a tool that produces quick and dirty interface modules for C libraries http www swig org This chapter provides you with an overview of the entire system with enough information to get started writing and running small Scheme programs Subsequent chapters cover Basic mode of operation Compiling Scheme files Using the compiler Explains how to use Chicken to compile programs and execute them e Using the interpreter Invocation and usage of CS1 the Chicken interpreter e Supported language The language implemented by Chicken deviations from the standard and extensions Interface to external functions and variables Accessing C and C code and data chicken setup Packaging and installing extension libraries Data representation How Scheme data is internally represented Bugs and limitations Yes there are some FAQ A list of Frequently Asked Questions about Chicken and their answers Acknowledgements A list of some of the people that have contributed to make Chicken what it is Bibliography Links to documents that may be of interest 2 3 Chicken repositories websites and community At present the URLs for Chicken information and download are somewhat confusing It is envisaged that everything will eventually be accessible via the domain chi cken scheme org but this hasn t been completely done At present the master Chicken website is http www call with current continuation org Here y
163. ere we create a simple application 2 23 hello2 scm print Hello for each lambda x printf A x command line arguments print We also need a setup script iii hello2 setup compile hello2 scm compile hello2 install program hello2 hello2 name of the extension and files to be inst To use it just run chi cken setup in the same directory chicken setup Here we omit the extension name Now the program hello2 will be installed in the same location as the other CHICKEN tools like chicken csi etc which will normally be usr local bin Note that you need write permissions for those locations and may have to run chicken setup with administrative rights Uninstallation is just as easy chicken setup uninstall hello2 chicken setup provides a make macro so build operations can be of arbitrary complexity When running chicken setup with an argument NAME for which no associated file NAME setup NAME egg or NAME scm exists will ask you to download the extension via HTTP from the default URL http www call with current continuation org eggs You can use the host option to specify an alternative source location Extensions that are required to compile and or use the requested extension are downloaded and installed automatically If the given extension name contains a path prefix and the host option is given then chicken setup 39 5 Examples for extensions 253 CHICKEN User s Manu
164. erface to external functions and variables Next Foreign type specifiers 32 9 foreign lambda 215 CHICKEN User s Manual The User s Manual 32 12 foreign primitive 216 33 Foreign type specifiers Here is a list of valid foreign type specifiers 33 1 scheme object An arbitrary Scheme data object immediate or non immediate 33 2 bool As argument any value f is false anything else is true As result anything different from 0 and the NULL pointer is t 33 3 byte unsigned byte A byte 33 4 char unsigned char A character 33 5 short unsigned short A short integer number 33 6 int unsigned int int32 unsigned int32 An small integer number in fixnum range at least 30 bit 33 Foreign type specifiers 217 CHICKEN User s Manual The User s Manual 33 7 integer unsigned integer integer32 unsigned integer32 integer64 Either a fixnum or a flonum in the range of a unsigned machine int or with 32 64 bit width 33 8 long unsigned long Either a fixnum or a flonum in the range of a unsigned machine Jong or with 32 bit width 33 9 float double A floating point number If an exact integer is passed as an argument then it is automatically converted to a float 33 10 number A floating point number Similar to doubLe but when used as a result type then either an exact integer or a floating point number is returned depending on whether the result fits into an exact integer or not 33 11 sym
165. es that are defined and used in a compiled source file are evaluated during compilation and so have no access to anything created with define Use def ine for syntax instead 42 4 2 Why isn t load properly loading my library of macros During compile time macros are only available in the source file in which they are defined Files included via include are considered part of the containing file 42 4 3 Why is include unable to load my hygienic macros It is not sufficient for the included file to require the syntax case extension Call require extension syntax case before calling include 42 4 4 Why are macros not visible outside of the compilation unit in which they are defined Macros are defined during compile time so when a file has been compiled the definitions are gone An exception to this rule are macros defined with def ine macro which are also visible at run time i e in eval To use macros defined in other files use the include special form 42 5 Warnings and errors 42 5 1 Why does my program crash when I use callback functions from Scheme to C and back to Scheme again There are two reasons why code involving callbacks can crash out of no apparent reason 1 It is important to use foreign safe lambda foreign safe Lambda for the C code that is to call back into Scheme If this is not done than sooner or later the available stack space will be exhausted 2 If the C code uses a large amount of stack storage or i
166. espectively 26 7 timemilliseconds procedure time gt milliseconds TIME Converts a time object as created via Current time into an exact integer representing the number of milliseconds since process startup 26 8 millisecondstime procedure milliseconds gt time ms Converts into a time object an exact integer representing the number of milliseconds since process startup This procedure may be useful in combination with thread sleep when your compilation unit is using declare fixnum arithmetic In that case you won t be able to pass an inexact value to 26 3 thread quantum set 145 CHICKEN User s Manual The User s Manual thread sleep but you can do the following define thread sleep ms ms thread sleep milliseconds gt time ms current milliseconds Previous Unit regex Next Unit posix 26 8 millisecondstime 146 27 Unit posix This unit provides services as used on many UNIX like systems Note that the following definitions are not all available on non UNIX systems like Windows See below for Windows specific notes This unit uses the regex scheduler extras and utils units All errors related to failing file operations will signal a condition of kind exn i o file 27 1 Constants 27 1 1 File control Commands 27 1 1 1 fcntl dupfd 27 1 1 2 fcntl getfd 27 1 1 3 fcntl setfd 27 1 1 4 fcntl getfl 27 1 1 5 fcntl setfl 27 1 2 Standard I O file descriptors 27 1 2 1 fileno stdi
167. ess run COMMAND ARGUMENT LIST Creates a new child process The PID of the new process is returned The single parameter version passes the COMMANDLINE to the system shell so usual argument expansion can take place The multiple parameter version directly invokes the COMMAND with the ARGUMENT LIST 27 8 7 process signal procedure process signal PID SIGNAL Sends SIGNAL to the process with the id PID using the UNIX system call kill SIGNAL defaults to the value of the variable signal term 27 8 8 process wait procedure process wait PID NOHANG Suspends the current process until the child process with the id PID has terminated using the UNIX system call waitpid If PID is not given then this procedure waits for any child process If NOHANG is given and not f then the current process is not suspended This procedure returns three values e PID or 0 if NOHANG is true and the child process has not terminated yet e t if the process exited normally or f otherwise either the exit status if the process terminated normally or the signal number that terminated stopped the process 27 8 9 process procedure process COMMANDLINE procedure process COMMAND ARGUMENT LIST ENVIRONMENT LIST Creates a subprocess and returns three values an input port from which data written by the sub process can be read an output port from which any data written to will be received as input in the sub process and the process
168. essing documentation You can access the manual directly from CSi using the man extension by Mario Domenech Goulart To enable it install the egg and put this in your CSi rc file use man man Load Then in CSi you can search for definitions using man search as in man search case 5 6 set describer 28 CHICKEN User s Manual The User s Manual Note that the search uses regular expressions To view the documentation for one entry from the manual use man help as in man help case lambda Note Currently the documentation provided by the man extension corresponds to Chicken s 2 429 one of the last releases whose documentation was in the texinfo format the format the man extension parses Previous Using the compiler Next Supported language 5 8 Accessing documentation 29 6 Supported language Deviations from the standard e Extensions to the standard e Non standard read syntax e Non standard macros and special forms Pattern matching Declarations Parameters Unit library basic Scheme definitions Unit eval evaluation and macro handling Unit data structures data structures Unit ports I O ports Unit extras useful utility definitions Unit srfi 1 list library Unit srfi 4 homogeneous numeric vectors Unit srfi 13 string library Unit srfi 14 character set library Unit srfi 69 hash tables Unit match pattern matching runtime support Unit regex regular expressio
169. etsid create symbolic link Link current directory curdir current effective groupd id getegid current effective user id geteuid current group id getgid current parent id getppid current process id getpid current user id getuid delete directory rmdir duplicate fileno dup dup2 exit exit file close close file access time stat file change time stat file modification time stat file execute access access file open open file lock fcntl file position ftell lseek file read read file read access access file select select file control fcntl file stat stat file test lock 27 23 How Scheme procedures relate to UNIX C functions 179 CHICKEN User s Manual The User s Manual fcntl file truncate truncate ftruncate file unlock fcntl file write write file write access access get groups getgroups get host name gethostname initialize groups initgroups local time gt seconds mktime local timezone abbreviation localtime map file to memory mmap open input file fdopen open output file fdopen open input pipe popen open output pipe popen port gt fileno fileno process execute execvp process fork fork process group id getpgid process signal kill process wait waitpid close input pipe pclose close output pipe pclose read symbolic link readlink seconds gt Llocal time localtime seconds string ctime seconds gt utc time gmtime set alarm 27 23 How Scheme pro
170. eturns to the invoking context that called CHICKEN_ run or CHICKEN continue After return to host has been executed and once CHICKEN run returns you can invoke callbacks which have been defined with def ine external The eval library unit also provides boilerplate callbacks that simplify invoking Scheme code embedded in a C or C application a lot 34 5 CHICKEN eval C macro int CHICKEN eval C word exp C word result Evaluates the Scheme object passed in exp writing the result value to result The return value is 1 if the operation succeeded or 0 if an error occurred Call CHICKEN get error message to obtain a description of the error 34 6 CHICKEN eval string C macro int CHICKEN eval string char str C word result Evaluates the Scheme expression passed in the string Str writing the result value to result 34 7 CHICKEN eval to string C macro int CHICKEN eval to string C word exp char result int size Evaluates the Scheme expression passed in exp writing a textual representation of the result into result Size should specify the maximal size of the result string 34 8 CHICKEN eval string to string C macro int CHICKEN eval string to string char str char result int size Evaluates the Scheme expression passed in the string Str writing a textual representation of the result into result size should specify the maximal size of the result string 34 4 return to host 225 CHICKEN User s Manual The User s
171. extension property static options STRING Additional options that should be passed to the linker when linking with the static version of an extension see Static above Used by CSC when compiling with the static extensions option All other properties are currently ignored The FILELIST argument may also be a single string 39 4 2 install program procedure install program ID FILELIST INFOLIST Similar to install extension but installs an executable program in the executable path usually usr local bin 39 4 3 install script procedure install script ID FILELIST INFOLIST Similar to instal l program but additionally changes the file permissions of all files in FILELIST to executable for installing shell scripts 39 4 4 run syntax run FORM Runs the shell command FORM which is wrapped in an implicit quasiquote run csc is treated specially and passes V if verbose has been given to chicken setup and feature compiling extension options to the compiler 39 4 5 compile syntax compile FORM Equivalent to run csc FORM 39 4 1 install extension 248 CHICKEN User s Manual The User s Manual 39 4 6 make syntax make TARGET DEPENDENT COMMAND ARGUMENTS A make macro that executes the expressions COMMAND when any of the dependents DEPENDENT have changed to build TARGET This is the same as the make extension which is available separately For mo
172. f Scheme to C to Scheme calls are nested deeply then the available nursery space on the stack will run low To avoid this it might be advisable to run the compiled code with a larger nursery setting i e run the code with S anda larger value than the default for example 300k or use the nursery compiler option Note that this 42 4 Compiled macros 268 CHICKEN User s Manual The User s Manual can decrease runtime performance on some platforms 42 5 2 Why does the linker complain about a missing function _C_ _toplevel This message indicates that your program uses a library unit but that the object file or library was not supplied to the linker If you have the unit foo which is contained in f 00 0 than you have to supply it to the linker like this assuming a GCC environment CSC program scm foo o o program 42 5 3 Why does the linker complain about a missing function _C_toplevel This means you have compiled a library unit as an application When a unit declaration as in declare unit is given then this file has a specially named toplevel entry procedure Just remove the declaration or compile this file to an object module and link it to your application code 42 5 4 Why does my program crash when I compile a file with unsafe or unsafe declarations The compiler option unsafe or the declaration declare unsafe disable certain safety checks to improve performance so code that would normally trigg
173. flavor and extensions provided by this library To test that PCRE support has been built into Chicken properly try require regex feature pcre t 25 1 grep procedure grep REGEX LIST Returns all items of LIST that match the regular expression REGEX This procedure could be defined as follows define grep regex lst filter lambda x string search regex x lst 25 2 globregexp procedure glob gt regexp PATTERN Converts the file pattern PATTERN into a regular expression glob gt regexp foo z ERAN TOO PATTERN should follow glob syntax Allowed wildcards are C C1 C2 C 25 3 glob procedure glob STRING Does the STRING have any glob wildcards A string without any glob wildcards does not meet the criteria even though it technically is a valid glob file pattern 25 Unit regex 138 CHICKEN User s Manual The User s Manual 25 4 regexp procedure regexp STRING IGNORECASE IGNORESPACE UTF8 Returns a precompiled regular expression object for St ring The optional arguments IGNORECASE IGNORESPACE and UTF8 specify whether the regular expression should be matched with case or whitespace differences ignored or whether the string should be treated as containing UTF 8 encoded characters respectively 25 5 regexp procedure regexp STRING OPTIONS TABLES Returns a precompiled regular expression object for st ring The option
174. for the first property with a key in the list PROPERTIES Returns 3 values the matching property key value and the tail of property list after the matching property When no match found all values are f 14 23 Property lists 90 CHICKEN User s Manual The User s Manual PROPERTIES may also be an atom in which case it is treated as a list of one element Previous Parameters Next Unit eval 14 23 5 get properties 91 15 Unit eval This unit has support for evaluation and macro handling This unit is used by default unless the program is compiled with the explicit use option 15 1 Loading code 15 1 1 load procedure load FILE EVALPROC Loads and evaluates expressions from the given source file which may be either a string or an input port Each expression read is passed to EVALPROC which defaults to eval On platforms that support it currently native Windows Linux ELF and Solaris Load can be used to load compiled programs cat x scm define hello print Hello CSC S X SCM csi q 1 gt load x so loading x so 2 gt hello Hello 3 gt The second argument to Load is ignored when loading compiled code If source code is loaded from a port then that port is closed after all expressions have been read Compiled code can be re loaded but care has to be taken if code from the replaced dynamically loaded module is still executing i e if an active continuation refers to co
175. from a structure field may be any expression it is applied to the value being matched and the result of this application is matched against pat and pat 1 pat n matches if all of the subpatterns match At least one subpattern must be present This pattern is often used as and x pat to bind x to to the entire value that matches pat cf as patterns in ML or Haskell or pat 1 pat n matches if any of the subpatterns match At least one subpattern must be present All subpatterns must bind the same set of pattern variables not pat 1 pat n matches if none of the subpatterns match At least one subpattern must be present The subpatterns may not bind any pattern variables predicate pat 1 pat n Inthis pattern predicate must be an expression evaluating to a single argument function This pattern matches if predicate applied to the corresponding value is true and the subpatterns pat 1 pat n all match The predicate should not have side effects as the code generated by the pattern matcher may invoke predicates repeatedly in any order The predicate expression is bound in the same scope as the match expression i e free variables in predicate are not bound by pattern variables set identifier matches anything and binds identifier to a procedure of one argument that mutates the corresponding field of the matching value This pattern must be nested within a pair vector box or structure pattern For exampl
176. g extension libraries This functionality is only available on platforms that support dynamic loading of compiled code Currently Linux BSD Solaris Windows with Cygwin and HP UX are supported 15 4 1 repository path parameter repository path Contains a string naming the path to the extension repository which defaults to either the value of the environment variable CHICKEN REPOSITORY or the default library path usually usr local lib chicken on UNIX systems 15 4 2 extension information procedure extension information ID If an extension with the name ID is installed and if it has a setup information list registered in the extension repository then the info list is returned Otherwise extension information returns f 15 3 4 macroexpand 1 95 CHICKEN User s Manual The User s Manual 15 4 3 provide procedure provide ID Registers the extension IDs ID as loaded This is mainly intended to provide aliases for certain extension identifiers 15 4 4 provided procedure provided ID Returns t if the extension with the IDs ID are currently loaded or f otherwise 15 4 5 require procedure require ID procedure require for syntax ID If the extension library ID is not already loaded into the system then require will lookup the location of the shared extension library and load it If ID names a library unit of the base system then it is loaded via load library If no extension l
177. gg does not exist in the current directory Various command line options exist for customizing the process and or retrieving the egg from other locations or in other formats 39 2 Installing extensions To install an extension library run the chicken setup program with the extension name as argument The extension archive is downloaded its contents extracted and the contained setup script is executed This setup script is a normal Scheme source file which will be interpreted by chicken setup The complete language supported by CS1 is available and the library units srfi 1 regex utils posix tcp are loaded Additional libraries can be loaded at run time The setup script should perform all necessary steps to build the new library or application After a successful build the extension can be installed by invoking one of the procedures install extension install programorinstall script These procedures will copy a number of given files into the extension repository or in the path where the CHICKEN executables are located in the case of executable programs or scripts Additionally the list of installed files and user defined metadata is stored in the repository If no extension name is given on the command line and if none of the options List version repository without argument program path without argument fetch fetch tree or docindex is given then all setup scripts in the current directory are processed 39 2 1 In
178. gs in XXX XXX XXX XXX notation 29 10 tcp port numbers procedure tcp port numbers PORT Returns two values for the input or output port PORT which should be a port returned by either tcp accept or tcp connect the TCP port numbers of the local and the remote machine that are connected over the socket associated with PORT 29 11 tcp abandon port procedure tcp abandon port PORT Marks the socket port PORT as abandoned This is mainly useful to close down a port without breaking the connection 29 12 tcp buffer size parameter tcp buffer size Sets the size of the output buffer By default no output buffering for TCP output is done but to improve performance by minimizing the number of TCP packets buffering may be turned on by setting this parameter to an exact integer greater zero A buffer size of zero or f turns buffering off The setting of this parameter takes effect at the time when the I O ports for a particular socket are created i e when t cp connect or tcp accept is called Note that since output is not immediately written to the associated socket you may need to call flush output once you want the output to be transmitted Closing the output port will flush automatically 29 13 tcp read timeout parameter tcp read timeout Determines the timeout for TCP read operations in milliseconds A timeout of f disables timeout checking The default read timeout is 60000 i e 1 minute 29 9 tcp addresses 192
179. gument a string CLOSE is called when the port is closed and should be a procedure of no arguments FLUSH if provided is called for flushing the output port 17 1 4 with error output to port procedure with error output to port PORT THUNK Call procedure THUNK with the current error output port temporarily bound to PORT 17 Unit ports 110 CHICKEN User s Manual The User s Manual 17 1 5 with input from port procedure with input from port PORT THUNK Call procedure THUNK with the current input port temporarily bound to PORT 17 2 String port extensions 17 2 1 call with input string procedure call with input string STRING PROC Calls the procedure PROC with a single argument that is a string input port with the contents of STRING 17 2 2 call with output string procedure call with output string PROC Calls the procedure PROC with a single argument that is a string output port Returns the accumulated output string 17 2 3 with input from string procedure with input from string STRING THUNK Call procedure THUNK with the current input port temporarily bound to an input string port with the contents of STRING 17 2 4 with output to string procedure with output to string THUNK Call procedure THUNK with the current output port temporarily bound to a string output port and return the accumulated output string 17 1 5 with input from port 111 CHICKEN User s Manual The User s Manual 17 3 Port ite
180. h X placed between each element 16 1 5 butlast 99 CHICKEN User s Manual The User s Manual 16 1 10 join procedure join LISTOFLISTS LIST Concatenates the lists in LISTOFLISTS with LIST placed between each sublist LIST defaults to the empty list e join r s t a b cd join p q join could be implemented as follows define join lstoflsts optional lst apply append intersperse lstoflists lst 16 1 11 shuffle procedure shuffle LIST RANDOM Returns LIST with its elements sorted in a random order given by procedure RANDOM 16 1 12 tail procedure tail X LIST Returns true if X is one of the tails cdr s of LIST 16 2 Queues 16 2 1 listqueue procedure list gt queue LIST Returns LIST converted into a queue where the first element of the list is the same as the first element of the queue The resulting queue may share memory with the list and the list should not be modified after this operation 16 1 10 join 100 CHICKEN User s Manual The User s Manual 16 2 2 make queue procedure make queue Returns a newly created queue 16 2 3 queue procedure queue X Returns t if X is a queue or f otherwise 16 2 4 queuelist procedure queue list QUEUE Returns QUEUE converted into a list where the first element of the list is the same as the first element of the queue The resulting list may share memory with the queue object and sh
181. he analysis pass the program database the current node graph a getter and a setter procedure which can be used to access and manipulate the program database which holds various information about the compiled program a pass iteration count and an analysis continuation flag The getter procedure should be called with two arguments a symbol representing the binding for which information should be retrieved and a symbol that specifies the database entry The current value of the database entry will be returned or f if no such entry is available The setter procedure is called with three arguments the symbol and key and the new value The pass iteration count currently is meaningful only for the opt pass The analysis continuation flag will be f for the last opt pass For information about the contents of the program database contact the author 4 4 Extending the compiler 21 CHICKEN User s Manual The User s Manual Loaded code via the extend option has access to the library units extras srfi 1 srfi 4 utils regex and the pattern matching macros Multithreading is not available Note that the macroexpansion canonicalization phase of the compiler adds certain forms to the source program These extra expressions are not seen by user preprocessor pass but by user pass 4 5 Distributing compiled C files It is relatively easy to create distributions of Scheme projects that have been compiled to C The runtime system of CHICKEN consists
182. he returned values are booleans indicating whether input output is ready by t or f otherwise You can also pass f as READFDLIST or WRITEFDLIST argument which is equivalent to 27 5 7 file write procedure file write FILENO BUFFER SIZE Writes the contents of the string or bytevector BUFFER into the file with the file descriptor FILENO If the optional argument SIZE is given then only the specified number of bytes are written 27 5 8 file control procedure file control FILENO COMMAND ARGUMENT Performs the fcntl operation COMMAND with the given FILENO and optional ARGUMENT The return value is meaningful depending on the COMMAND 27 5 9 open input file 27 5 5 file read 156 CHICKEN User s Manual The User s Manual 27 5 10 open output file procedure open input file FILENO OPENMODE procedure open output file FILENO OPENMODE Opens file for the file descriptor FILENO for input or output and returns a port FILENO should be a positive exact integer OPENMODE specifies an additional mode for opening the file currently only the keyword append is supported which opens an output file for appending 27 5 11 portfileno procedure port gt fileno PORT If PORT is a file or tcp port then a file descriptor is returned for this port Otherwise an error is signaled 27 6 Retrieving file attributes 27 6 1 file access time 27 6 2 file change time 27 6 3 file modification time procedure
183. hen removed and are converted to symbols Note that this parameter is invoked before processing of the extend option and so can only be changed in compiled user passes parameter user read pass Holds a procedure of three arguments The first argument is a list of strings with the code passed to the compiler via prelude options The second argument is a list of source files including any files specified by prologue and epilogue The third argument is a list of strings specified using postlude options The procedure should return a list of toplevel Scheme expressions parameter user preprocessor pass Holds a procedure of one argument This procedure is applied to each toplevel expression in the source file before macro expansion The result is macro expanded and compiled in place of the original expression parameter user pass Holds a procedure of one argument This procedure is applied to each toplevel expression after macro expansion The result of the procedure is then compiled in place of the original expression parameter user pass 2 Holds a procedure of three arguments which is called with the canonicalized node graph as its sole argument The result is ignored so this pass has to mutate the node structure to cause any effect parameter user post analysis pass Holds a procedure that will be called after every performed program analysis pass The procedure when defined will be called with seven arguments a symbol indicating t
184. i gue Eee Enea ee ARR ERE Dae Meses 198 SAS Bee ette e e t eee re e es en e ere a 199 SODA pointer u32 setl EE 199 30 1 25 Bee 199 30 1 26 ee E EE 199 90 1 27 pointer f04 Set i e oerte eter EE A E n EEA SE EEEE ENE ESEE 199 30 L28 align e E 199 30 2 Tagged e EE 200 30 2 1 tAg pOint EE 200 30 2 Ee E 200 SUP ACRI GC NNTT Ea 200 30 3 Extending procedures with data 200 30 3 1 Eeer 200 30 3 2 EE e E 201 30 33 procedure data 2c Atos uere dese Ve eee deer e Perth Vacs wan tust adectuvedeadessavedesssdedndessadauewedels 201 EAR Ee e 201 30 4 Data in unmanaged memorg nees ian innen nnns tnn sinn ne ntes enne s enne sten sister enne 201 30A TO E 201 xvi CHICKEN User s Manual The User s Manual Chicken User s Manual 30 Unit lolevel 30 4 2 Object CVICt tO lOCATION eee eecceesseceececeeeeeeeceeaaeceeaeeseaeecaeeesaeeseaaecseaeceeeecaeeesaeceeaaeseaeeceeeeess 202 S043 ENT OT 202 30 4 4 ODJECESI ZG EE 202 SOAS TO 202 SOA GODJECIUNEVICE EE 202 BOS EE 203 SE RRE 203 30 5 2 make weak Jocatwye eme KEERN KEKEE RNEER 203 30 5 5 06 dLEVOS EE TTE EE PEE XL EE EE 203 30 54 locative EE 203 30 5 5 e 204 30 5 6 eror belle iieii E a E EEEE ERE VNE EE OIRE ETE AERECO E 204 30 6 Accessia toplevel variables eter nette e etude e vase itd e iE e cudeuuceesveebenedeevodvenadenas 204 30 6 1 global bound eorr iret er ene ir rg Hon RR en RR REIR EFE Edere Pee god ga Ted Ya 204 SRPA A O EE 204
185. ibrary is available for the given ID then an attempt is made to load the file ID so or ID scm in that order from one of the following locations the current include path which defaults to the pathnames given in CHICKEN INCLUDE PATH the current directory ID should be a string or a symbol The difference between require and require for syntax is the the latter loads the extension library at compile time the argument is still evaluated while the former loads it at run time 15 4 6 set extension specifier procedure set extension specifier SYMBOL PROC Registers the handler procedure PROC as a extension specifier with the name SYMBOL This facility allows extending the set of valid extension specifiers to be used with require extension When register extension is called with an extension specifier of the form SPEC and SPEC has been registered with set extension specifier then PROC will be called with two arguments the specifier and the previously installed handler or f if no such handler was defined The handler should return a new specifier that will be processed recursively If the handler returns a vector then each element of the vector will be processed recursively Alternatively the handler may return a string which specifies a file to be loaded eval when compile eval set extension specifier my package Lambda spec old 15 4 3 provide 96 CHICKEN User s Manual The User s Manual make pathname my pa
186. ide explicit export information a exports file is searched as with used units After the analysis phase of the compiler referenced toplevel variables for which no assignment was found will generate a warning Also re assignments of imported variables will trigger a warning check syntax Aborts compilation process after macro expansion and syntax checks debug MODES Enables one or more compiler debugging modes MODES is a string of characters that select debugging information about the compiler that will be printed to standard output show time needed for compilation show breakdown of time needed for each compiler pass show performed optimizations show invocation parameters 7 O00 et 4 Using the compiler 13 CHICKEN User s Manual The User s Manual show program size information and other statistics show node matching during simplification show execution of compiler sub passes show lambda lifting information show GC statistics during compilation print the line number database print every expression before macro expansion lists all unassigned global variable references display information about experimental features when printing nodes use node tree output show the real name mapping table show expressions after the secondary user pass show database before lambda lifting pass show expressions after lambda lifting show unit information and syntax runtime requirements show source expressions show canonicalized expre
187. if N is zero Signum is exactness preserving 14 1 8 finite procedure finite N Returns f if N is negative or positive infinity and t otherwise 14 2 File Input Output 14 2 1 current output port procedure current output port PORT Returns default output port If PORT is given then that port is selected as the new current output port Note that the default output port is not buffered Use http galinha ucpel tche br Unit posix Setting the file buffering modelset buf fering mode if you need a different behavior 14 2 2 current error port procedure current error port PORT Returns default error output port If PORT is given then that port is selected as the new current error output port Note that the default error output port is not buffered Use http galinha ucpel tche br Unit posix Setting the file buffering modelset buf fering mode if you need a different behavior 14 2 3 flush output procedure flush output PORT Write buffered output to the given output port PORT defaults to the value of Current output port 14 1 7 signum 70 CHICKEN User s Manual The User s Manual 14 2 4 port name procedure port name PORT Fetch filename from PORT This returns the filename that was used to open this file Returns a special tag string enclosed into parentheses for non file ports PORT defaults to the value of current input port 14 2 5 port position procedure port posi
188. ign function interface dynamic 4 1 Compiler command line format 14 CHICKEN User s Manual The User s Manual This option should be used when compiling files intended to be loaded dynamically into a running Scheme program epilogue FILENAME Includes the file named FILENAME at the end of the compiled source file The include path is not searched This option may be given multiple times emit exports FILENAME Write exported toplevel variables to FILENAME emit external prototypes first Emit prototypes for callbacks defined with def ine external before any other foreign declarations This is sometimes useful when C C code embedded into the a Scheme program has to access the callbacks By default the prototypes are emitted after foreign declarations explicit use Disables automatic use of the units Library eval and extras Use this option if compiling a library unit instead of an application unit extend FILENAME Loads a Scheme source file or compiled Scheme program on systems that support it before compilation commences This feature can be used to extend the compiler This option may be given multiple times The file is also searched in the current include path and in the extension repository extension Mostly equivalent to prelude define extension lt NAME gt where NAME is the basename of the currently compiled file Note that if you want to compile a file as a normal dynamically loadable extension library you shou
189. ignal kill 27 13 11 signal int 27 13 12 signal hup 27 13 13 signal fpe 27 13 14 signal ill 27 13 15 signal segv 27 13 16 signal abrt 27 13 17 signal trap 27 13 18 signal quit 27 13 19 signal alrm 27 13 9 signal term 169 CHICKEN User s Manual The User s Manual 27 13 20 signal vtalrm 27 13 21 signal prof 27 13 22 signal io 27 13 23 signal urg 27 13 24 signal chld 27 13 25 signal cont 27 13 26 signal stop 27 13 27 signal tstp 27 13 28 signal pipe 27 13 29 signal xcpu 27 13 30 signal xfsz 27 13 20 signal vtalrm 170 CHICKEN User s Manual The User s Manual 27 13 31 signal usr1 27 13 32 signal usr2 27 13 33 signal winch These variables contain signal codes for use with process signal set signal handler signal handLler signal masked signal mask or Signal unmask 27 14 Environment access 27 14 1 current environment procedure current environment Returns a association list of the environment variables and their current values 27 14 2 setenv procedure setenv VARIABLE VALUE Sets the environment variable named VARIABLE to VALUE Both arguments should be strings If the variable is not defined in the environment a new definition is created 27 14 3 unsetenv procedure unsetenv VARIABLE Removes the definition of the environment variable VARIABLE from the environment of the current process If the variable is not defined nothing happens 27 13 31
190. ile is given then this form is evaluated at compile time When encountered while compiling code and the situation specifier Load is not given then this form is ignored and an expression resulting into an unspecified value is compiled instead The following table should make this clearer In compiled code In interpreted code eval ignore evaluate compile evaluate at compile time ignore load compile as normal ignore The situation specifiers compile time and run time are also defined and have the same meaning as compile and Load respectively 10 7 5 include syntax include STRING Include toplevel expressions from the given source file in the currently compiled interpreted program If the included file has the extension SCm then it may be omitted The file is searched in the current directory and if not found in all directories specified in the include path option 10 7 6 nth value syntax nth value N EXP Returns the Nth value counting from zero of the values returned by expression EXP 10 7 7 time syntax time EXP1 Evaluates EXP1 and prints elapsed time and some values about GC use like time spent in major GCs number of minor and major GCs Previous Non standard read syntax Next Pattern matching 10 7 4 eval when 5 11 Pattern matching This description has been taken mostly from Andrew Wright s postscript document Pattern matching allows complicated control decisions based on data st
191. iles file size may return an inexact integer 27 6 7 regular file procedure regular file FILENAME Returns true if FILENAME names a regular file not a directory or symbolic link 27 6 8 file owner procedure file owner FILE Returns the user id of FILE FILE may be a filename or a file descriptor 27 6 9 file permissions procedure file permissions FILE Returns the permission bits for FILE You can test this value by performing bitwise operations on the result and the perm values FILE may be a filename or a file descriptor 27 6 4 file stat 158 CHICKEN User s Manual The User s Manual 27 6 10 file read access 27 6 11 file write access 27 6 12 file execute access procedure file read access FILENAME procedure file write access FILENAME procedure file execute access FILENAME These procedures return t if the current user has read write or execute permissions on the file named FILENAME 27 6 13 stat regular 27 6 14 stat directory 27 6 15 stat char device 27 6 16 stat block device 27 6 17 stat fifo 27 6 18 stat symlink 27 6 19 stat socket procedure stat regular FILENAME procedure stat directory FILENAME procedure stat char device FILENAME procedure stat block device FILENAME 27 6 10 file read access 159 CHICKEN User s Manual The User s Manual procedure stat fifo FILENAME procedure stat symlink FILENAME procedure
192. iles in compiled form To link your compiled files use the following command csc foo o bar o o foo This should produce the foo executable which you can run just as in the previous example At this point you 4 3 2 An example with multiple files 20 CHICKEN User s Manual The User s Manual can also erase the 0 files You could avoid one step and link the two files just as foo scm is compiled csc cC bar scm csc foo scm bar o o foo Note that if you want to distribute your program you might want it to follow the GNU Coding Standards One relatively easy way to achieve this is to use Autoconf and Automake two tools made for this specific purpose 4 4 Extending the compiler The compiler supplies a couple of hooks to add user level passes to the compilation process Before compilation commences any Scheme source files or compiled code specified using the extend option are loaded and evaluated The parameters user options pass user read pass user preprocessor pass user pass user pass 2and user post analysis pass can be set to procedures that are called to perform certain compilation passes instead of the usual processing for more information about parameters see Supported language parameter user options pass Holds a procedure that will be called with a list of command line arguments and should return two values the source filename and the actual list of options where compiler switches have their leading hyp
193. in faster executables There are a number of declaration specifiers that should be used to speed up compiled files declaring standard bindings is mandatory since this enables most optimizations Even if some standard procedures should be redefined you can list untouched bindings in the declaration Declaring extended bindings lets the compiler choose faster versions of certain internal library functions This might give another speedup You can also use the the usual integrations declaration which is identical to declaring standard bindings and extended bindings note that usual integrations is set by default Declaring block tells the compiler that global procedures are not changed outside the current compilation unit this gives the compiler some more opportunities for optimization If no floating point arithmetic is required then declaring number type fixnum can give a big performance improvement because the compiler can now inline most arithmetic operations Declaring unsafe will switch off most safety checks If threads are not used you can declare disable interrupts You should always use maximum optimizations settings for your C compiler Good GCC compiler options on Pentium and compatible hardware are 0s fomit frame pointer fno strict aliasing Some programs are very sensitive to the setting of the nursery the first 42 5 8 Why do built in units such as srfi 1 srfi 18 and posix fail toload 271 CHICKEN User s Ma
194. ined extension of external representations For more information see the documentation for SRFI 10 9 4 Syntax Expression EXPRESSION An abbreviation for Syntax EXPRESSION 9 5 Location Expression EXPRESSION An abbreviation for Location EXPRESSION 9 Non standard read syntax 37 CHICKEN User s Manual The User s Manual 9 6 Keyword SYMBOL Syntax for keywords Keywords are symbols that evaluate to themselves and as such don t have to be quoted 9 7 Multiline String Constant lt lt TAG Specifies a multiline string constant Anything up to a line equal to TAG or end of file will be returned as a single string define msg lt lt END Hello world she said END is equivalent to define msg Hello world she said 9 8 Multiline String Constant with Embedded Expressions lt TAG Similar to lt lt but allows substitution of embedded Scheme expressions prefixed with and optionally enclosed in curly brackets Two consecutive s are translated to a single define three 3 display lt E0F This is a simple string with an embedded character and substituted expressions three 99 gt three 99 three is three EOF prints This is a simple string with an embedded character and substituted expressions three 99 gt 102 three is 3 9 6 Keyword 38 CHICKEN User s Manual The User s Manual 9 9 Foreign Declare gt lt Ab
195. ing that names the file with the components DIRECTORY FILENAME and optionally EXTENSION with SEPARATOR being the directory separation indicator usually on UNIX systems and on Windows defaulting to whatever platform this is running on DIRECTORY can be f meaning no directory component a string or a list of strings FILENAME and EXTENSION should be strings or f make absolute pathname returns always an absolute pathname 28 2 5 pathname directory procedure pathname directory PATHNAME 28 2 6 pathname file procedure pathname file PATHNAME 28 2 7 pathname extension procedure pathname extension PATHNAME Accessors for the components of PATHNAME If the pathname does not contain the accessed component then f is returned 28 2 2 decompose pathname 185 CHICKEN User s Manual The User s Manual 28 2 8 pathname replace directory procedure pathname replace directory PATHNAME DIRECTORY 28 2 9 pathname replace file procedure pathname replace file PATHNAME FILENAME 28 2 10 pathname replace extension procedure pathname replace extension PATHNAME EXTENSION Return a new pathname with the specified component of PATHNAME replaced by a new value 28 2 11 pathname strip directory procedure pathname strip directory PATHNAME 28 2 12 pathname strip extension procedure pathname strip extension PATHNAME Return a new pathname with the specified component of PATHNAME stripped 28 2 13 dire
196. ique The file descriptor of the created file and the generated filename is returned See the mkstemp 3 manual page for details on how this function works The template string given is not modified Example usage let values fd temp path file mkstemp tmp mytemporary X let temp port open output file fd format temp port This file is A 5 temp path close output port temp port 27 5 File descriptors and low level I O 155 CHICKEN User s Manual The User s Manual 27 5 5 file read procedure file read FILENO SIZE BUFFER Reads SIZE bytes from the file with the file descriptor FILENO If a string or bytevector is passed in the optional argument BUFFER then this string will be destructively modified to contain the read data This procedure returns a list with two values the buffer containing the data and the number of bytes read 27 5 6 file select procedure file select READFDLIST WRITEFDLIST TIMEOUT Waits until any of the file descriptors given in the lists READFDLIST and WRITEFDLIST is ready for input or output respectively If the optional argument TIMEOUT is given and not false then it should specify the number of seconds after which the wait is to be aborted the value may be a floating point number This procedure returns two values the lists of file descriptors ready for input and output respectively READFDLIST and WRITEFDLIST may also by file descriptors instead of lists In this case t
197. irectory where the extension is built This is not necessarily identical to setup root directory 39 4 20 setup verbose flag parameter setup verbose flag BOOL Reflects the setting of the verbose option i e is t if verbose was given 39 4 21 setup install flag parameter setup install flag BOOL Reflects the setting of the no install option i e is f if no install was given 39 4 22 required chicken version procedure required chicken version VERSION Signals an error if the version of CHICKEN that this script runs under is lexicographically less than VERSION the argument will be converted to a string first 39 4 17 program path 251 CHICKEN User s Manual The User s Manual 39 4 23 required extension version procedure required extension version EXTENSION1 VERSIONI Checks whether the extensions EXTENSION1 are installed and at least of version VERSION1 The test is made by lexicographically comparing the string representations of the given version with the version of the installed extension If one of the listed extensions is not installed has no associated version information or is of a version older than the one specified 39 4 24 cross chicken procedure cross chicken Returns t if this system is configured for cross compilation or f otherwise 39 4 25 host extension parameter host extension For a cross compiling CHICKEN when compiling an extension then it should be buil
198. itial value if provided Otherwise aborts with an exception Returns the new VALUE 23 1 21 hash table update default procedure hash table update HASH TABLE KEY UPDATE FUNCTION DEFAULT VALUE Sets or replaces the VALUE for KEY in the HASH TABLE The UPDATE FUNCTION takes the existing VALUE for KEY and returns the new VALUE The DEFAULT VALUE is used when the entry for KEY is missing Returns the new VALUE 23 1 22 hash table copy procededure hash table copy HASH TABLE Returns a shallow copy of the HASH TABLE 23 1 23 hash table delete procedure hash table delete HASH TABLE KEY Deletes the entry for KEY in the HASH TABLE 23 1 24 hash table remove procedure hash table remove HASH TABLE PROC Calls PROC for all entries in HASH TABLE with the key and value of each entry If PROC returns true then that entry is removed 23 1 25 hash table clear procedure hash table clear HASH TABLE Deletes all entries in HASH TABLE 23 1 20 hash table update 132 CHICKEN User s Manual The User s Manual 23 1 26 hash table merge procedure hash table merge HASH TABLE 1 HASH TABLE 2 Returns a new HASH TABLE with the union of HASH TABLE 1 and HASH TABLE 2 23 1 27 hash table merge procedure hash table merge HASH TABLE 1 HASH TABLE 2 Returns HASH TABLE 1 as the union of HASH TABLE 1 and HASH TABLE 2 23 1 28 hash table map procedure hash table map HASH TABLE F
199. ker Enter csc help on the command line for more information 4 1 Compiler command line format chicken FILENAME OPTION FILENAME is the complete pathname of the source file that is to be translated into C A filename argument of specifies that the source text should be read from standard input Note that the filename has to be the first argument to Chicken Possible options are analyze only Stop compilation after first analysis pass benchmark mode Equivalent to no trace no lambda info optimize level 3 fixnum arithmetic disable interrupts block lambda lift block Enable block compilation When this option is specified the compiler assumes that global variables are not modified outside this compilation unit Specifically toplevel bindings are not seen by eval and unused toplevel bindings are removed case insensitive Enables the reader to read symbols case insensitive The default is to read case sensitive in violation of R5RS This option registers the case insensitive feature identifier check imports Search for references to undefined global variables For each library unit accessed via declare uses the compiler will search a file named UNITNAME exports in the current include path and load its contents into the import table 1f found Also export information for extensions accessed through require extension will be searched and stored in the import table If a required extension does not prov
200. l Generate a destructor function with the name NAME that takes a pointer to a structure of this type as its single argument and releases the storage with f ree 3 If the argument is f the destructor procedure does nothing 32 6 5 rename rename EXPRESSION Evaluates EXPRESSION at compile macro expansion time and applies the result which should be a procedure to the string representation of the name of each accessor procedure generated Another or the same string should be returned which in turn is taken as the actual name of the accessor An example require for syntax srfi 13 define foreign record Some Struct rename compose string downcase cut string translate lt gt constructor make some struct destructor free some struct int xCoord int yCoord pt will generate the following procedures make some struct C POINTER free some struct C POINTER some struct xcoord C POINTER gt NUMBER some struct ycoord C POINTER gt NUMBER some struct xcoord set C POINTER NUMBER some struct ycoord set C POINTER NUMBER 32 7 define foreign enum syntax define foreign enum TYPESPEC USE ALIASES ENUMSPEC Defines a foreign type as with define foreign type that maps the elements of a C C enum or a enum like list of constants to and from a set of symbols TYPESPEC specifies a foreign type that converts a symbol argument from the set ENUMSPEC into the appropriate enum
201. l procedure repl Start a new read eval print loop Sets the reset handler so that any invocation of reset restarts the read eval print loop Also changes the current exception handler to display a message write any arguments to the value of current error port and reset 15 3 Macros 15 3 1 get line number procedure get line number EXPR If EXPR is a pair with the car being a symbol and line number information is available for this expression then this procedure returns the associated line number If line number information is not available then f is returned Note that line number information for expressions is only available in the compiler 15 3 2 macro procedure macro SYMBOL Returns t if there exists a macro definition for SYMBOL 15 3 3 macroexpand procedure macroexpand X If X is a macro form expand the macro and repeat expansion until expression is a non macro form Returns the resulting expression 15 1 5 set dynamic load mode 94 CHICKEN User s Manual The User s Manual 15 3 4 macroexpand 1 procedure macroexpand 1 X If X is a macro form expand the macro Returns the resulting expression 15 3 5 undefine macro procedure undefine macro SYMBOL Remove the current macro definition of the macro named SYMBOL 15 3 6 syntax error procedure syntax error LOCATION MESSAGE ARGUMENT Signals an exception of the kind exn syntax Otherwise identical to error 15 4 Loadin
202. l result in incorrect results fxneg negates its argument On division by zero fx and f xmod signal a condition of kind exn arithmetic fxshl and fxshr perform arithmetic shift left and right respectively procedure fx N1 N2 procedure fx N1 N2 procedure fx N1 N2 procedure fx N1 N2 procedure fxmod N1 N2 procedure fxneg N procedure fxmin N1 N2 procedure fxmax N1 N2 procedure fx N1 N2 procedure fx N1 N2 procedure fx N1 N2 procedure fx gt N1 N2 procedure fx N1 N2 procedure fxand N1 N2 procedure fxior N1 N2 procedure fxxor N1 N2 procedure fxnot N procedure fxshl N1 N2 procedure fxshr N1 N2 14 1 6 Arithmetic floating point operations In safe mode these procedures throw a type error with non float arguments except f Lonum which returns f In unsafe mode these procedures do not check their arguments A non flonum argument in unsafe mode can crash the system procedure flonum X procedure fp X Y procedure fp X Y procedure fp X Y procedure fp X Y procedure fpneg X procedure fpmin X Y procedure fpmax X Y procedure fp X Y procedure fp X Y procedure fp X Y procedure fp gt X Y procedure fp X Y 14 1 5 Arithmetic fixnum operations 69 CHICKEN User s Manual The User s Manual 14 1 7 signum procedure signum N Returns 1 if N is positive 1 if N is negative or 0
203. l ul6vector nonnull u32vector nonnull s8vector nonnull s16vector nonnull 220vector n CHICKEN User s Manual The User s Manual 33 25 c string list Similar to C string list but releases the storage of each string and the pointer array using f ree 1 33 26 void Specifies an undefined return value Not allowed as argument type 33 27 const TYPE The foreign type TYPE with an additional const specifier 33 28 enum NAME An enumeration type Handled internally as an integer 33 29 c pointer TYPE An operating system pointer or a locative to an object of TYPE 33 30 nonnull c pointer TYPE As C pointer TYPE but guaranteed not to be f NULL 33 31 ref TYPE A C reference type Reference types are handled the same way as pointers inside Scheme code 33 25 c string list 221 CHICKEN User s Manual The User s Manual 33 32 struct NAME A struct of the name NAME which should be a string Structs cannot be directly passed as arguments to foreign function neither can they be result values Pointers to structs are allowed though 33 33 template TYPE ARGTYPE A C template type For example vector lt int gt would be specified as template vector int Template types cannot be directly passed as arguments or returned as results 33 34 union NAME A union of the name NAME which should be a string Unions cannot be directly passed as arguments to foreign function neither can they be resul
204. laced by the value of the given environment variable 6 6 1 if the procedures current input port and current output port are called with an argument which should be a port then that argument is selected as the new current input and output port respectively The procedures open input file open output file with input from file with output to file call with input file and call with output file accept an optional second or third argument which should be one or more keywords if supplied These arguments specify the mode in which the file is opened Possible values are the keywords text binary or append 6 7 The exit procedure exits a program right away and does not invoke pending dynamic wind thunks Previous Deviations from the standard Next Non standard read syntax 8 Extensions to the standard 35 CHICKEN User s Manual The User s Manual 8 Extensions to the standard 36 9 Non standard read syntax 9 1 Multiline Block Comment A multiline block comment May be nested Implements SRFI 30 9 2 Expression Comment EXPRESSION Treats EXPRESSION as a comment That is the comment runs through the whole S expression regardless of newlines which saves you from having to comment out every line or add a newline in the middle of your parens to make the commenting of the last line work or other things like that 9 3 External Representation CONSTRUCTORNAME DATUM Allows user def
205. ld also pass the Shared option feature SYMBOL Registers SYMBOL to be a valid feature identifier for cond expand Multiple symbols may be given if comma separated fixnum arithmetic Equivalent to fixnum arithmetic declaration Assume all mathematical operations use small integer arguments heap size NUMBER Sets a fixed heap size of the generated executable to NUMBER bytes The parameter may be followed by a M m or K K suffix which stand for mega and kilobytes respectively The default heap size is 5 kilobytes Note that only half of it is in use at every given time heap initial size NUMBER Sets the size that the heap of the compiled application should have at startup time heap growth PERCENTAGE Sets the heap growth rate for the compiled program at compile time see hg heap shrinkage PERCENTAGE Sets the heap shrinkage rate for the compiled program at compile time see hs help Print a summary of available options and the format of the command line parameters and exit the compiler import FILENAME Read exports from linked or loaded libraries from given file See also check imports This is equivalent to declaring declare import FILENAME Implies check imports include path PATHNAME Specifies an additional search path for files included via the include special form This option may be given multiple times If the environment variable CHICKEN INCLUDE PATH is set it should contain a list of alterna
206. ld be available through the package management system e g APT Synaptic RPM or Yum depending upon your Linux distribution On Macintosh OS X you will need the XCode tools which are shipped on the OS X DVD with recent versions of the operating system e On Windows you have three choices Cygwin http sources redhat com cygwin provides a relatively full featured Unix environment for Windows Chicken works substantially the same in Cygwin and Unix The GNU Compiler Collection has been ported to Windows in the MinGW system http mingw sourceforge net Unlike Cygwin executables produced with MinGW do not need the Cygwin DLLs in order to run MSys is a companion package to MinGW it provides a minimum Unix style development build environment again ported from free software 9 You can build Chicken either with MinGW alone or with MinGW plus MSys Both approaches produce a Chicken built against the mingw headers and import libraries The only difference is the environment where you actually run make Makefile mingw is can be used in cmd exe with the version of make that comes with mingw Makefile mingw msys uses unix commands such as Cp and rm The end product is the same Microsoft Visual Studio will soon be supported including the Express edition which is a non free but no cost compiler suite available from Microsoft http www microsoft com express vc Chicken supports command line building using the command line C C
207. ld not be accessible from code in other compilation units or by eval Access to toplevel bindings declared as block global is also more efficient 12 Declarations 58 CHICKEN User s Manual The User s Manual 12 6 bound to procedure declaration specifier bound to procedure SYMBOL Declares that the given identifiers are always bound to procedure values 12 7 c options declaration specifier c options STRING Declares additional C C compiler options that are to be passed to the subsequent compilation pass that translates C to machine code This declaration will only work if the source file is compiled with the CSC compiler driver 12 8 check c syntax declaration specifier check c syntax declaration specifier not check c syntax Enables or disables syntax checking of embedded C C code fragments Checking C syntax is the default 12 9 constant declaration specifier constant SYMBOL Declares the procedures with the names SYMBOL as constant that is as not having any side effects This can help the compiler to remove non side effecting expressions 12 10 export declaration specifier export SYMBOL The opposite of hide All given identifiers will be exported and all toplevel variables not listed will be hidden and not be accessible outside of this compilation unit 12 11 emit exports declaration specifier emit exports STRING Write exported toplevel variables to file with name STRING
208. le with define extension NAME 10 1 1 require extension 42 CHICKEN User s Manual The User s Manual 10 2 Binding forms for optional arguments 10 2 1 optional syntax optional ARGS DEFAULT Use this form for procedures that take a single optional argument If ARGS is the empty list DEFAULT is evaluated and returned otherwise the first element of the list ARGS It is an error if ARGS contains more than one value define incr x i x optional i 1 incr 10 gt 11 incr 12 5 gt 17 10 2 2 case lambda syntax case lambda LAMBDA LIST1 EXP1 Expands into a lambda that invokes the body following the first matching lambda list define plus case lambda 0 x x x y x y x y z x y z args apply args plus gt 0 plus 1 gt plus 1 2 3 gt 6 For more information see the documentation for SRFI 16 10 2 3 let optionals syntax let optionals ARGS VAR1 DEFAULT1 BODY Binding constructs for optional procedure arguments ARGS should be a rest parameter taken from a lambda list Let optionals binds VAR1 to available arguments in parallel orto DEFAULT1 if not enough arguments were provided Let optionals binds VAR1 sequentially so every variable sees the previous ones it is an error if any excess arguments are provided let optionals one two a 1 b 2 c 3 list a b c gt one two 3 10 2 Binding forms for
209. lements qp 1 qp n a vector of n elements qp 1 qp n qp n 1 k a vector of n k or more elements pat a pattern pat a pattern spliced The notation k denotes a keyword consisting of three consecutive dots ie or two dots and an non negative integer eg 1 2 or three consecutive underscores ie or two underscores and a non negative integer The keywords kand k are equivalent The keywords 0 and 0 are equivalent The next subsection describes the various patterns The match Lambda and match Lambda forms are convenient combinations of mat ch and Lambda and can be explained as follows match lambda pat body lambda x match x pat body 11 1 Pattern Matching Expressions 53 CHICKEN User s Manual The User s Manual match lambda pat body lambda x match x pat body where X is a unique variable The mat ch Lambda form is convenient when defining a single argument function that immediately destructures its argument The match Lambda form constructs a function that accepts any number of arguments the patterns of match Lambda should be lists The match let match Let match Letrec and natch define forms generalize Scheme s Let let Letrec and define expressions to allow patterns in the binding position rather than just variables For example the following expression match let x y z list 1 2 3 body bi
210. libraries If the unit is not found an error is signaled When the library unit can be successfully loaded a feature identifier named UNIT is registered If the feature is already registered before loading the load library does nothing 15 1 5 set dynamic load mode procedure set dynamic load mode MODELIST On systems that support dynamic loading of compiled code via the dLopen 3 interface for example Linux and Solaris some options can be specified to fine tune the behaviour of the dynamic linker MODE should be a list of symbols or a single symbol taken from the following set local If Local is given then any C C symbols defined in the dynamically loaded file are not available for subsequently loaded files and libraries Use this if you have linked foreign code into your dynamically loadable file and if you don t want to export them for example because you want to load another file that defines the same symbols global The default is g Lobal which means all C C symbols are available to code loaded at a later stage now If now is specified all symbols are resolved immediately lazy Unresolved symbols are resolved as code from the file is executed This is the default 15 1 3 load noisily 93 CHICKEN User s Manual The User s Manual Note that this procedure does not control the way Scheme variables are handled this facility is mainly of interest when accessing foreign code 15 2 Read eval print loop 15 2 1 rep
211. line arguments The first item in the list is a string containing the name of the executing program The other items are the arguments passed to the application This list is freshly created on every invocation of argv It depends on the host shell whether arguments are expanded globbed or not 14 8 2 exit procedure exit CODE Exit the running process and return exit code which defaults to 0 Invokes exit handler Note that pending dynamic wind thunks are not invoked when exiting your program in this way 14 7 2 breakpoint 76 CHICKEN User s Manual The User s Manual 14 8 3 build platform procedure build platform Returns a symbol specifying the toolset which has been used for building the executing system which is one of the following cygwin mingw32 gnu intel unknown 14 8 4 chicken version procedure chicken version FULL Returns a string containing the version number of the CHICKEN runtime system If the optional argument FULL is given and true then a full version string is returned 14 8 5 errno procedure errno Returns the error code of the last system call 14 8 6 getenv procedure getenv STRING Returns the value of the environment variable STRING or f if that variable is not defined 14 8 7 machine byte order procedure machine byte order Returns the symbol Litt le endian or big endian depending on the machine s byte order 14 8 3 build platform TI CHICKEN Use
212. lity to run commands in the same directory as the current file such as make grep etc SciTE is written with the GTK toolkit and is portable to any GTK platform including Windows Linux and MacOS It uses the Scintilla text editing component which lends itself well to embedding within other IDEs and graphical toolkits It does not have any other Scheme specific features but being open source and modular features like auto formatting of S expressions could be added The syntax highlighting can be configured to use different fonts for different types of syntax including proportional fonts Vim http www vim org is a highly configurable text editor built to enable efficient and fast text editing It is an improved version of the vi editor distributed with most UNIX systems Vim comes with generic Lisp and therefore Scheme editing capabilities out of the box A few tips on using Vim with Chicken can be found at http cybertiggyr com gene 15 vim In the rest of this chapter we ll assume that you are using an editor of your choice and a regular terminal window for executing your Chicken code 2 6 The Read Eval Print loop To invoke the Chicken interpreter you use the CS i command csi CHICKEN c 2008 The Chicken Team c 2000 2007 Felix L Winkelmann Version 3 1 2 macosx unix gnu x86 manyargs dload ptables applyhook SVN rev 10185 compiled 2008 03 27 on argyre local Darwin 1 gt This brings up a brief banner and then
213. llowing feature identifiers are available in all situations machine byte order machine type software type software version where the actual feature identifier is platform dependent In addition the following feature identifiers may exist app Lyhook extraslot ptables dload For further information see the documentation for SRFI 0 10 7 3 ensure syntax ensure PREDICATE EXP ARGUMENTS Evaluates the expression EXP and applies the one argument procedure PREDICATE to the result If the predicate returns f an error is signaled otherwise the result of EXP is returned If compiled in unsafe mode either by specifying the unsafe compiler option or by declaring unsafe then this expression expands to an unspecified value If specified the optional ARGUMENTS are used as arguments to the invocation of the error signalling code as in error ARGUMENTS If no ARGUMENTS are given a generic error message is displayed with the offending value and PREDICATE expression 10 7 4 eval when syntax eval when SITUATION EXP Controls evaluation compilation of subforms SITUATION should be one of the symbols eval compile or Load When encountered in the evaluator and the situation specifier eval is not given then this form is not evaluated and an unspecified value is returned When encountered while compiling code and the situation 10 7 2 cond expand 50 CHICKEN User s Manual The User s Manual specifier comp
214. losing paranthesis character follows the then the result of the last expression is returned Note that the value returned is implicitly quoted 5 3 Toplevel commands 21 CHICKEN User s Manual The User s Manual 5 6 set describer procedure set describer TAG PROC Sets a custom description handler that invokes PROC when the d command is invoked with a record type object that has the type TAG a symbol PROC is called with two arguments the object to be described and an output port It should write a possibly useful textual description of the object to the passed output port For example 1 gt define record point x y 2 gt set describer point lambda pt o print a point with x point x pt and y point y pt 3 gt d make point 1 2 a point with x 1 and y 2 5 7 Auto completion and edition On platforms that support it it is possible to get auto completion of symbols history over different csi sessions and a more feature full editor for the expressions you type using the http www call with current continuation org eggs readline html egg by Tony Garnock Jones It is very useful for interactive use of csi To enable it install the egg and put this in your CSi rc file use readline regex current input port make gnu readline port gnu history install file manager string append or getenv HOME csi history More details are available in the egg s documentation 5 8 Acc
215. ly attempt to match with pairs that may exist in the remaining arguments Extra arguments that don t match are simply unused and forgotten if no rest parameter has been declared Because of this the caller of a procedure containing one or more keyword parameters cannot rely on any kind of system error to report 8 Extensions to the standard 33 CHICKEN User s Manual The User s Manual wrong keywords being passed in It shall be an error for an lt ident gt to appear more than once in a parameter list If there is no rest parameter and no keyword parameters in the parameter list then it shall be an error for any extra arguments to be passed to the procedure Example lambda x x 3 4 5 6 gt 3 45 6 lambda x y rest z z 345 6 gt 5 6 lambda x y optional z rest r key i j 1 list xyz i ij j 345 1 61 7 gt 3 45 i 6 j 1 4 1 6 set for unbound toplevel variables is allowed set PROCEDURE is supported as CHICKEN implements SRFI 17 4 2 1 The cond form supports SRFI 61 4 2 2 It is allowed for initialization values of bindings in a Let rec construct to refer to previous variables in the same set of bindings so letrec foo 123 bar foo bar is allowed and returns 123 4 2 3 begin is allowed in non toplevel contexts and evaluates to an unspecified value 4 2 5 Delayed expressions may return multiple values 5 2 2 CHICKEN extends standard semantics by allowi
216. may be any constant expression and may also refer to constants defined via define constant previously This for should only be used at top level 10 3 9 parameterize 46 CHICKEN User s Manual The User s Manual 10 4 2 define inline syntax define inline NAME VAR VAR BODY syntax define inline NAME EXP Defines an inline procedure Any occurrence of NAME will be replaced by EXP or Lambda VAR VAR BODY This is similar to a macro but variable names and scope will be correctly handled Inline substitutions take place after macro expansion EXP should be a lambda expression Any reference to NAME should appear textually after its definition Note that inline procedures are local to the current compilation unit and are not available outside of the source file in which they are defined Names of inline procedures still exist in the Scheme namespace and can be lexically shadowed This construct is equivalent to def ine when evaluated or interpreted Inline definitions should only appear at toplevel 10 4 3 define macro syntax define macro NAME VAR VAR EXP1 syntax define macro NAME lambda VAR VAR EXP1 syntax define macro NAME1 NAME2 Define a globally visible macro special form The macro is available as soon as it is defined i e it is registered at compile time If the file containing this definition invokes eval and the declaration run time macros or the command line op
217. mpiled code in the old module Support for reloading compiled code dynamically is still experimental 15 1 2 load relative procedure load relative FILE EVALPROC Similar to Load but loads FILE relative to the path of the currently loaded file 15 Unit eval 92 CHICKEN User s Manual The User s Manual 15 1 3 load noisily procedure load noisily FILE key EVALUATOR TIME PRINTER As Load but the result s of each evaluated toplevel expression is written to standard output If EVALUATOR is given and not f then each expression is evaluated by calling this argument with the read expression as argument If TIME is given and not false then the execution time of each expression is shown as with the time macro If PRINTER is given and not false then each expression is printed before evaluation by applying the expression to the value of this argument which should be a one argument procedure See also the load verbose parameter 15 1 4 load library procedure load library UNIT LIBRARYFILE On platforms that support dynamic loading Load Library loads the compiled library unit UNIT which should be a symbol If the string LIBRARYFILE is given then the given shared library will be loaded and the toplevel code of the contained unit will be executed If no LIBRARYFILE argument is given then the following libraries are checked for the required unit e a file named UNIT so the files given in the parameter dynamic load
218. ms The routines complex real and rational are identical to the standard procedure number The procedures numerator denominator rationalize make rectangular and make polar are not implemented Fixnums are limited to A 230 or A 262 on 64 bit hardware Support for extended numbers is available as a separate package provided the GNU multiprecision library is installed 6 2 6 The procedure st ring gt number does not obey read write invariance on inexact numbers 6 4 The maximum number of values that can be passed to continuations captured using call with current continuation is 120 6 5 Code evaluated in scheme report environment or nul l environment still sees non standard syntax 6 6 2 The procedure char ready always returns t for terminal ports The procedure read does not obey read write invariance on inexact numbers 6 6 3 The procedures write and disp Lay do not obey read write invariance to inexact numbers 7 Deviations from the standard 31 CHICKEN User s Manual The User s Manual 6 6 4 The transcript on and transcript off procedures are not implemented Previous Supported language Next Extensions to the standard 7 Deviations from the standard 32 8 Extensions to the standard 2 1 Identifiers may contain special characters if delimited with 2 3 The brackets andthe braces are provided as an alternative syntax for A number of reader extensions is pro
219. n 27 Unit posix 147 CHICKEN User s Manual The User s Manual 27 1 2 2 fileno stdout 27 1 2 3 fileno stderr 27 1 3 Open flags 27 1 3 1 open rdonly 27 1 3 2 open wronly 27 1 3 3 open rdwr 27 1 3 4 open read 27 1 3 5 open write 27 1 3 6 open creat 27 1 3 7 open append 27 1 3 8 open excl 27 1 3 9 open noctty 27 1 2 Standard I O file descriptors 148 CHICKEN User s Manual The User s Manual 27 1 3 10 open nonblock 27 1 3 11 open trunc 27 1 3 12 open sync 27 1 3 13 open fsync 27 1 3 14 open binary 27 1 3 15 open text 27 1 4 Permission bits 27 1 4 1 perm irusr 27 1 4 2 perm iwusr 27 1 4 3 perm ixusr 27 1 4 4 perm irgrp 27 1 4 5 perm iwgrp 27 1 3 Open flags 149 CHICKEN User s Manual The User s Manual 27 1 4 6 perm ixgrp 27 1 4 7 perm iroth 27 1 4 8 perm iwoth 27 1 4 9 perm ixoth 27 1 4 10 perm irwxu 27 1 4 11 perm irwxg 27 1 4 12 perm irwxo 27 1 4 13 perm isvtx 27 1 4 14 perm isuid 27 1 4 15 perm isgid 27 2 Directories 27 2 1 change directory procedure change directory NAME Changes the current working directory to NAME 27 1 4 Permission bits 150 CHICKEN User s Manual The User s Manual 27 2 2 current directory procedure current directory DIR Returns the name of the current working directory If the optional argument DIR is given then current directory DIR is equivalent to change directory DIR 27 2 3 create dir
220. n Compiling Scheme files Using the compiler Explains how to use CHICKEN to compile programs and execute them Using the interpreter Invocation and usage of CSi the CHICKEN interpreter Supported language The language implemented by CHICKEN deviations from the standard and extensions Interface to external functions and variables Accessing C and C code and data chicken setup Packaging and installing extension libraries Data representation How Scheme data is internally represented Bugs and limitations Yes there are some EAQ A list of Frequently Asked Questions about CHICKEN and their answers Acknowledgements A list of some of the people that have contributed to make CHICKEN what it is Bibliography Links to documents that may be of interest The User s Manual 2 Getting started Chicken is a compiler that translates Scheme source files into C which in turn can be fed to a C compiler to generate a standalone executable An interpreter is also available and can be used as a scripting environment or for testing programs before compilation This chapter is designed to get you started with Chicken programming describing what it is and what it will do for you and covering basic use of the system With almost everything discussed here there is more to the story which the remainder of the manual reveals Here we only cover enough to get you started Nonetheless someone who knows Scheme already should be able
221. n the calling machine Quoting is suggested as shell special characters including space are not escaped However all path separators and prefixes are handled in an OS independent fashion Any appearance of below imply is also handled The prefix for NAME determines what path to prepend If NAME begins with a this prefix is stripped and the user s home directory is added If beginning with or a DRIVE LETTER combination no additional path is added Otherwise the current directory and separator are added All relative path elements and duplicate separators are processed and removed If NAME ends with a or is empty the appropriate slash is appended to the tail No directories or files are actually tested for existence this procedure only canonicalises path syntax 27 2 9 set root directory procedure set root directory STRING Sets the root directory for the current process to the path given in STRING using the chroot function If the current process has no root permissions the operation will fail 27 3 Pipes 27 3 1 call with input pipe 27 3 2 call with output pipe procedure call with input pipe CMDLINE PROC MODE procedure call with output pipe CMDLINE PROC MODE Call PROC with a single argument a input or output port for a pipe connected to the subprocess named in CMDL INE If PROC returns normally the pipe is closed and any result values are returned 27 2 7 glob 152 CHICKEN User s Manu
222. n to word PTR OR INT Accepts either a machine pointer or an integer as argument and returns a new pointer or integer aligned to the native word size of the host platform 30 1 23 pointer s16 set 199 CHICKEN User s Manual The User s Manual 30 2 Tagged pointers Tagged pointers are foreign pointer objects with an extra tag object 30 2 1 tag pointer procedure tag pointer PTR TAG Creates a new tagged pointer object from the foreign pointer PTR with the tag TAG which may an arbitrary Scheme object 30 2 2 tagged pointer procedure tagged pointer X TAG Returns t if X is a tagged pointer object with the tag TAG using an eq comparison or f otherwise 30 2 3 pointer tag procedure pointer tag PTR If PTR is a tagged pointer object its tag is returned If PTR is a normal untagged foreign pointer object f is returned Otherwise an error is signalled 30 3 Extending procedures with data 30 3 1 extend procedure procedure extend procedure PROCEDURE X Returns a copy of the procedure PROCEDURE which contains an additional data slot initialized to X If PROCEDURE is already an extended procedure then its data slot is changed to contain X and the same procedure is returned 30 2 Tagged pointers 200 CHICKEN User s Manual The User s Manual 30 3 2 extended procedure procedure extended procedure PROCEDURE Returns t if PROCEDURE is an extended procedure or f otherwise 30 3 3 procedure data
223. name bell gt 7 14 15 1 port 84 CHICKEN User s Manual The User s Manual 14 17 Blobs blobs are collections of unstructured bytes You can t do much with them but allow conversion to and from SRFI 4 number vectors 14 17 1 make blob procedure make blob SIZE Returns a blob object of SIZE bytes aligned on an 8 byte boundary uninitialized 14 17 2 blob procedure blob X Returns t if X is a blob object or f otherwise 14 17 3 blob size procedure blob size BLOB Returns the number of bytes in BLOB 14 17 4 blobstring procedure blob gt string BLOB Returns a string with the contents of BLOB 14 17 5 stringblob procedure string gt blob STRING Returns a blob with the contents of STRING 14 17 Blobs 85 CHICKEN User s Manual The User s Manual 14 17 6 blob procedure blob BLOB1 BLOB2 Returns t if the two argument blobs are of the same size and have the same content 14 18 Vectors 14 18 1 vector copy procedure vector copy VECTOR1 VECTOR2 COUNT Copies contents of VECTOR1 into VECTOR2 If the argument COUNT is given it specifies the maximal number of elements to be copied If not given the minimum of the lengths of the argument vectors is copied Exceptions exn bounds 14 18 2 vector resize procedure vector resize VECTOR N INIT Creates and returns a new vector with the contents of VECTOR and length N If N is greater than the original leng
224. ncountered iB Sounds a bell ASCII 7 on every major garbage collection SS 4 2 Runtime options 17 CHICKEN User s Manual The User s Manual Forces console mode Currently this is only used in the interpreter CSi to force output of the N gt prompt even if stdin is not a terminal for example if running in an emacs buffer under Windows d D W Prints some debug information at runtime Prints some more debug information at runtime FNUMBER Specifies the maximal number of currently pending finalizers before finalization is forced hNUMBER Specifies fixed heap size hg PERCENTAGE Sets the growth rate of the heap in percent If the heap is exhausted then it will grow by PERCENTAGE The default is 200 hi NUMBER Specifies the initial heap size hmNUMBER Specifies a maximal heap size The default is 2GB 15 hsPERCENTAGE Sets the shrink rate of the heap in percent If no more than a quarter of PERCENTAGE of the heap is used then it will shrink to PERCENTAGE The default is 50 Note If you want to make sure that the heap never shrinks specify a value of H this can be useful in situations where an optimal heap size is known in advance Disables detection of stack overflows at run time Writes trace output to stderr This option has no effect with in files compiled with the no trace options SNUMBER Specifies stack size tNUMBER Specifies symbol table size Enables garbage collection of unuse
225. nds X to 1 y to 2 and Z to 3 in body These forms are convenient for destructuring the result of a function that returns multiple values as a list or vector As usual for Let rec and define pattern variables bound by match letrec and match define should not be used in computing the bound value The match match Lambda and match Lambda forms allow the optional syntax gt identifier between the pattern and the body of a clause When the pattern match for such a clause succeeds the identifier is bound to a failure procedure of zero arguments within the body If this procedure is invoked it jumps back to the pattern matching expression and resumes the matching process as if the pattern had failed to match The body must not mutate the object being matched otherwise unpredictable behavior may result 11 2 Patterns identifier excluding the reserved names and or not set get and Kfor non negative integers K matches anything and binds a variable of this name to the matching value in the body _ matches anything without binding any variables t f string number character s expression These constant patterns match themselves i e the corresponding value must be equal to the pattern pat 1 pat n matches a proper list of n elements that match pat 1 through pat n pat 1 pat n pat n 1 matches a possibly improper list of at least n elements that ends in something matchi
226. ne eoa 225 CHICKEN User s Manual The User s Manual Chicken User s Manual 34 Embedding SET EE OT 226 34 10 CHICKEN apply tO StPlfig ecce rrr Pepe eere eria EE P eger e ERR EE RS 226 34 II LOADS NOT 226 SA EX CHICKEN e EE 226 34 13 CHICKEN get error TEEN 226 34 14 CHICKEN yield DE 226 34 1 e UL ENT TEE 228 34 16 CHICKEN NeW 86 TOO yi ssassssaecsudssncieeseadecexansededenndvass AEEA IEEE USER ER ERR RR SEEK ENEE ER 229 34 17 CHICKEN del te e TOOL eri ritenere en e tener EE Ed EE EES a denn 229 34 18 CHICKEN g root TEL iaceret re a PP gs ere EPOR HERE EROR EESTE 229 34 19 CHICKEN 286 TOOL Set eie orte irae euet Ie EC Pete ERES E HERE EUREN EROR TERRE EET RET ege sees 229 34 20 CHICKEN global Jookun enne nennen enne 230 34 21 CHICKEN glob l T l ete etie riter ee tte E d rre re eH ue Ha E e rete Ee ret dE 230 34 22 CHICKEN global Set reine htt nee e E dte iR Ee bep rre NEE 230 EE HU NEE 231 3 Dad Ge MME geg ET 231 35 2 itor IU oF Ye SERO TEM n 232 35 3 C callback adjust Stack EE 232 A E 233 36 1 defini TOCatlodL iste extn eer ree dale rasgo Pie bo rune pe TREE nee DEENEN 233 SNB Ie IPIE Eege EES 233 36 3 eer 233 37 Other support DEGCeIUEBS os i ere o EPOR REEF FEE EDI TORRE REPRE AN EEDAEAIR eis 235 BLL AL E 235 SL MT Ga 236 BOSC SAVE EE 236 382 WE EEN 236 BSS KE 236 3o make character EE 236 38 SCA SCHEME END OF LISE eege ee 236 38 6
227. ne values 45 CHICKEN User s Manual The User s Manual 10 3 9 parameterize syntax parameterize PARAMETER1 X1 BODY Binds the parameters PARAMETER1 dynamically to the values X1 during execution of BODY see also make parameter in Parameters Note that PARAMETER may be any expression that evaluates to a parameter procedure 10 3 10 receive syntax receive NAME1 NAMEn VALUEEXP BODY syntax receive VALUEEXP SRFI 8 Syntactic sugar for cal L with values Binds variables to the result values of VALUEEXP and evaluates BODY The syntax receive VALUEEXP is equivalent to receive _ VALUEEXP _ 10 3 11 set values syntax set values NAME EXP Assigns the result values of expression EXP to multiple variables 10 4 Substitution forms and macros 10 4 1 define constant syntax define constant NAME CONST Define a variable with a constant value evaluated at compile time Any reference to such a constant should appear textually after its definition This construct is equivalent to def ine when evaluated or interpreted Constant definitions should only appear at toplevel Note that constants are local to the current compilation unit and are not available outside of the source file in which they are defined Names of constants still exist in the Scheme namespace and can be lexically shadowed If the value is mutable then the compiler is careful to preserve its identity CONST
228. nerated binaries and or support files any invocations of install program install extension or install script will be be no ops i docindex Displays the path to the index page of any installed extension documentation if the index page does not exist it is created t test EXTENSION return success if all given extensions are installed ls EXTENSION List installed files for extension fetch tree Download and print the repository catalog create tree DIRECTORY Create a fresh minimal repository catalog and writes it to stdout t test If the extension sources contain a directory named tests and this directory includes a file named run scm then this file is executed with tests being the current working directory tree FILENAME Download and show the repository catalog svn URL Fetch extension from Subversion repository svn trunk URL Fetch extension from trunk in Subversion repository revision REV Specifies SVN revision to check out Local PATHNAME Fetch extension from local file install prefix PATHNAME Specify alternative installation prefix for packaging host extension Compile extension in host mode sets the parameter host extension to f build prefix PATHNAME Location where chicken setup will create egg build directories default the value of environment variable CHICKEN TMPDIR or tmp chicken MAJOR VERSION build USER download path PATHNAME Location where chicken setup will save downloaded files default build
229. ng 33 38 Mappings int unsigned char unsigned short unsigned int unsigned int unsigned long float double double void unsigned char unsigned char char unsigned short short uint32 t int32 t float double char unsigned char char char void TYPE enum NAME struct NAME TYPE amp T1 lt T2 gt union NAME CALLCONV RTYPE ATYPE CNAME CNAME amp 223 34 Embedding Compiled Scheme files can be linked with C code provided the Scheme code was compiled in embedded mode by passing DC EMBEDDED to the C compiler this will disable generation of a main function CSC will do this when given the embedded option Alternatively pass embedded to csc The following C API is available 34 1 CHICKEN parse command line C function void CHICKEN parse command line int argc char argv int heap Parse the programs command line contained in argc and argv and return the heap stack and symbol table limits given by runtime options of the form or choose default limits The library procedure argv can access the command line only if this function has been called by the containing application 34 2 CHICKEN initialize C function int CHICKEN initialize int heap int stack int symbols void to Initializes the Scheme execution context and memory heap holds the number of bytes that are to be allocated for the secondary heap Stack holds the number
230. ng NUM STRING PORT START procedure write string STRING NUM PORT Read or write NUM characters from to PORT which defaults to the value of Current input port or current output port respectively If NUM is f or not given then all data up to the end of file is read or in the case of write string the whole string is written If no more input is available read string returns the empty string read string reads destructively into the given STRING argument but never more characters that would fit into STRING If START is given then the read characters are stored starting at that position read st ring returns the actual number of characters read 18 3 5 read file 117 CHICKEN User s Manual The User s Manual 18 3 12 read token procedure read token PREDICATE PORT Reads characters from PORT which defaults to the value of Current input port and calls the procedure PREDICATE with each character until PREDICATE returns false Returns a string with the accumulated characters Previous Unit ports Next Unit srfi 1 18 3 12 read token 118 19 Unit srfi 1 List library see the documentation for SRFI 1 Previous Unit extras Next Unit srfi 4 19 Unit srfi 1 119 20 Unit srfi 4 Homogeneous numeric vectors see the documentation for SREI 4 64 bit integer vectors U64vector and s64vector are not supported The basic constructor procedures for number vectors are extended to allow allocating
231. ng internal definitions everywhere and not only at the beginning of a body A set of internal definitions is equivalent to a Let rec form enclosing all following expressions in the body let foo 123 bar define foo 456 baz foo expands into let foo 123 bar lLetrec foo 456 baz foo 5 2 define with a single argument is allowed and initializes the toplevel or local binding to an unspecified value CHICKEN supports curried definitions where the variable name may also be a list specifying a name and a nested lambda list So define make adder x y x y 8 Extensions to the standard 34 CHICKEN User s Manual The User s Manual is equivalent to define make adder x lambda y x y 6 CHICKEN provides numerous non standard procedures See the manual sections on library units for more information 6 2 4 The special IEEE floating point numbers nan inf and inf are supported as is negative zero 6 3 4 User defined character names are supported See char name Characters can be given in hexadecimal notation using the AxXX syntax where XX specifies the character code Character codes above 255 are supported and can be read and are written using the AuXXXX and AUXXXXXXXX notations Non standard characters names supported are tab Linefeed return alarm vtab nul page esc delete and backspace 6 3 5 CHICKEN supports special characters preceded with a
232. ng pat n 1 pat 1 pat n pat n 1 matches a proper list of n or more elements where each element of the tail matches pat n 1 Each pattern variable in pat n 1 is bound to a list of the matching values For example the expression match er x 1 y 21 z let binding values exp body binds binding to the list x y values to the list 1 2 and exp to Z in the body of the match expression For the special case where pat n 1 is a pattern variable the list bound to that variable may share with the matched value pat 1 pat n pat n 1 This pattern means the same thing as the previous pattern 11 2 Patterns 54 CHICKEN User s Manual The User s Manual pat 1 pat n pat n 1 k This pattern is similar to the previous pattern but the tail must be at least k elements long The pattern keywords and are equivalent pat 1 pat n pat n 1 Kl This pattern means the same thing as the previous pattern pat 1 pat n matches a vector of length n whose elements match pat 1 through pat n pat 1 pat n pat n 1 matches a vector of length n or more where each element beyond n matches pat n 1 pat 1 pat n pat n 1 k matches a vector of length n k or more where each element beyond n matches pat n 1 struct pat 1 pat n matches a structure declared with def ine record or define record type field pat is intended for selecting a field
233. ng the procedure with one argument changes its value to the value of that argument subsequent invocations with zero parameters return the new value GUARD should be a procedure of a single argument Any new values of the parameter even the initial value are passed to this procedure The guard procedure should check the value and or convert it to an appropriate form 13 2 case sensitive If true then read reads symbols and identifiers in case sensitive mode and uppercase characters in symbols are printed escaped Defaults to t 13 3 dynamic load libraries A list of strings containing shared libraries that should be checked for explicitly loaded library units this facility is not available on all platforms See Load Library 13 4 command line arguments Contains the list of arguments passed to this program with the name of the program and any runtime options all options starting with removed 13 Parameters 65 CHICKEN User s Manual The User s Manual 13 5 current read table A read table object that holds read procedures for special non standard read syntax see set read syntax for more information 13 6 exit handler A procedure of a single optional argument When exit is called then this procedure will be invoked with the exit code as argument The default behavior is to terminate the program 13 7 eval handler A procedure of one or two arguments When eval is invoked it calls the value of this parameter with
234. nless the program is compiled with the explicit use option 18 1 Formatted output 18 1 1 printf 18 1 2 fprintf 18 1 3 sprintf procedure fprintf PORT FORMATSTRING ARG procedure printf FORMATSTRING ARG procedure sprintf FORMATSTRING ARG Simple formatted output to a given port fprintf the value of current output port printf or a string sprintf The FORMATSTRING can contain any sequence of characters There must be at least as many ARG arguments given as there are format directives that require an argument in FORMATSTRING Extra ARG arguments are ignored The character prefixes special formatting directives l o write newline character N the same as S write the next argument A display the next argument n skip all whitespace in the format string until the next non whitespace character B write the next argument as a binary number 0 18 Unit extras 114 CHICKEN User s Manual The User s Manual write the next argument as an octal number X write the next argument as a hexadecimal number C write the next argument as a character display flush all pending output invoke formatted output routine recursively with the next two arguments as format string and list of parameters 18 1 4 format procedure format DESTINATION FORMATSTRING ARG The parameters FORMATSTRING and ARG areas for printf sprintf fprintf The optional DESTI
235. nnect procedure tcp connect HOSTNAME TCPPORT Establishes a client side TCP connection to the machine with the name HOSTNAME a string at TCPPORT an exact integer and returns two values an input and output port for communicating with the remote process The current value of tcp connect timeout is used to determine the maximal number of milliseconds if any to wait until the connection is established When the connection takes place any read and write operations on the returned ports will use the current values at the time of the call to tcp connect of tcp read timeout and tcp write timeout respectively to determine the maximal number of milliseconds to wait for input output before a timeout error is signalled If the TCPPORT is omitted the port is parsed from the HOSTNAME string The format expected is HOSTNAME PORT The PORT can either be a string representation of an integer or a service name which is translated to an integer using the POSIX function getservbyname Note any I O on the ports returned will not block other running threads 29 5 tcp accept ready 191 CHICKEN User s Manual The User s Manual 29 9 tcp addresses procedure tcp addresses PORT Returns two values for the input or output port PORT which should be a port returned by either tcp accept or tcp connect the IP address of the local and the remote machine that are connected over the socket associated with PORT The returned addresses are strin
236. ns Unit srfi 18 multithreading Unit posix Unix like services Unit utils Shell scripting and file operations Unit tcp basic TCP sockets Unit lolevel low level operations Previous Using the interpreter Next Interface to external functions and variables 6 Supported language 7 Deviations from the standard Identifiers are by default case sensitive see Compiler command line format 4 1 3 The maximal number of arguments that may be passed to a compiled procedure or macro is 120 A macro definition that has a single rest parameter can have any number of arguments 4 2 2 Let rec does evaluate the initial values for the bound variables sequentially and not in parallel that is letrec x 1 y 2 cons x y is equivalent to let x void y void set x 1 set y 2 cons x y where RSRS requires let x void y void let tmp1 1 tmp2 2 set x tmpl set y tmp2 cons x y 4 3 syntax rules macros are not provided but available separately 6 1 equal compares all structured data recursively while R5RS specifies that eqv is used for data other than pairs strings and vectors 6 2 4 The runtime system uses the numerical string conversion routines of the underlying C library and so does only understand standard C library syntax for floating point constants 6 2 5 There is no built in support for rationals complex numbers or extended precision integers bignu
237. nto the compiled Scheme code You should add the following declarations at the head of your code include chicken hn extern void C toplevel C word C word C word C noret 42 3 2 How can add compiled user passes To add a compiled user pass instead of an interpreted one create a library unit and recompile the main unit of the compiler in the file chicken scm with an additional uses declaration Then link all compiler modules and your compiled extension to create a new version of the compiler like this assuming all sources are in the current directory cat userpass scm userpass scm My very own compiler pass declare unit userpass Perhaps more user passes extensions are added let old user pass user pass lambda x Let x2 do something with x if old old x2 x2 csc C X userpass scm csc chicken scm c o chicken extended o uses userpass gcc chicken extended o support o easyffi o compiler o optimizer o batch drive C backend o userpass o csc ldflags libs o chicken extended o o oe On platforms that support it Linux ELF Solaris Windows VC compiled code can be loaded via extend just like source files see Load in the User s Manual 42 3 How do I run custom startup code before the runtime system is invoked 267 CHICKEN User s Manual The User s Manual 42 4 Compiled macros 42 4 1 Why is define macro complaining about unbound variables Macro bodi
238. nual The User s Manual heap generation You should experiment with different nursery settings either by compiling with the nursery option or by using the S runtime option 42 6 3 Which non standard procedures are treated specially when the extended bindings Or usual integrations declaration or compiler option is used The following standard bindings are handled specially depending on optimization options and compiler settings quotient eq eqv equal apply c r values call with values list ref null Length not char string symbol vector pair procedure boolean number complex rational real exact inexact list eof object string ref string set vector ref vector set charz char char char char char numeric char alphabetic char whitespace char upper case char lower case char upcae char downcase list tail assv memv memq assoc member set car set cdr abs exp sin cos tan log asin acos atan sqrt zero positive negative vector length string length char gt integer integer gt char inexact gt exact gt lt gt lt for each map substring string append gcd lcm list exact gt inexact string gt number number gt string even odd remainder floor ceiling truncate round cons vector string string string ci make vector call with current continuation write char read string The following extended bindings are handled specially bitwise and bitwise ior bitwise xor bitwise not bit set add1 su
239. o write a handler for this signal 27 13 2 set signal handler procedure set signal handler SIGNUM PROC Establishes the procedure of one argument PROC as the handler for the signal with the code SIGNUM PROC is called with the signal number as its sole argument If the argument PROC is f then any signal handler will be removed and the corresponding signal set to SIG IGN Note that is is unspecified in which thread of execution the signal handler will be invoked 27 12 2 file lock blocking 167 CHICKEN User s Manual The User s Manual 27 13 3 signal handler procedure signal handler SIGNUM Returns the signal handler for the code SIGNUM or f 27 13 4 set signal mask procedure set signal mask SIGLIST Sets the signal mask of the current process to block all signals given in the list SIGLIST Signals masked in that way will not be delivered to the current process 27 13 5 signal mask procedure signal mask Returns the signal mask of the current process 27 13 6 signal masked procedure signal masked SIGNUM Returns whether the signal for the code SIGNUM is currently masked 27 13 7 signal mask procedure signal mask SIGNUM Masks blocks the signal for the code SIGNUM 27 13 8 signal unmask procedure signal unmask SIGNUM Unmasks unblocks the signal for the code SIGNUM 27 13 3 signal handler 168 CHICKEN User s Manual The User s Manual 27 13 9 signal term 27 13 10 s
240. of only two handcoded C files runtime c and chicken h plus the file chicken config h which is generated by the build process All other modules of the runtime system and the extension libraries are just compiled Scheme code The following example shows a minimal application which should run without changes on the most frequent operating systems like Windows Linux or FreeBSD Let s take a simple example hello scm print Hello world chicken hello scm optimize level 3 output file hello c Compiled to C we get hel lo c We need the files chicken hand runtime c which contain the basic runtime system plus the three basic library files Library c eval cand extras c which contain the same functionality as the library linked into a plain CHICKEN compiled application or which is available by default in the interpreter CSi cd tmp echo print Hello World hello scm cp CHICKEN BUILD runtime c cp CHICKEN BUILD Llibrary c cp CHICKEN BUILD eval c cp CHICKEN BUILD extras c gcc static 0s fomit frame pointer runtime c library c eval c extras c hello c o hello lm d o o o d i o d i Now we have all files together and can create an tarball containing all the files 9 6 tar cf hello tar Makefile hello c runtime c library c eval c extras c chicken gzip hello tar This is naturally rather simplistic Things like enabling dynamic loading estimating the optimal stack size and selecting supporte
241. ollowing accessor procedures will be generated 32 6 1 TYPENAME SLOTNAME TYPENAME SLOTNAME FOREIGN RECORD POINTER INDEX A procedure of one argument a pointer to a C structure that returns the slot value of the slot SLOTNAME If a SIZE has been given in the slot definition then an additional argument INDEX is required that specifies the index of an array element 32 6 2 TYPENAME SLOTNAME set TYPENAME SLOTNAME set FOREIGN RECORD POINTER INDEX VALUE A procedure of two arguments a pointer to a C structure and a value that sets the slot value of the slot SLOTNAME in the structure If a SIZE has been given in the slot definition then an additional argument INDEX is required for the array index If a slot type is of the form const then no setter procedure will be generated Slots of the types struct or union are accessed as pointers to the embedded struct or union and no setter will be generated Additionally special record declarations DECL may be given where each declaration consists of a list of the form KEYWORD ARGUMENT The available declarations are 32 6 3 constructor constructor NAME Generate a constructor procedure with no arguments that has the name NAME a symbol that returns a pointer to a structure of this type The storage will be allocated with malloc 3 32 6 4 destructor destructor NAME 32 6 define foreign record 212 CHICKEN User s Manual The User s Manua
242. on of recursive definitions rec NAME EXPRESSION is equivalent to Letrec NAME EXPRESSION NAME and rec NAME VARIABLE BODY isthesame as Letrec NAME lambda VARIABLE BODY NAME 10 3 3 cut syntax cut SLOT syntax cute SLOT Syntactic sugar for specializing parameters 10 2 4 let optionals 44 CHICKEN User s Manual The User s Manual 10 3 4 define values syntax define values NAME EXP Defines several variables at once with the result values of expression EXP 10 3 5 fluid let syntax fluid let VAR1 X1 BODY Binds the variables VAR1 dynamically to the values X1 during execution of BODY 10 3 6 let values syntax let values NAME EXP BODY Binds multiple variables to the result values of EXP All variables are bound simultaneously 10 3 7 let values syntax let values NAME EXP BODY Binds multiple variables to the result values of EXP The variables are bound sequentially let values i b values 2 3 a p a b p gt 5 10 3 8 letrec values syntax letrec values NAME EXP BODY Binds the result values of EXP to multiple variables at once All variables are mutually recursive letrec values odd even values lambda n if zero n f even subl n lambda n if zero n t odd subl n odd 17 gt t 10 3 4 defi
243. ons for this For most applications of Scheme fixnums exact word sized integers and flonums 64 bit floating point numbers are more than sufficient Interfacing to C is simpler Dispatching of arithmetic operations is more efficient There is an extension based on the GNU Multiprecision Package that implements most of the full numeric tower see numbers 42 1 10 How can I specialize a generic function method to match instances of every class Specializing a method on obj ect doesn t work on primitive data objects like numbers strings etc so for example define method foo x lt my class gt define method foo x lt object gt foo 123 will signal an error because to applicable method can be found To specialize a method for primitive objects use top define method foo x lt top gt 42 1 11 Does CHICKEN support native threads Native threads are not supported for two reasons One the runtime system is not reentrant Two concurrency implemented properly would require mandatory locking of every object that could be potentially shared between two threads The garbage collection algorithm would then become much more complex and inefficient since the location of every object has to be accessed via a thread synchronization protocol Such a design would make native threads in Chicken essentially equivalent to Unix processes and shared memory For a different approach to concurrency plea
244. optional arguments 43 CHICKEN User s Manual The User s Manual 10 2 4 let optionals syntax let optionals ARGS VAR1 DEFAULT1 RESTVAR BODY Binding constructs for optional procedure arguments ARGS should be a rest parameter taken from a lambda list Let optionals binds VAR1 to available arguments in parallel orto DEFAULT1 if not enough arguments were provided Let optionals binds VAR1 sequentially so every variable sees the previous ones If a single variable RESTVAR is given then it is bound to any remaining arguments otherwise it is an error if any excess arguments are provided let optionals one two a 1 b 2 c a list a b c gt one two one 10 3 Other binding forms 10 3 1 and let syntax and let BINDING EXP1 EXP2 SRFI 2 Bind sequentially and execute body BINDING can be a list of a variable and an expression a list with a single expression or a single variable If the value of an expression bound to a variable is f the and Letz form evaluates to f and the subsequent bindings and the body are not executed Otherwise the next binding is performed If all bindings expressions evaluate to a true result the body is executed normally and the result of the last expression is the result of the and Letz form See also the documentation for SRFI 2 10 3 2 rec syntax rec NAME EXPRESSION syntax rec NAME VARIABLE BODY Allows simple definiti
245. ore information see the documentation for SRFI 9 10 7 Other forms 10 7 1 assert syntax assert EXP STRING ARG Signals an error if EXP evaluates to false An optional message STRING and arguments ARG supplied to give a more informative error message If compiled in unsafe mode either by specifying the unsafe compiler option or by declaring unsafe then this expression expands to an unspecified value The result is the value of EXP 10 6 2 define record printer CHICKEN User s Manual The User s Manual 10 7 2 cond expand syntax cond expand FEATURE CLAUSE Expands by selecting feature clauses This form is allowed to appear in non toplevel expressions Predefined feature identifiers are situation specific compile eval Library match compiling srfi 11 srfi 15 srfi 31 srfi 26 srfi 16 utils regex srfi 4 match srfi 1 srfi 69 srfi 28 extras srfi 8 srfi 6 srfi 2 srfi 0 srfi 10 srfi 9 srfi 55 srfi 61 chicken srfi 23 srfi 30 srfi 39 srfi 62 srfi 17 srfi 12 load srfi 69 srfi 28 extras srfi 8 srfi 6 srfi 2 srfi 0 srfi 10 srfi 9 srfi 55 srfi 61 chicken srfi 23 srfi 30 srfi 39 srfi 62 srfi 17 Srfi 12 Library is implicit eval match csi srfi 11 srfi 15 srfi 31 srfi 26 srfi 16 srfi 69 srfi 28 extras srfi 8 srfi 6 srfi 2 srfi 0 srfi 10 srfi 9 srfi 55 srfi 61 chicken srfi 23 srfi 30 srfi 39 srfi 62 srfi 17 srfi 12 library is implicit The fo
246. orrectly convert values between Scheme and C representation This foreign variable can only be accessed in the current compilation unit but the name can be lexically shadowed Note that STRING can name an arbitrary C expression If no assignments are performed then STRING doesn t even have to specify an lvalue gt enum abc 3 def ghi lt define macro define simple foreign enum items begin G map match lambda name realname define foreign variable name int realname name define foreign variable name int items define simple foreign enum abc def ghi ghi gt 5 32 6 define foreign record syntax define foreign record NAME DECL SLOT Defines accessor procedures for a C structure definition NAME should either be a symbol or a list of the form TYPENAME FOREIGNNAME If NAME is a symbol then a C declaration will be generated that defines a C struct named struct NAME If NAME is a list then no struct declaration will be generated and FOREIGNNAME should name an existing C record type A foreign type specifier named NAME or TYPENAME will be defined as a pointer to the given C structure A SLOT definition should be a list of one of the following forms 32 4 define foreign type 211 CHICKEN User s Manual The User s Manual TYPE SLOTNAME or TYPE SLOTNAME SIZE The latter form defines an array of SIZE elements of the type TYPE embedded in the structure For every slot the f
247. ose that support interactive evaluation of forms during editing Pointers to these and to any editor customization files appropriate should be put on the Chicken wiki and will likely be added to future editions of this manual We have had a request for editors that support proportional fonts in particular Emacs http www gnu org software emacs is an extensible customizable self documenting editor available for Linux Unix Macintosh and Windows systems CHICKEN provides Emacs support out of the box with the hen el Emacs Lisp file Consult the Emacs Guide for Chicken Users which will be available on the Chicken Wiki soon for information on setting up and using Emacs with Chicken Epsilon http www lugaru com is a commercial proprietary text editor whose design was inspired by Emacs Although Scheme support isn t provided a Lisp mode is available on Lugaru s FTP site and could with some work be made to duplicate the Emacs support SciTE http scintilla sourceforge net SciTE html unlike Emacs or Vim follows typical graphical UI design conventions and control key mappings and for simple tasks is as familiar and easy to use as Notepad KEdit TeachText etc However it has many programming features such as multiple open files syntax highlighting for a large number of languages including Lisps matching of brackets ability to fold sections of code based on the matched brackets column selections comment uncomment and the abi
248. ou can find basic information about Chicken downloads and pointers to other key resources The Chicken wiki http chicken wiki br contains the most current version of the User s manual along with various tutorials and other useful documents The list of eggs is at http chicken wiki br Eggs 20Unlimited 203 A very useful search facility for questions about Chicken is found at http www callcc org The Chicken issue tracker is at http trac callcc org The Chicken community has two major mailing lists If you are a Chicken user Chicken Users http lists nongnu org mailman listinfo chicken users will be of interest The crew working on the Chicken system itself uses the very low volume Chicken Hackers list http lists nongnu org mailman listinfo chicken hackers for communication 2 3 Chicken repositories websites and community 4 CHICKEN User s Manual The User s Manual 2 4 Installing Chicken Chicken is available in binary form for Windows and Linux x86 systems and in source form for all other platforms Refer to the README file in the distribution for instructions on installing it on your system Because it compiles to C Chicken requires that a C compiler be installed on your system If you re not writing embedded C code you can pretty much ignore the C compiler once you have installed it e On a Linux system the GNU Compiler Collection JCC should be installed as part of the basic operating system or shou
249. ould not be modified 16 2 5 queue add procedure queue add QUEUE X Adds X to the rear of QUEUE 16 2 6 queue empty procedure queue empty QUEUE Returns t if QUEUE is empty or f otherwise 16 2 7 queue first procedure queue first QUEUE Returns the first element of QUEUE If QUEUE is empty an error is signaled 16 2 2 make queue 101 CHICKEN User s Manual The User s Manual 16 2 8 queue last procedure queue last QUEUE Returns the last element of QUEUE If QUEUE is empty an error is signaled 16 2 9 queue remove procedure queue remove QUEUE Removes and returns the first element of QUEUE If QUEUE is empty an error is signaled 16 2 10 queue push back procedure queue push back QUEUE ITEM Pushes an item into the first position of a queue i e the next queue remove will return ITEM 16 2 11 queue push back list procedure queue push back list QUEUE LIST Pushes the items in item list back onto the queue so that car LIST becomes the next removable item 16 3 Sorting 16 3 1 merge procedure merge LIST1 LIST2 LESS procedure merge LIST1 LIST2 LESS Joins two lists in sorted order merge is the destructive version of merge LESS should be a procedure of two arguments that returns true if the first argument is to be ordered before the second argument 16 2 8 queue last 102 CHICKEN User s Manual The User s Manual 16 3 2 sort procedure sort SEQUENCE LESS
250. ows open noinherit This variable is a mode value for create pipe Useful when spawning a child process spawn overlay spawn wait spawn nowait spawn nowaito spawn detach These variables contains special flags that specify the exact semantics of process spawn spawn overLlay replaces the current process with the new one Spawn wait suspends execution of the current process until the spawned process returns spawn nowait does the opposite spawn nowaito is identical according to the Microsoft documentation and runs the process asynchronously spawn detach runs the new process in the background without being attached to a console 27 24 4 process spawn procedure process spawn MODE COMMAND ARGUMENT LIST ENVIRONMENT LIST EXACT Creates and runs a new process with the given COMMAND filename and the optional ARGUMENT LIST and ENVIRONMENT LIST MODE specifies how exactly the process should be executed and must be one or more of the spawn flags defined above The EXACT FLAG default f controls quote wrapping of argument strings When t quote wrapping is not performed Returns the exit status when synchronous e the PID when asynchronous when failure Previous Unit srfi 18 Next Unit utils 27 24 3 Additional Definitions 183 28 Unit utils This unit contains file pathname oriented procedures apropos plus acts as a grab bag for procedures without a good home and which don t have to be availa
251. p t to pipe E 154 XENON NT dive AEE A lees vaateesh nee av veu sere waite 154 PERSEO TT D mE 154 xi CHICKEN User s Manual The User s Manual Chicken User s Manual 27 Unit posix 2TA PAN EU EE 154 27 5 File descriptors and low level UO 155 ER DN d plicate TEN EE 155 Qe D2 EEN Te E 155 E EE E 155 21 54 EE 155 27 59 E EE 156 DIDO Ee EE 156 21 5 7 EE 156 27 58 Mle conti E 156 ER ENT EE RE 156 27 5 10 0pen output file EE 157 Df DV POTN UC NL RR 157 27 6 Retrieving file attributes eoe ir D caapssaceaeoaneaa REPAIR tenes dedesuacsuancesuesnganegae REEF TER NE TEREE ESE 157 PA OS Mb il eere e I IRIURE UT TM 157 21 6 2 EE E 157 Z p3Dle modibeapon ume nemen nemen nn n nnns nsns asas asses ss ss sa ee 157 Ee EE 157 ERT Tee TEE 158 2 EGO EK 158 PAESI CIE EE 158 ENEE STREET Uu 158 ERSTEN EE EE 158 27610 TiE TEAd ACCESS E EE vedesnvassesdn ladadeansmageassnvededacdecssesaees 159 DAO EE KI LEE 159 2126 12 Ee Tee 159 21 6 13 EE 159 PE SM bae Gane e 159 Re EE Eed E 159 21 6 EE Elle Ee 159 POS KEE E EE 159 21 61 EE 159 21 0 19 St8t S0 Ke bo sor e Ee E ee e Ee 159 27 7 Changing tile attributes senis osi orno ia DR ERE GT IRR PRRAE CERE Re ed EEN 160 27 AV RURSUS 160 21 FD SCt TSP OST OM E 160 ENEE E TEE 160 21 7 4 EI EEN 160 21 8 PEOCESSES E 161 21 8 T Cum Mt PLOCESS AC 2stesycssttssssdacessnscsudvsesieessadescvansadedeneteass A A OE EEE 161 21 8 2 p rent prOCess Id
252. pecifier no argc checks Disables argument count checking 12 23 no bound checks declaration specifier no bound checks Disables the bound checking of toplevel bindings 12 24 no procedure checks declaration specifier no procedure checks Disables checking of values in operator position for being of procedure type 12 25 post process declaration specifier post process STRING Arranges for the shell commands STRING to be invoked after the current file has been translated to C Any occurrences of the substring in the strings given for this declaration will be replaced by the pathname of the currently compiled file without the file extension This declaration will only work if the source file is compiled with the CSC compiler driver 12 26 number type 12 27 fixnum arithmetic declaration specifier number type TYPE declaration specifier fixnum arithmetic Declares that only numbers of the given type are used TYPE may be fixnum or generic which is the default 12 22 no argc checks 62 CHICKEN User s Manual The User s Manual 12 28 run time macros declaration specifier run time macros Equivalent to the compiler option of the same name macros defined in the compiled code are also made available at runtime 12 29 standard bindings declaration specifier standard bindings SYMBOL declaration specifier not standard bindings SYMBOL Declares that all given standard proc
253. play string append arg if palindrome arg is a palindrome n isn t a palindrome n We can compile this program using CSC creating an executable named palindrome csc o palindrome palindrome scm palindrome level level is a palindrome palindrome liver liver isn t a palindrome Chicken supports separate compilation using some extensions to Scheme Let s divide our palindrome program into a library module pal proc scm and a client module pal user scm Here s the external library We declare that pal proc is a unit which is the basis of separately compiled modules in Chicken Units deal with separate compilation but don t involve separated namespaces namespaced module systems are available as eggs Library pal proc scm declare unit pal proc define palindrome x define check left right if gt left right t and charz string ref x left string ref x right check add1 left subl right check 0 subl string length x Next we have some client code that uses this separately compiled module Client pal user scm declare uses pal proc let arg car command line arguments display string append arg if palindrome arg is a palindrome n isn t a palindrome n 2 7 The compiler CHICKEN User s Manual The User s Manual Now we can compile and link everything together We show the compile and link operations separately but they
254. procedure OLD PROC Replaces the procedure OLD with the result of calling the one argument procedure PROC PROC will receive a copy of OLD that will be identical in behaviour to the result of PROC Replace arbitrary procedure with tracing one mutate procedure my proc lambda new lambda args printf s called with arguments s new args apply new args Previous Unit tcp Next Interface to external functions and variables 30 9 1 object become 208 31 Interface to external functions and variables e Accessing external objects Foreign type specifiers e Embedding e Callbacks e Locations Other support procedures e C interface Previous Supported language Next chicken setup 31 Interface to external functions and variables 209 32 Accessing external objects 32 1 foreign code syntax foreign code STRING Executes the embedded C C code STRING which should be a sequence of C statements which are executed and return an unspecified result foreign code doSomeInitStuff gt unspecified Code wrapped inside foreign code may not invoke callbacks into Scheme 32 2 foreign value syntax foreign value STRING TYPE Evaluates the embedded C C expression STRING returning a value of type given in the foreign type specifier TYPE print foreign value my version string c string 32 3 foreign declare syntax foreign declare STRING Include given strings ver
255. process group id PID PGID setter set process group id PID PGID Sets the process group ID of the process specifed by PID to PGID 27 12 Record locking 27 12 1 file lock procedure file lock PORT START LEN Locks the file associated with PORT for reading or writing according to whether PORT is an input or output port START specifies the starting position in the file to be locked and defaults to 0 LEN specifies the length of the portion to be locked and defaults to t which means the complete file fi le LOCK returns a lock object 27 11 Changing user amp group information 166 CHICKEN User s Manual The User s Manual 27 12 2 file lock blocking procedure file lock blocking PORT START LEN Similar to file lock but if a lock is held on the file the current process blocks including all threads until the lock is released 27 12 3 file test lock procedure file test lock PORT START LEN Tests whether the file associated with PORT is locked for reading or writing according to whether PORT is an input or output port and returns either f or the process id of the locking process 27 12 4 file unlock procedure file unlock LOCK Unlocks the previously locked portion of a file given in LOCK 27 13 Signal handling 27 13 1 set alarm procedure set alarm SECONDS Sets an internal timer to raise the signal alrm after SECONDS are elapsed You can use the set signal handler procedure t
256. pt print eval with input from string car command line arguments read chmod x foo foo 3 4 N o o The parameter command Line arguments is set to a list of the parameters that were passed to the Scheme script Scripts can be compiled to standalone executables don t forget to declare used library units CHICKEN supports writing shell scripts in Scheme for these platforms as well using a slightly different approach The first example would look like this on Windows C gt type foo bat csibatch 0 1 2 3 4 5 6 7 8 9 print eval with input from string car command line arguments read C gt foo 3 4 7 Like UNIX scripts batch files can be compiled Windows batch scripts do not accept more than 8 arguments Since it is sometimes useful to run a script into the interpreter without actually running it for example to test specific parts of it the option SS can be used as an alternative to script ss PATHNAME is equivalent to script PATHNAME but invokes main command line arguments after loading all top level forms of the script file The result of Main is returned as the exit status to the shell Any non numeric result exits with status zero 5 1 Interpreter command line format 25 CHICKEN User s Manual The User s Manual cat hi scm define main args print Hi car args 0 Csi ss hi scm you D you csi q l l hi scm 2 gt main list ye all i y
257. ptrs to be garbage collection roots The locations should not contain pointers to data allocated in the nursery only immediate values or pointers to heap data are valid Any assignment of potential nursery data into a root array should be done via C mutate The variables have to be initialized to sensible values before the next garbage collection starts when in doubt set all locations in ptrstoC SCHEME UNDEFINED C gc protect may not called before the runtime system has been initialized either by CHICKEN initialize CHICKEN run or CHICKEN invoke For a slightly simpler interface to creating and using GC roots see CHICKEN new gc root 38 45 C gc unprotect C function void C gc unprotect int n Removes the last n registered variables from the set of root variables 38 41 C make header 242 CHICKEN User s Manual The User s Manual 38 46 C pre gc hook C Variable void C pre gc hook int mode If not NULL the function pointed to by this variable will be called before each garbage collection with a flag indicating what kind of collection was performed either 0 for a minor collection or 2 for a resizing collection A resizing collection means a secondary collection that moves all live data into a enlarged or shrinked heap space Minor collections happen very frequently so the hook function should not consume too much time The hook function may not invoke Scheme callbacks Note that resizing collections may be nested in normal majo
258. r EE 242 38 43 C re 242 30 44 e EE 242 36 45 C ge ter 242 38 46 C pre gc TEE 243 S8A47 C post 26 TOO P E E A A AE 243 38 48 An example for simple calls to foreign code involving callbacke 243 BEA NOLES RECRUIT 244 39 CNC KEN Se paa PE EEERE FEE MU UR EDO FUR RE RH eae mamas 245 39 1 Extension Ibraes ne nennen memet meses nen en nensis as ieee 245 39 2 Installing EE 245 39 2 1 Installing extensions that use Ibrartes ee eee ceteeeeeeceeacecenceceeeeeeeeesaaeeeeaeeeeneeeeaees 245 E EE 246 39 4 Procedures and macros available in setup scpts nennen 246 SE Di BEE E Ter 246 39 4 2 1nstall prograt ET 248 39 43 ins tall Sra EE 248 DO AeA TU EE 248 SET EE 248 SE A000 eiiie Ea E a E E E E EAN 249 SE 249 SOAS COP UE 249 SNE Rule TEE 249 39 4 10 ue RE 249 30 4 11 Et De enero ettet ee ee nte nter aer re dekedeetedaanesvaden NAE RER e 240 39 4 12 find headen ccccssccccscocsssssnsccccecsssssnsceceesevsnssscesescovsssanceesssvssvsanscecscsessnsnsescessessnseseccevssvenss 250 39 413 Ru TEE 250 SEET EE 250 39 4 T5 chicken DEteTlx E 250 39 4 16unst llation prefix 24 eee ver ien reete een oaaae eiia aa deaa eiie eane 250 39 4 17 TEE score e ree EO RE PERPE EN PO EE EE ITO Nee ae pu era pee dva 250 30 4 18 NEE e E 251 SEENEN chen err e ei eria deep teure ETLE E A 251 XX CHICKEN User s Manual The User s Manual Chicken User s Manual 39 chicken setup 39 4 20 setup verbose T ag ii eee et rre ete dewceeatas eee e een ele ten
259. r collections 38 47 C post gc hook C Variable void C post gc hook int mode long ms If not NULL the function pointed to by this variable will be called after each garbage collection with a flag indicating what kind of collection was performed either O for a minor collection 1 for a major collection or 2 for a resizing collection Minor collections happen very frequently so the hook function should not consume too much time The hook function may not invoke Scheme callbacks The ms argument records the number of milliseconds required for the garbage collection if the collection was a major one For minor collections the value of the mS argument is undefined 38 48 An example for simple calls to foreign code involving callbacks cat foo scm gt extern int callout int int int lt define callout foreign safe lambda int callout int int int define external callin scheme object xyz int print This is callin xyz 123 print callout 1 2 3 cat bar c include lt stdio h gt include chicken h extern int callout int int int extern int callin C word x int callout int x int y int z 38 46 C pre gc hook 243 CHICKEN User s Manual The User s Manual C word ptr C alloc C SIZEOF LIST 3 C word lst printf This is callout d d Sd n x y Z lst C list amp ptr 3 C fix x C fix y C fix z return callin lst Note callin will have GC d the data in
260. r is not added When 25 13 string substitute 142 CHICKEN User s Manual The User s Manual WITHOUT EOL is t the end of line anchor is not added The WITHOUT BOL and WITHOUT EOL arguments are ignored for a precompiled regular expression Previous Unit match Next Unit srfi 18 25 16 make anchored pattern 143 26 Unit srfi 18 A simple multithreading package This threading package follows largely the specification of SRFI 18 For more information see the documentation for SRFI 18 Notes e thread start accepts a thunk a zero argument procedure as argument which is equivalent to thread start make thread THUNK e thread sleep accepts a seconds real number value in addition to a time object e When an uncaught exception i e an error is signalled in a thread other than the primordial thread and warnings are enabled see enable warnings then a warning message is written to the port that is the value of current error port e Blocking I O will block all threads except for some socket operations see the section about the tcp unit An exception is the read eval print loop on UNIX platforms waiting for input will not block other threads provided the current input port reads input from a console e t is generally not a good idea for one thread to call a continuation created by another thread if dynamic wind is involved When more than one thread compete for the current time slice the thread that was waiting
261. r s Manual The User s Manual 14 8 8 machine type procedure machine type Returns a symbol specifying the processor on which this process is currently running which is one of the following alpha mips hppa ultrasparc sparc ppc ppc64 ia64 x86 x86 64 unknown 14 8 9 on exit procedure on exit THUNK Schedules the zero argument procedures THUNK to be executed before the process exits either explicitly via exit or implicitly after execution of the last top level form Note that finalizers for unreferenced finalized data are run before exit procedures 14 8 10 software type procedure software type Returns a symbol specifying the operating system on which this process is currently running which is one of the following windows unix macos ecos unknown 14 8 11 software version procedure software version Returns a symbol specifying the operating system version on which this process is currently running which is one of the following 14 8 8 machine type 78 CHICKEN User s Manual The User s Manual Linux freebsd netbsd openbsd macosx hpux solaris sunos unknown 14 8 12 c runtime procedure c runtime Returns a symbol that designates what kind of C runtime library has been linked with this version of the Chicken libraries Possible return values are Static dynamic or unknown On systems not compiled with the Microsoft C compiler C runtime always returns unknown 14 8 13 system proce
262. rators 17 3 1 port for each procedure port for each FN THUNK Apply FN to successive results of calling the zero argument procedure THUNK until it returns eof discarding the results 17 3 2 port map procedure port map FN THUNK Apply FN to successive results of calling the zero argument procedure THUNK until it returns eof returning a list of the collected results 17 3 3 port fold procedure port map FN ACC THUNK Apply FN to successive results of calling the zero argument procedure THUNK passing the ACC value as the second argument The FN result becomes the new ACC value When THUNK returns eof the last FN result is returned 17 4 Funky ports 17 4 1 make broadcast port procedure make broadcast port PORT Returns a custom output port that emits everything written into it to the ports given as PORT Closing the broadcast port does not close any of the argument ports 17 4 2 make concatenated port procedure make concatenated port PORT1 PORT2 17 3 Port iterators 112 CHICKEN User s Manual The User s Manual Returns a custom input port that reads its input from PORT1 until it is empty then from PORT2 and so on Closing the concatenated port does not close any of the argument ports Previous Unit data structures Next Unit extras 17 4 2 make concatenated port 113 18 Unit extras This unit contains a collection of useful utility definitions This unit is used by default u
263. re procedure procedure procedure procedure procedure procedure procedure procedure procedure procedure 20 25 blobf64vector blob gt u8vector BLOB blob gt s8vector BLOB blob gt ul6vector blob gt sl6vector blob gt u32vector blob gt s32vector blob gt f32vector blob gt f64vector blob gt u8vector shared BLOB blob gt s8vector shared BLOB blob gt ul6vector shared BLOB blob gt sl6vector shared BLOB blob gt u32vector shared BLOB blob gt s32vector shared BLOB BLOB BLOB BLOB BLOB BLOB BLOB CHICKEN User s Manual The User s Manual procedure blob gt f32vector shared BLOB procedure blob gt f64vector shared BLOB Each of these procedures return a vector where the argument BLOB is taken as a packed representation of the contents of the vector The Shared variants return a vector that shares memory with the contents of the blob 20 34 subu8vector 20 35 subu16vector 20 36 subu32vector 20 37 subs8vector 20 38 subs16vector 20 39 subs32vector 20 40 subf32vector 20 41 subf64vector procedure subu8vector U8VECTOR FROM TO procedure subul6vector U16VECTOR FROM TO procedure subu32vector U32VECTOR FROM TO procedure subs8vector S8VECTOR FROM TO procedure subsl6vector S16VECTOR FROM TO procedure subs32vector S32VECTOR FROM TO procedure subf32vector F32VECTOR FROM TO procedure subf64vector F64VECTOR FROM TO 20 33 blobf64vector share
264. re information see make 39 4 7 patch procedure patch WHICH REGEX SUBST Replaces all occurrences of the regular expression REGEX with the string SUBST in the file given in WHICH If WHICH is a string the file will be patched and overwritten If WHICH is a list of the form OLD NEW then a different file named NEW will be generated 39 4 8 copy file procedure copy file FROM TO Copies the file or directory recursively given in the string FROM to the destination file or directory TO 39 4 9 move file procedure move file FROM TO Moves the file or directory recursively given in the string FROM to the destination file or directory TO 39 4 10 remove file procedure remove file PATH Removes the file or directory given in the string PATH 39 4 11 find library procedure find library NAME PROC Returns t if the library named LibNAME a s0 unix or NAME Lib windows could be found by compiling and linking a test program PROC should be the name of a C function that must be provided by the library If no such library was found or the function could not be resolved f is returned 39 4 6 make 249 CHICKEN User s Manual The User s Manual 39 4 12 find header procedure find header NAME Returns t if a C include file with the given name is available or f otherwise 39 4 13 try compile procedure try compile CODE key cc cflags ldflags compile only c Returns t if the C code in CODE compile
265. rguments The second is to define an externally visible wrapper function around a Scheme procedure with the define external form Note the names of all functions variables and macros exported by the CHICKEN runtime system start with C Itis advisable to use a different naming scheme for your own code to avoid name clashes Callbacks defined by def ine externaLl do not capture the lexical environment Non local exits leaving the scope of the invocation of a callback from Scheme into C will not remove the C call frame from the stack and will result in a memory leak 35 1 define external syntax define external QUALIFIERS NAME ARGUMENTTYPE1 VARIABLE1 RET syntax define external NAME TYPE INIT The first form defines an externally callable Scheme procedure NAME should be a symbol which when converted to a string represents a legal C identifier ARGUMENTTYPE1 and RETURNTYPE are foreign type specifiers for the argument variables VAR1 and the result respectively QUALIFIERS is an optional qualifier for the foreign procedure definition like stdcall define external foo c string x int string length x The second form of define external can be used to define variables that are accessible from foreign code It declares a global variable named by the symbol NAME that has the type TYPE INIT can be an arbitrary expression that is used to initialize the variable NAME is accessible from Scheme just like any other
266. ring 27 16 1 secondslocal time 173 CHICKEN User s Manual The User s Manual 27 16 4 secondsstring procedure seconds gt string SECONDS Converts the local time represented in SECONDS into a string of the form Tue May 21 13 46 22 1991 27 16 5 secondsutc time procedure seconds gt utc time SECONDS Similar to seconds gt Local time but interpretes SECONDS as UTC time 27 16 6 utc timeseconds procedure utc time gt seconds VECTOR Converts the ten element vector VECTOR representing the UTC time value into the number of seconds since the first of January 1970 UTC 27 16 7 timestring procedure time gt string VECTOR Converts the broken down time represented in the 10 element vector VECTOR into a string of the form Tue May 21 13 46 22 1991 27 17 Raw exit 27 17 1 exit procedure exit CODE Exits the current process without flushing any buffered output using the C function exit Note that the exit handLler is not called when this procedure is invoked The optional return code CODE defaults to 0 27 16 4 secondsstring 174 CHICKEN User s Manual The User s Manual 27 18 ERRNO values 27 18 1 errno perm 27 18 2 errno noent 27 18 3 errno srch 27 18 4 errno intr 27 18 5 errno io 27 18 6 errno noexec 27 18 7 errno badf 27 18 8 errno child 27 18 9 errno nomem 27 18 10 errno acces 27 18 ERRNO values 175 CHICKEN User s Manual The User s Manual 27 18 11 errno
267. root void root Deletes the gc root 34 18 CHICKEN gc root ref C macro C word CHICKEN gc root ref void root Returns the value stored in the gc root 34 19 CHICKEN gc root set C macro void CHICKEN gc root set void root C word value Sets the content of the GC root to a new value Sometimes it is handy to access global variables from C code 34 16 CHICKEN new gc root 229 CHICKEN User s Manual The User s Manual 34 20 CHICKEN global lookup C function void CHICKEN global lookup char name Returns a GC root that holds the global variable with the name name If no such variable exists NULL is returned 34 21 CHICKEN global ref C function C word CHICKEN global ref void global Returns the value of the global variable referenced by the GC root global 34 22 CHICKEN global set C function void CHICKEN global set void global C word value Sets the value of the global variable referenced by the GC root global to value Previous Foreign type specifiers Next Callbacks 34 20 CHICKEN global lookup 230 35 Callbacks To enable an external C function to call back to Scheme the form foreign safe Lambda or foreign safe lambda has to be used This generates special code to save and restore important state information during execution of C code There are two ways of calling Scheme procedures from C the first is to invoke the runtime function C callback with the closure to be called and the number of a
268. rrors caused by accessing non existent elements of a collection exn runtime Signaled on low level runtime system error situations 14 7 1 condition case 75 CHICKEN User s Manual The User s Manual exn runtime Limit Signaled when an internal limit is exceeded like running out of memory exn match Signaled on errors raised by failed matches see the section on mat ch exn syntax Signaled on syntax errors exn breakpoint Signaled when a breakpoint is reached Notes All error exceptions of the kind exn are non continuable Error exceptions of the exn kind have additional arguments and Location properties that contain the arguments passed to the exception handler and the name of the procedure where the error occurred if available When the posix unit is available and used then a user interrupt signal int signals an exception of the kind user interrupt the procedure condition property accessor accepts an optional third argument If the condition does not have a value for the desired property and if the optional argument is given no error is signaled and the accessor returns the third argument n composite conditions all properties are currently collected in a single property list so in the case that to conditions have the same named property only one will be visible 14 8 Environment information and system interface 14 8 1 argv procedure argv Return a list of all supplied command
269. ructure to be expressed in a concise manner Pattern matching is found in several modern languages notably Standard ML Haskell and Miranda These syntactic extensions internally use the match library unit Note this pattern matching package is not compatible with hygienic macro expanders like the syntax case extension available separately The basic form of pattern matching expression is match exp pat body where exp is an expression pat is a pattern and body is one or more expressions like the body of a lambda expression The match form matches its first subexpression against a sequence of patterns and branches to the body corresponding to the first pattern successfully matched For example the following code defines the usual map function define map lambda f 1 match l O 543 x y cons f x map f y 1 The first pattern matches the empty list The second pattern X y matches a pair binding X to the first component of the pair and y to the second component of the pair 11 1 Pattern Matching Expressions The complete syntax of the pattern matching expressions follows exp match exp clause match lambda clause match lambda clause match let pat exp body match let pat exp body match letrec pat exp body match let var pat exp body match define pat exp clause pat body pat gt identifier body pat id
270. ry file Retrieve complete extension repository big cd opt svn co https galinha ucpel tche br svn chicken eggs release 3 eggs 39 7 Windows notes 257 CHICKEN User s Manual The User s Manual Get your own copy of the repository file chicken setup fetch tree gt my repository file Now you can install eggs from your local checkout with full dependency tracking and without being connected to the internet cd tmp chicken setup local opt eggs tree my repository file opengl 39 10 Linking extensions statically The compiler and chicken setup support statically linked eggs The general approach is to generate an object file or static library in addition to the usual shared library in your Setup script and install it along with the dynamically loadable extension The setup properties Static should contain the name of the object file or static library to be linked when CSC gets passed the static extensions option compile s 02 dl my ext scm dynamically loadable normal version compile c 02 d1 my ext unit my ext statically linkable version install extension my ext my ext so 0 t static my ext o Mo gH e my ex i Note the use of the Unit option in the second compilation step static linking must use static library units chicken setup will perform platform dependent file extension translation for the file list but does currently not do that for the Static extension
271. s a procedure of one argument PROC that will be called as soon as the non immediate data object X is about to be garbage collected with that object as its argument Note that the finalizer will not be called while interrupts are disabled This procedure returns X 14 11 4 set gc report procedure set gc report FLAG Print statistics after every GC depending on FLAG A value of t shows statistics after every major GC A true value different from t shows statistics after every minor GC f switches statistics off 14 12 Other control structures 14 11 Garbage collection 82 CHICKEN User s Manual The User s Manual 14 12 1 promise procedure promise X Returns t if X is a promise returned by de Lay or f otherwise 14 13 String utilities 14 13 1 reverse liststring procedure reverse list gt string LIST Returns a string with the characters in LIST in reverse order This is equivalent to List gt string reverse LIST but much more efficient 14 14 Generating uninterned symbols 14 14 1 gensym procedure gensym STRING OR SYMBOL Returns a newly created uninterned symbol If an argument is provided the new symbol is prefixed with that argument 14 14 2 stringuninterned symbol procedure string gt uninterned symbol STRING Returns a newly created unique symbol with the name STRING 14 15 Standard Input Output 14 12 1 promise 83 CHICKEN User s Manual The User s Manual 14 15 1 port
272. s and links successfully or f otherwise The keyword parameters CC compiler name defaults to the C compiler used to build this system Cf Lags and Ldflags accept additional compilation and linking options If compile only is true then no linking step takes place If the keyword argument C is given and true then the code will be compiled in C mode 39 4 14 create directory procedure create directory PATH Creates the directory given in the string PATH with all parent directories as needed 39 4 15 chicken prefix parameter chicken prefix The installation prefix specified when CHICKEN was built 39 4 16 installation prefix parameter installation prefix An alternative installation prefix that will be prepended to extension installation paths if specified It is set by the install prefix option or environment variable CHICKEN INSTALL PREFIX 39 4 17 program path parameter program path PATH 39 4 12 find header 250 CHICKEN User s Manual The User s Manual Holds the path where executables are installed and defaults to either CHICKEN PREFIX bin ifthe environment variable CHICKEN PREFIX is set or the path where the CHICKEN binaries chicken csi etc are installed 39 4 18 setup root directory parameter setup root directory PATH Contains the path of the directory where chicken setup was invoked 39 4 19 setup build directory parameter setup build directory PATH Contains the path of the d
273. se see the mpi egg 42 1 9 Why doesn t CHICKEN support the full numeric tower by default 264 CHICKEN User s Manual The User s Manual 42 1 12 Does CHICKEN support Unicode strings Yes as an extension By default all string and character functions operate bytewise so that characters with an iteger value greater than 255 don t make much sense and multibyte UTF 8 characters are seen and manipulated as separate bytes analogous to what a C program would see You can enable UTF 8 support by placing the following two lines at the beginning of your source file or in your csirc for interactive sessions before any other code including other use directives use iset syntax case utf8 import utf8 This will replace all builtin string operators with UTF 8 aware versions that will treat strings as sequences of multibyte UTF 8 characters thus enabling you to represent and manipulate Unicode characters while remaining compatible with most C libraries and system interfaces Most eggs should work correctly in utf8 mode including the regex extension but you still have the option of working around incompatibilities of specific eggs by loading them before the import utf8 directive Keep in mind that some operations such as string length are much more expensive in utf8 multibyte mode and should be used with care See the utf8 egg documentation for details 42 1 13 Why do I get an Error invalid syntax using match and syntax c
274. sh t ble SIZ amp co rrt arreter EER ERE EEEE NE ERE 128 23 1 4 bach Goble couivalence Tunctnon eene 129 23 1 5 bhasb able hasbh Tuncpon nennen meneme nemen nemen 129 23 1 6 hash table min lOad eene a nnn nnn nenas ases esses 129 23 bhasbh able ma Joad em mnn nnn nnn nnn nns nsns enean 129 23 1 8 hash table w eak K6ys eere rene rene inte tnde e cene bn eee He E Ee ded 129 23 1 9 bhasbh able weak valuesg eene eene nene meneneee nemen nenne nennen 129 23 1 10 hash table has initial essen nnne nnnn nennen nnns nnne 130 23 1 11 basb oble mmm 130 23 1 12 hashetable KGyS eite tbe tete dett etie Pa e Une eee de hee e e nete Pe er pnta tes 130 SNE ET ER 130 23 ENEE EI EE 130 23 1 15 alisthash tables scccssscseceassscsicsssnsdecesovessesavasevevevacevassesdevedecannsdeacsasavaseeannndteradvedvesadedded sates 130 23 1 16 h sh table Tel c erem eror aeter tem eee ss ies svaalenvedestacodea teer er er mE aep Po VOUS 131 23 1 17 EE EE ELE 131 23 EE El 131 23 1 19 h sh table sett uii certare ett heat law eet vato sek ga tese ons tne lenior beealton teet a eor c 131 23 1 20 hash table update eee eere tenente netten ener nne eade eie iiini 131 23 1 21 bach Goble update lidetault eren 132 23 EE EE 132 23 1 23 hash table delete ic scesssescsesssscseceassedesveseceve vedas sand eege Ed ENEE EN E gre ERE T PR Vara cue 132 23 1 24 hashstabl TemOyVel s oo oed are ege sue ENEE EEN 13
275. ssions show expressions converted into CPS show database after each analysis pass show expressions after each optimization pass show expressions after each inlining pass show expressions after complete optimization show database after final analysis show expressions after closure conversion LO OO Jon P uMtaA ST OC SO zs Co DS Koay debug level LEVEL Selects amount of debug information LEVEL should be an integer debug level 0 is equivalent to no trace no lambda info debug level 1 is equivalent to no trace debug level 2 does nothing the default disable interrupts Equivalent to the disable interrupts declaration No interrupt checks are generated for compiled programs disable compiler macros disable expansion of compiler macros disable stack overflow checks Disables detection of stack overflows This is equivalent to running the compiled executable with the 10 runtime option disable warning CLASS Disables specific class of warnings may be given multiple times The following classes are defined usage warnings related to command line arguments type warnings related to type conversion ext warnings related to extension libraries var warnings related to variable and syntax definitions and const warnings related to constant definitions syntax syntax related warnings redef warnings about redefinitions of standard or extended bi call warnings related to known procedure calls ffi warnings related to the fore
276. stalling extensions that use libraries Sometimes an extension requires a C library to compile Compilation can fail when your system has this library in a nonstandard location Luckily normally Chicken searches in the default locations usr and usr LlocaL and in the prefix where Chicken itself was installed Sometimes this is not enough so you ll need to supply chicken setup with some extra hints to the C compiler linker Here s an example chicken setup c I usr pkg include mysql c L usr pkg lib mysql c L 39 chicken setup 245 CHICKEN User s Manual The User s Manual This installs the mysql egg with the extra compiler options I and L to set the include path and the library search path The second L switch passes the R option directly to the linker which causes the library path to get hardcoded into the resulting extension file for systems that do not use Id so conf 39 3 Creating extensions Extensions can be created by creating an optionally gzipped tar archive named EXTENSION egg containing all needed files plus a Setup script in the root directory After chicken setup has extracted the files the setup script will be invoked There are no additional constraints on the structure of the archive but the setup script has to be in the root path of the archive 39 4 Procedures and macros available in setup scripts 39 4 1 install extension install extension ID FILELIST INFOLIST Installs the extension library
277. stat socket FILENAME These procedures return t if the FILENAME given is of the appropriate type 27 7 Changing file attributes 27 7 1 file truncate procedure file truncate FILE OFFSET Truncates the file FILE to the length OFFSET which should be an integer If the file size is smaller or equal to OFFSET then nothing is done FILE should be a filename or a file descriptor 27 7 2 set file position procedure set file position FILE POSITION WHENCE procedure set file position FILE POSITION Sets the current read write position of FILE to POSITION which should be an exact integer FILE should be a port or a file descriptor WHENCE specifies how the position is to interpreted and should be one of the values seek set seek cur and seek end It defaults to seek set Exceptions exn bounds exn i o file 27 7 3 change file mode procedure change file mode FILENAME MODE Changes the current file mode of the file named FILENAME to MODE using the chmod system call The perm variables contain the various permission bits and can be combinded with the bitwise ior procedure 27 7 4 change file owner procedure change file owner FILENAME UID GID Changes the owner information of the file named FILENAME to the user and group ids UID and GID which should be exact integers using the chown system call 27 6 19 stat socket 160 CHICKEN User s Manual The User s Manual 27 8 Processes 27 8 1 curren
278. string or a number the comparison is done lexicographically using st ring gt See also set extension specifier When syntax extensions are loaded that redefine the global toplevel macro expander for example the syntax case extension then all remaining expression in the same toplevel form are still expanded with the old toplevel macro expander 10 1 2 define extension syntax define extension NAME CLAUSE This macro simplifies the task of writing extensions that can be linked both statically and dynamically If encountered in interpreted code or code that is compiled into a shared object specifically if compiled with the feature chicken compi Le shared done automatically by CSC when compiling with the shared or dynamic option then the code given by clauses of the form dynamic EXPRESSION are inserted into the output as a begin form If compiled statically specifically if the feature chi cken compile shared has not been given then this form expands into the following declare unit NAME provide NAME and all clauses of the form static EXPRESSION all additionally inserted into the expansion As a convenience the clause export IDENTIFIER is also allowed and is identical to declare export IDENTIFIER unless the define extension form occurs in interpreted code in with it is simply ignored Note that the compiler option extension NAME is equivalent to prefixing the compiled fi
279. t This is actually useful sometimes 16 6 2 constantly procedure constantly X Returns a procedure that always returns the values X regardless of the number and value of its arguments constantly X lambda args X 16 6 3 complement procedure complement PROC Returns a procedure that returns the boolean inverse of PROC complement PROC lt gt lambda x not PROC x 16 6 4 compose procedure compose PROC1 PROC2 Returns a procedure that represents the composition of the argument procedures PROC1 PROC2 compose F G lambda args 16 5 11 substring index 106 CHICKEN User s Manual The User s Manual call with values Lambda apply G args F compose is equivalent to values 16 6 5 conjoin procedure conjoin PRED Returns a procedure that returns t if its argument satisfies the predicates PRED conjoin odd positive 33 gt dt conjoin odd positive 33 gt f 16 6 6 disjoin procedure disjoin PRED Returns a procedure that returns t if its argument satisfies any predicate PRED disjoin odd positive 32 gt t disjoin odd positive 32 gt T 16 6 7 each procedure each PROC Returns a procedure that applies PROC to its arguments and returns the result s of the last procedure application For example each pp eval is equivalent to Lambda args apply pp args apply eval args e
280. t for the host environment as opposed to the target environment This parameter is controlled by the host extension command line option A setup script should perform the proper steps of compiling any code by passing host when invoking CSC or using the compile macro 39 5 Examples for extensions The simplest case is a single file that does not export any syntax For example see eh te SE define hello name print Hello name 1 We need a Setup script to build and install our nifty extension hello setup compile the code into a dynamically loadable shared object will generate hello so compile s hello scm Install as extension library install extension hello heilo so After entering 39 4 23 required extension version 252 CHICKEN User s Manual The User s Manual chicken setup hello at the shell prompt and in the same directory where the two files exist the file hello scm will be compiled into a dynamically loadable library If the compilation succeeds hel lo SO will be stored in the repository together with a file named hello setup info containing an a list with metadata If no extension name is given to chicken setup it will simply execute the first file with the Setup extension it can find Use it like any other CHICKEN extension csi q 1 gt require extension hello loading usr local lib chicken 1 hello so 2 gt hello me Hello me 3 gt H
281. t process id procedure current process id Returns the process ID of the current process 27 8 2 parent process id procedure parent process id Returns the process ID of the parent of the current process 27 8 3 process group id procedure process group id PID Returns the process group ID of the process specified by PID 27 8 4 process execute procedure process execute PATHNAME ARGUMENT LIST ENVIRONMENT LIST Creates a new child process and replaces the running process with it using the C library function execvp 3 If the optional argument ARGUMENT LIST is given then it should contain a list of strings which are passed as arguments to the subprocess If the optional argument ENVIRONMENT LIST is supplied then the library function execve 2 is used and the environment passed in ENVIRONMENT LIST which should be of the form lt NAME gt lt VALUE gt _ is given to the invoked process Note that execvp 3 respects the current setting of the PATH environment variable while execve 3 does not 27 8 5 process fork procedure process fork THUNK Creates a new child process with the UNIX system call fork Returns either the PID of the child process or 0 If THUNK is given then the child process calls it as a procedure with no arguments and terminates 27 8 Processes 161 CHICKEN User s Manual The User s Manual 27 8 6 process run procedure process run COMMANDLINE procedure proc
282. t stack size depends on the target platform optimize leaf routines Enable leaf routine optimization optimize level LEVEL Enables certain sets of optimization options LEVEL should be an integer optimize level 0 does nothing optimize level 1 is equivalent to optimize leaf routines optimize level 2 is currently the same as optimize level 1 optimize level 3 is equivalent to optimize leaf routines unsafe output file FILENAME Specifies the pathname of the generated C file Default is FILENAME c postlude EXPRESSIONS Add EXPRESSIONS after all other toplevel expressions in the compiled file This option may be given multiple times Processing of this option takes place after processing of epilogue prelude EXPRESSIONS Add EXPRESSIONS before all other toplevel expressions in the compiled file This option may be given multiple times Processing of this option takes place before processing of prologue profile accumulate profile Instruments the source code to count procedure calls and execution times After the program terminates either via an explicit exit or implicitly profiling statistics are written to a file named PROFILE Each line of the generated file contains a list with the procedure name the number of calls and the time spent executing it Use the chi cken profile program to display the profiling information in a more user friendly form Enter chicken profile with no arguments at the command line to get a list of
283. t values Pointers to unions are allowed though 33 35 instance CNAME SCHEMECLASS A pointer to a C class instance CNAME should designate the name of the C class and SCHEMECLASS should be the class that wraps the instance pointer Normally SCHEMECLASS should be a subclass of crt object 33 36 instance ref CNAME SCHEMECLASS A reference to a C class instance 33 37 function RESULTTYPE ARGUMENTTYPEH CALLCONV A function pointer CALLCONV specifies an optional calling convention and should be a string The meaning of this string is entirely platform dependent The value f is also allowed and is passed as a NULL pointer 33 32 struct NAME 222 CHICKEN User s Manual The User s Manual 33 38 Mappings Foreign types are mapped to C types in the following manner bool unsigned char unsigned short unsigned int unsigned integer unsigned long float double number nonnull c pointer nonnull blob nonnull u8vector nonnull s8vector nonnull ul6vector nonnull s16vector nonnull u32vector nonnull s32vector nonnull f32vector nonnull f64vector nonnull c string nonnull unsigned c string c string list symbol void nonnull c pointer TYPE enum NAME struct NAME ref TYPE template T1 T2 union NAME function RTYPE ATYPE CALLCONV instance CNAME SNAME instance ref CNAME SNAME Previous Accessing external objects Next Embeddi
284. tead or in Unix machines modify your PATH environment variable to include your current directory 4 3 1 A simple example with one source file CHICKEN User s Manual The User s Manual 4 3 2 An example with multiple files If multiple bodies of Scheme code are to be combined into a single executable then we have to compile each file and link the resulting object files together with the runtime system Let s consider an example where your program consists of multiple source files 4 3 2 1 Writing your source files The declarations in these files specify which of the compiled files is the main module and which is the library module An executable can only have one main module since a program has only a single entry point In this case foo scm is the main module because it doesn t have a uni t declaration ijr T EEN The declaration marks this source file as dependant on the symbols provided by the bar unit declare uses bar write fac 10 newline bar scm will be our library bar scm The declaration marks this source file as the bar unit The names of the units and your files don t need to match declare unit bar define fac n if zero n 1 n fac n 1 4 3 2 2 Compiling and running your program You should compile your two files with the following commands csc C bar scm csc c foo scm That should produce two files bar o and foo o They contain the code from your source f
285. ter then it is bound to a list containing all the remaining arguments left over after the argument bindings with required parameters and optional parameters have been made e If key was specified in the parameter list there should be an even number of remaining arguments These are interpreted as a series of pairs where the first member of each pair is a keyword specifying the parameter name and the second member is the corresponding value If the same keyword occurs more than once in the list of arguments then the corresponding value of the first keyword is the binding value If there is no argument for a particular keyword parameter then the variable is bound to the result of evaluating lt initializer gt if one was specified otherwise f The corresponding lt initializer gt is evaluated in an environment in which all previous parameters have been bound Needing a special mention is the close relationship between the rest parameter and possible keyword parameters Declaring a rest parameter binds up all remaining arguments in a list as described above These same remaining arguments are also used for attempted matches with declared keyword parameters as described above in which case a matching keyword parameter binds to the corresponding value argument at the same time that both the keyword and value arguments are added to the rest parameter list Note that for efficiency reasons the keyword parameter matching does nothing more than simp
286. th of VECTOR then all additional items are initialized to INIT If INIT is not specified the contents are initialized to some unspecified value 14 19 The unspecified value 14 19 1 void procedure void Returns an unspecified value 14 20 Continuations 14 17 6 blobz 86 CHICKEN User s Manual The User s Manual 14 20 1 call cc procedure call cc PROCEDURE An alias for cal L with current continuation 14 20 2 continuation capture procedure continuation capture PROCEDURE Creates a continuation object representing the current continuation and tail calls PROCEDURE with this continuation as the single argument More information about this continuation API can be found in the paper http repository readscheme org ftp papers sw2001 feeley pdf A Better API for first class Continuations by Marc Feeley 14 20 3 continuation procedure continuation X Returns t if X is a continuation object or f otherwise Please note that this applies only to continuations created by the Continuation API but not by call cc i e Call with current continuation continuation returns f whereas continuation capture continuation returns t 14 20 4 continuation graft procedure continuation graft CONT THUNK Calls the procedure THUNK with no arguments and the implicit continuation CONT 14 20 5 continuation return procedure continuation return CONT VALUE Returns the value s to the continuation CONT continu
287. the storage in non garbage collected memory 20 1 make XXXvector procedure make XXXvector SIZE INIT NONGC FINALIZE Creates a SRFI 4 homogenous number vector of length SIZE If INIT is given it specifies the initial value for each slot in the vector The optional arguments NONGC and FINALIZE define whether the vector should be allocated in a memory area not subject to garbage collection and whether the associated storage should be automatically freed using finalization when there are no references from Scheme variables and data NONGC defaults to f the vector will be located in normal garbage collected memory and FINALIZE defaults to t Note that the FINALIZE argument is only used when NONGC is true Additionally the following procedures are provided 20 2 u8vectorblob 20 3 s8vectorblob 20 4 u16vectorblob 20 5 s16vectorblob 20 6 u32vectorblob 20 Unit srfi 4 120 CHICKEN User s Manual The User s Manual 20 7 s32vectorblob 20 8 f32vectorblob 20 9 f64vectorblob 20 10 u8vectorblob shared 20 11 s8vectorblob shared 20 12 u16vectorblob shared 20 13 s16vectorblob shared 20 14 u32vectorblob shared 20 15 s32vectorblob shared 20 16 f32vectorblob shared 20 17 f64vectorblob shared u8vector gt blob U8VECTOR s8vector gt blob S8VECTOR ul6vector gt blob U16VECTOR sl6vector gt blob S16VECTOR procedure procedure procedure procedure D 20 7 s32vectorblob 121 CHICKEN User s Manu
288. the value of current input port current output port to a port for a pipe connected to the subprocess named in CMDLINE and call the procedure THUNK with no arguments After THUNK returns normally the pipe is closed and the standard input output port is restored to its previous value and any result values are returned with output to pipe gs dNOPAUSE sDEVICE jpeg dBATCH sOutputFile signball lambda print Z EOF 951 TOPSC 1993 Creator HAYAKAWA Takashi XxxxXxxxX aXX XXXXXX XX XX C neg d mul R rlineto E exp H cvx def repeat def T dup g gt r roll J ifelse H A copy Z amp v4QX amp 93r9AxYQO0ZomQalxS2w O amp vMYa43d6r93rMYvx2dca D amp cjSnjSnj j 30 v amp 6 X amp 55SAxM1CD7Aj YxTTd62rmxCnTdSSTOg amp 12wECST amp JOgGD1 amp xMO JOg L amp 544dC2Ac96ra m amp 3 F amp amp vGoGSnCTOg amp wDmlvGoS8wpn6wpS2wTCpS1Sd70v7Uk704Qkdw amp Mvlx1S70Z2ES3w J J Q amp 7185 Z amp lx1CS9d9nEA4 k amp KX amp MY7 amp 1 I x amp jdnjdS3odS N amp mmx1C2wEc G amp 150Nx4 n amp 20 j amp 43r U amp 0777 2AY2A776ddT40S30SnMVC00VVORRRA5E42063rNz amp v7UXS amp UOzF F J amp 44ETCnVn a amp 1CDN Y amp O V1c amp j2AYdjmMdjjd o amp 1lr M T 0 4 3 r put T g T 9 g cvn cvi J g I I cvx forall moveto p floor w div S add 29 H setgray fill for Y for showpage EOF s Jpg g600x600 q 27 4 Fifos 27 4 1 create fifo procedure create fifo FILENAME MODE Creates a FIFO with the name FILENAME and the permission bits
289. tion run time macros has been used then the macro is visible in evaluated expressions during runtime The second possible syntax for def ine macro is allowed for portability purposes only In this case the second argument must be a lambda expression or a macro name Only global macros can be defined using this form define macro NAME1 NAME2 simply copies the macro definition from NAME2 to NAME creating an alias Extended lambda list syntax optional etc can be used but note that arguments are source expressions and thus default values for optional or keyword arguments should take this into consideration 10 4 4 define for syntax syntax define for syntax NAME VAR VAR EXP1 syntax define for syntax NAME VALUE Defines the toplevel variable NAME at macro expansion time This can be helpful when you want to define support procedures for use in macro transformers for example 10 5 Conditional forms 10 4 2 define inline 47 CHICKEN User s Manual The User s Manual 10 5 1 select syntax select EXP KEY EXP1 else EXPn This is similar to Case but the keys are evaluated 10 5 2 unless syntax unless TEST EXP1 EXP2 Equivalent to if not TEST begin EXP1 EXP2 10 5 3 when syntax when TEST EXP1 EXP2 Equivalent to if TEST begin EXP1 EXP2 10 6 Record structures 10 6 1 define record syntax define record NAME SLOTNAME Defines a re
290. tion PORT Returns the current position of PORT as two values row and column number If the port does not support such an operation an error is signaled This procedure is currently only available for input ports PORT defaults to the value of current input port 14 2 6 set port name procedure set port name PORT STRING Sets the name of PORT to STRING 14 3 Files 14 3 1 delete file procedure delete file STRING Deletes the file with the pathname STRING If the file does not exist an error is signaled 14 3 2 file exists procedure file exists STRING Returns STRING if a file with the given pathname exists or f otherwise 14 2 4 port name 71 CHICKEN User s Manual The User s Manual 14 3 3 rename file procedure rename file OLD NEW Renames the file or directory with the pathname OLD to NEW If the operation does not succeed an error is signaled 14 4 String ports 14 4 1 get output string procedure get output string PORT Returns accumulated output of a port created with open output string 14 4 2 open input string procedure open input string STRING Returns a port for reading from STRING 14 4 3 open output string procedure open output string Returns a port for accumulating output in a string 14 5 Feature identifiers CHICKEN maintains a global list of features naming functionality available in the current system Additionally the cond expand form accesses this feature
291. tive include pathnames separated by inline Enable procedure inlining for known procedures of a size below the threshold which can be set through the inline Limit option inline limit THRESHOLD Sets the maximum size of a potentially inlinable procedure The default threshold is 10 keyword style STYLE 4 1 Compiler command line format 15 CHICKEN User s Manual The User s Manual Enables alternative keyword syntax where STYLE may be either prefix as in Common Lisp suffix as in DSSSL or none Any other value is ignored The default is suf fix keep shadowed macros Do not remove macro definitions with the same name as assigned toplevel variables the default is to remove the macro definition lambda lift Enable the optimization known as lambda lifting no lambda info Don t emit additional information for each Lambda expression currently the argument list after alpha conversion renaming no trace Disable generation of tracing information If a compiled executable should halt due to a runtime error then a list of the name and the line number if available of the last procedure calls is printed unless no trace is specified With this option the generated code is slightly faster no warnings Disable generation of compiler warnings nursery NUMBER stack size NUMBER Sets the size of the first heap generation of the generated executable to NUMBER bytes The parameter may be followed by a M m or K k suffix The defaul
292. to use this chapter as the basis for writing and running small Chicken programs 2 1 Scheme Scheme is a member of the Lisp family of languages of which Common Lisp and Emacs Lisp are the other two widely known members As with Lisp dialects Scheme features a wide variety of programming paradigms including imperative functional and object oriented avery simple syntax based upon nested parenthesization the ability to extend the language in meaningful and useful ways In contrast to Common Lisp Scheme is very minimal and tries to include only those features absolutely necessary in programming In contrast to Emacs Lisp Scheme is not anchored into any one program Emacs and has a somewhat more modern language design Scheme is defined in a document called The Revised 5 Report on the Algorithmic Language Scheme or RSRS for short Yes it really has been revised five times so an expanded version of its name would be The Revised Revised Revised Revised Revised Report A newer report R6RS was released in 2007 but this report has attracted considerable controversy and not all Scheme implementations will be made compliant with it Chicken essentially complies with R5RS Even though Scheme is consciously minimalist it is recognized that a language must be more than a minimal core in order to be useful Accordingly the Scheme community uses a process known as Scheme Requests For Implementation SRFI pronounced SUR fee to defin
293. tr should be the address of an allocation pointer created with C alloc 38 19 C alloc C macro C word C alloc int words Allocates memory from the C stack C al loc and returns a pointer to it words should be the number of words needed for all data objects that are to be created in this function Note that stack allocated data objects have to be passed to Scheme callback functions or they will not be seen by the garbage collector This is really only usable for callback procedure invocations make sure not to use it in normal code because the allocated memory will be re used after the foreign procedure returns When invoking Scheme callback procedures a minor garbage collection is performed so data allocated with C alloc will already have moved to a safe place Note that C alloc is really just a wrapper around alloca and can also be simulated by declaring a stack allocated array of C words 38 14 C flonum 238 CHICKEN User s Manual The User s Manual 38 20 C SIZEOF LIST C macro int C SIZEOF LIST int length 38 21 C SIZEOF STRING C macro int C SIZEOF STRING int Length 38 22 C SIZEOF VECTOR C macro int C SIZEOF VECTOR int Length 38 23 C SIZEOF INTERNED SYMBOL C macro int C SIZEOF INTERNED SYMBOL int length 38 24 C SIZEOF PAIR C macro int C SIZEOF PAIR 38 25 C SIZEOF FLONUM C macro int C SIZEOF FLONUM 38 26 C SIZEOF POINTER C macro int C SIZEOF POINTER 38 27 C SIZEOF LOCATIVE C m
294. translate procedure string translate STRING SMAP Substitutes elements of STRING according to SMAP SMAP should be an association list where each element of the list is a pair of the form MATCH REPLACEMENT Every occurrence of the string MATCH in STRING will be replaced by the string REPLACEMENT string translate lt hl gt this is a string lt h1 gt 1 Slt 5 amp gt SN amp quot gt amp lt hl amp gt this is a amp quot string amp quot amp lt hl amp gt 16 5 10 substringz procedure substring STRING1 STRING2 START1 START2 LENGTH procedure substring ci STRING1 STRING2 START1 START2 LENGTH Returns t if the strings STRING1 and STRING2 are equal or f otherwise The comparison starts at the positions START1 and START2 which default to 0 comparing LENGTH characters which defaults to the minimum of the remaining length of both strings 16 5 7 string split 105 CHICKEN User s Manual The User s Manual 16 5 11 substring index procedure substring index WHICH WHERE START procedure substring index ci WHICH WHERE START Searches for first index in string WHERE where string WHICH occurs If the optional argument START is given then the search starts at that index substring index Ci is a case insensitive version of substring index 16 6 Combinators 16 6 1 any procedure any X Ignores its argument and always returns
295. turns true if FILENAME names a symbolic link 27 8 9 process 163 CHICKEN User s Manual The User s Manual 27 9 2 create symbolic link procedure create symbolic link OLDNAME NEWNAME Creates a symbolic link with the filename NEWNAME that points to the file named OLDNAME 27 9 3 read symbolic link procedure read symbolic link FILENAME Returns the filename to which the symbolic link FILENAME points 27 9 4 file link procedure file link OLDNAME NEWNAME Creates a hard link from OLDNAME to NEWNAME both strings 27 10 Retrieving user amp group information 27 10 1 current user id procedure current user id setter set current user id UID Get or set the real user id of the current process 27 10 2 current effective user id procedure current effective user id setter set current effective user id UID Get or set the effective user id of the current process 27 9 2 create symbolic link 164 CHICKEN User s Manual The User s Manual 27 10 3 user information procedure user information USER AS VECTOR If USER specifes a valid username as a string or user ID then the user database is consulted and a list of 7 values are returned the user name the encrypted password the user ID the group ID a user specific string the home directory and the default shell When AS VECTOR is t a vector of 7 elements is returned instead of a list If no user with this name or id then f is return
296. ually read the next toplevel expression from the standard input or an input file if loading from a file At the moment k was defined the next expression was k k But when k is invoked the next expression will be whatever follows after k k In other words invoking a captured continuation will not rewind the file position of the input source A solution is to wrap the whole code into a begin expression so all toplevel expressions will be loaded together 42 5 7 Why does define reader ctor not work in my compiled program The following piece of code does not work as expected eval when compile define reader ctor integer char integer gt char print integer gt char 33 The problem is that the compiler reads the complete source file before doing any processing on it so the sharp comma form is encountered before the reader ctor is defined A possible solution is to include the file containing the sharp comma form like this eval when compile define reader ctor integer char integer gt char include other file other file scm print integer gt char 33 42 5 8 Why do built in units such as srfi 1 srfi 18 and posix fail to load When you try to USe a built in unit such as Sr fi 18 you may get the following error 1 gt use srfi 18 loading library srfi 18 Error load library unable to load library jj on a Mac H image not found bjec No such file or directory d
297. value when passed as an argument to a foreign function A list of symbols passed as an argument will be combined using bi twise ior An empty list will be passed as 0 zero Results of the enum type are automatically converted into a scheme value note that combinations are not supported in this case 32 6 4 destructor 213 CHICKEN User s Manual The User s Manual TYPESPEC maybe a TYPENAME symbol or a list of the form SCHEMENAME REALTYPE DEFAULT SCHEME VALUE where REALTYPE designates the native type used The default type specification is TYPENAME TYPENAME The DEFAULT SCHEME VALUE overrides the default result of mapping from the native type i e when no such mapping exists When supplied the form is used unquoted otherwise the result is ENUMSPEC is a TYPENAME symbol or a list of the form SCHEMENAME REALTYPE SCHEME VALUE where REALTYPE designates the native type used The default enum specification is TYPENAME TYPENAME The SCHEME VALUE overrides the result of mapping from the native type When supplied the form is used unquoted otherwise the SCHEMENAME symbol is returned USE ALIASES is an optional boolean flag that determines whether an alias or the SCHEMENAME is used as the defined foreign variable name The default is 7t Additionally two procedures are defined named SCHEMENAME number and number gt SCHEMENAME SCHEMENAME number takes one argument and converts a symbol or a list of sym
298. vided See Non standard read syntax 4 Numerous non standard macros are provided See Non standard macros and special forms for more information 4 1 4 Extended DSSSL style lambda lists are supported DSSSL parameter lists are defined by the following grammar lt parameter list gt gt lt required parameter gt optional optional parameter rest lt rest parameter gt key lt keyword parameter gt lt required parameter gt gt lt ident gt lt optional parameter gt gt lt ident gt lt ident gt lt initializer gt lt rest parameter gt gt lt ident gt lt keyword parameter gt gt lt ident gt lt ident gt lt initializer gt lt initializer gt gt lt expr gt When a procedure is applied to a list of arguments the parameters and arguments are processed from left to right as follows Required parameters are bound to successive arguments starting with the first argument It shall be an error if there are fewer arguments than required parameters Next the optional parameters are bound with the remaining arguments If there are fewer arguments than optional parameters then the remaining optional parameters are bound to the result of the evaluation of their corresponding lt initializer gt if one was specified otherwise f The corresponding lt initializer gt is evaluated in an environment in which all previous parameters have been bound e If there is a rest parame
299. warnings are enabled or disabled is global and not thread local 14 10 2 error procedure error LOCATION STRING EXP Prints error message writes all extra arguments to the value of current error port and invokes the current exception handler This conforms to SREL23 If LOCATION is given and a symbol it specifies the location the name of the procedure where the error occurred 14 10 3 get call chain procedure get call chain START THREAD Returns a list with the call history Backtrace information is only generated in code compiled without no trace and evaluated code If the optional argument START is given the backtrace starts at this offset i e when START is 1 the next to last trace entry is printed and so on If the optional argument THREAD is given then the call chain will only be constructed for calls performed by this thread 14 9 3 current seconds 80 CHICKEN User s Manual The User s Manual 14 10 4 print call chain procedure print call chain PORT START THREAD Prints a backtrace of the procedure call history to PORT which defaults to current output port 14 10 5 print error message procedure print error message EXN PORT STRING Prints an appropriate error message to PORT which defaults to the value of current output port for the object EXN EXN may be a condition a string or any other object If the optional argument STRING is given it is printed before the error mess
300. x E e DEE 95 15 3 5 UNGEFIME MACTO EN 95 15 36 syntax eron EE 95 15 4 Loading extension MT E EE 95 IT KE ORTAC E OE o 95 13 A2extension Apformaton eiiean dinsin e irea esas eeie 95 1543 providers iee s R EE A A E E E E DEER EES 96 15 4 4 ele RE 96 EE LEE e 96 EE E e E E 96 1525 System Information 2 e eco ERR REFER ER ER RNRES EINE ESES EEEE ERR ER ond ananteeags saves saa EEEE EEE Sn 97 155A elite xelmHOHINECENTSEREUTTTIRLLLUU EE 97 JISE Date 1 T 97 OO kevat Ee e E AEEA EE e 97 vi CHICKEN User s Manual The User s Manual Chicken User s Manual Io Kette HORN EE eg EE E 161 2 HE EE 16 LI CR TENA EE IO Ae EE 16 1 6 EE eu HORE RE GE eelere e Wl JOU EE 1 16 43 Run VE 1 VG NMED ECHT 1 16 2 TT 1 16 2 1 Ee EE 1 16 22 MAKE EE 1 ee EE 1 l6 24 gueuelist M m 1 16 2 5 Te EE 1 16 2 6 queue empty eot oo eri ee teta ee nes dasa reete bases t EA sand renta an s aae ena eise e ERR un 1 16 27 ET EE 1 16 2 8 queue last ennei E sate PNE LIRE RAE obaeacs A EE EE VEEE NEO 1 16 2 9 TEE 1 ege Ae UE EE 1 16 2 Re TEE Ee E 1 ee Be 1 ef Gi Wert 1 l6 e EE 1 T63 DB SOMO 55s E E E AEE AEA AOE e 1 164 Random ul ER 1 16 4 1 aerer D 1 eet 1 165 Re 1 ILUBPAVHDMEM 1 16 5 3 String hoD neiaie aaia ea a EEE aE E E
301. zed expression The optional argument MODE defaults to 1 and specifies the number of the match to be substituted Any non numeric index specifies that all matches are to be substituted string substitute 0 9 eggs chicks NN or 99 chicks 2 NN Y 190 T 2 NM 99 eggs or chicks 99 V d LO D Q Hi Q Note that a regular expression that matches an empty string will signal an error 25 14 string substitute procedure string substitute STRING SMAP MODE Substitutes elements of STRING with string substitute according to SMAP SMAP should be an association list where each element of the list is a pair of the form MATCH REPLACEMENT Every occurrence of the regular expression MATCH in STRING will be replaced by the string REPLACEMENT string substitute lt hl gt Hello world h1 D A Za Z0 e 9 gt i EN gt Hello world 25 15 regexp escape procedure regexp escape STRING Escapes all special characters in STRING with so that the string can be embedded into a regular expression regexp escape 0 9 4 HNN NNTA LONN NS p VAN ENN VN H WT 4 I L F gt AAWL O S N AE a An AVAS 25 16 make anchored pattern procedure make anchored pattern REGEXP WITHOUT BOL WITHOUT EOL Makes an anchored pattern from REGEXP a string or a precompiled regular expression and returns the updated pattern When WITHOUT BOL is t the beginning of line ancho

Download Pdf Manuals

image

Related Search

Related Contents

Philips AVENT Adapter ring for feeding bottle SCF925  Wiley MacBook Pro Portable Genius, 3rd Edition  UP SP TEACH LAPROSCOPES  Philips LCD monitor with SmartControl Lite, Audio 191V2AB  HP ProLiant Moonshot Cartridge User and Maintenance Guide  TS-W1ZOOPRO  Manuel d`instructions    取扱説明書  ITSI Empathy Parent Payment Manual  

Copyright © All rights reserved.
Failed to retrieve file