source: project/wiki/man/5/Getting started @ 35525

Last change on this file since 35525 was 35525, checked in by felix, 7 weeks ago

man/5: restructuring, fixed links, added csi module, simplification

File size: 20.1 KB
1[[tags: manual]]
3== Getting started
5CHICKEN is a compiler that translates Scheme source files into
6C, which in turn can be fed to a C compiler to generate a
7standalone executable.  An interpreter is also available and can be
8used as a scripting environment or for testing programs before
11This chapter is designed to get you started with CHICKEN programming,
12describing what it is and what it will do for you, and covering basic
13use of the system. With almost everything discussed here, there is
14more to the story, which the remainder of the manual reveals. Here, we
15only cover enough to get you started. Nonetheless, someone who knows
16Scheme already should be able to use this chapter as the basis for
17writing and running small CHICKEN programs.
19=== Scheme
21Scheme is a member of the Lisp family of languages, of which Common
22Lisp, Emacs Lisp and Clojure are other widely-known members. As with
23Lisp dialects, Scheme features
25* a wide variety of programming paradigms, including imperative, functional, and object-oriented
26* a very simple syntax, based upon nested parenthesization
27* the ability to extend the language in meaningful and useful ways
29In contrast to Common Lisp, Scheme is very minimal, and tries to
30include only those features absolutely necessary in programming. In
31contrast to Emacs Lisp, Scheme is not anchored into a single program
32(Emacs), and has a more modern and elegant language design. In contrast
33to Clojure, Scheme provides only a very minimal set of concepts but allows
34them to be used in very general ways with few restrictions.
36Scheme is defined in a document called ''The Revised^5 Report on the
37Algorithmic Language Scheme'', or ''R5RS'' for short. (Yes, it really
38has been revised five times, so an expanded version of its name would
39be ''The Revised Revised Revised Revised Revised Report''.)  A newer
40report, ''R6RS'', was
41released in 2007, but this report has attracted considerable
42controversy, and a number of Scheme implementations have chosen
43not to be compliant
44with it. Yet another report was released in 2013 ("R7RS"), that was
45less ambitious than R6RS and more minimal.
47CHICKEN fully complies with R5RS and, by using a separately available
48extension also with the "R7RS small" language.
50Even though Scheme is consciously minimalist, it is recognized that a
51language must be more than a minimal core in order to be
52useful. Accordingly, the Scheme community uses a process known as
53`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
54define new language features. A typical Scheme system therefore
55complies with one of the Scheme reports plus some or all of the
56accepted SRFIs.
58A good starting point for Scheme knowledge is
59[[]]. There you will find the defining reports,
60FAQs, lists of useful books and other resources, and the SRFIs.
64CHICKEN Scheme combines an optimising compiler with a reasonably fast
65interpreter.  It supports almost all of R7RS and the important SRFIs.
66The compiler generates portable C code that supports tail recursion,
67first-class continuations and lightweight threads, and the interface to
68and from C libraries is flexible, efficient, and easy to use.  There are
69hundreds of contributed CHICKEN libraries that make the programmer's
70task easier.  The interpreter allows interactive use, fast prototyping,
71debugging, and scripting.  The active and helpful CHICKEN community
72fixes bugs and provides support.  Extensive documentation is supplied.
74CHICKEN was developed by Felix L. Winkelmann over the period from 2000
75through 2007. In early 2008, Felix
76asked the community to take over the responsibility of developing and
77maintaining the system, though he still takes a strong interest in it,
78and participates actively.
80CHICKEN includes
82* a Scheme interpreter that supports all of R5(7)RS Scheme, with
83  only a few relatively minor omissions, and with many extensions
84* a compatible compiler whose target is C, thus making porting to new
85  machines and architectures relatively straightforward
86** the C support allows Scheme code to include `embedded' C code,
87  thus making it easyto invoke host OS or library
88  functions
89* a framework for language extensions, library modules that broaden
90  the functionality of the system
92This package is distributed under the '''BSD license''' and as such is free
93to use and modify as long as the original authors are acknowledged.
95Scheme cognoscenti will appreciate the method of compilation and the
96design of the runtime-system, which follow closely Henry Baker's
97[[|CONS Should Not
98CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
99number of interesting properties.
101* Consing (creation of data on the heap) is relatively inexpensive,
102  because a generational garbage collection scheme is used in which
103  short-lived data structures are reclaimed extremely quickly.
105* Moreover, {{call-with-current-continuation}} is practically for free
106  and CHICKEN does not suffer under any performance penalties if
107  first-class continuations are used in complex ways.
109The generated C code fully supports tail-call optimization (TCO.)
111Some of the features supported by CHICKEN:
113* Lightweight threads based on first-class continuations
114* Record structures
115* Extended comment- and string-literal syntaxes
116* Libraries for regular expressions, string handling
117* UNIX system calls and extended data structures
118* Compiled C files can be easily distributed
119* Allows the creation of fully self-contained statically linked executables
120* On systems that support it, compiled code can be loaded dynamically
121* Built-in support for cross-compilation
123CHICKEN has been used in many environments ranging from embedded
124systems through desktop machines to large-scale server deployments. 
125The number of language extensions, or '''eggs''', is constantly growing:
127* extended language features
128* development tools, such as documentation generators, debugging, and
129  automated testing libraries
130* interfaces to other languages such as Java, Python, and Objective-C
131* interfaces to database systems, GUIs, and other large-scale
132  libraries,
133* network applications, such as servers and clients for ftp,
134  smtp/pop3, irc, and http 
135* web servers and related tools, including URL parsing, HTML
136  generation, AJAX, and HTTP session management
137* data formats, including XML, JSON, and Unicode support
139This chapter provides you with an overview of the entire system, with
140enough information to get started writing and running small Scheme
143=== CHICKEN repositories, websites and community
145The master CHICKEN website is
146[[]]. Here you can find
147basic information about CHICKEN, downloads and pointers to other key
150The CHICKEN wiki ([[]]) contains the most
151current version of the User's manual, along with various tutorials and
152other useful documents. The list of eggs is at
155A very useful search facility for questions about procedures and syntax
156available for CHICKEN can be found at
157[[]]. The CHICKEN issue tracker is at
160The CHICKEN community has two major mailing lists. If you are a
161CHICKEN user, {{chicken-users}}
162([[]]) will be
163of interest. The crew working on the CHICKEN system itself uses the
164very low-volume {{chicken-hackers}} list
165([[]]) for
166communication.  For other topic-specific mailing lists (e.g.,
167announcements, security) and discussion groups, see
170There is also an IRC channel ({{#chicken}}) on
173=== Installing CHICKEN
175CHICKEN is available as C sources. Refer to the
176{{README}} file in the distribution for instructions on installing it
177on your system.
179Because it compiles to C, CHICKEN requires that a C compiler be
180installed on your system. (If you're not writing embedded C code, you
181can pretty much ignore the C compiler once you have installed it.)
183* On a Linux system, a C toolchain (e.g., GCC, clang) should be
184  installed as part of the basic operating system, or should be
185  available through the package management system (e.g., APT,
186  Synaptic, RPM, or Yum, depending upon your Linux distribution).
187* On Macintosh OS X, you will need the XCode tools, which were shipped
188  on the OS X DVD with older versions of the operating system, and are
189  installable from the App Store with recent versions of the operating
190  system.
191* On Windows, you have three choices:
192** Cygwin ([[]]) provides a relatively
193  full-featured Unix environment for Windows.  CHICKEN works
194  substantially the same in Cygwin and Unix.
195** The GNU Compiler Collection has been ported to Windows, in the
196  MinGW system ([[]]). Unlike Cygwin,
197  executables produced with MinGW do not need the Cygwin DLLs in order
198  to run.   MSYS is a companion package to MinGW; it provides a minimum
199  Unix-style development/build environment, again ported from free
200  software.
201*** You can build CHICKEN either with MinGW alone or with MinGW plus
202  MSYS. Both approaches produce a CHICKEN built against the mingw headers
203  and libraries.
204  The only difference is the environment where you actually run make.
205  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
206  that comes with mingw.  {{Makefile.mingw-msys}}
207  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
208  same.
210Refer to the {{README}} file for the version you're installing for
211more information on the installation process.
213Alternatively, third party packages in binary format are
214available. See
216for information about how to obtain them.
218=== Development environments
220The simplest development environment is a text editor and terminal
221window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
222using the interpreter and/or calling the compiler.  If you install one
223of the line editing extensions (e.g., [[/egg/readline|readline]],
224[[/egg/parley|parley]], [[/egg/linenoise|linenoise]]), you have some
225useful command line editing features in the interpreter (e.g., Emacs
226or vi-compatible line editing, customization).
228It will be helpful to use a text editor that knows Scheme; it can be painful
229with editors that don't do parenthesis matching and proper
232In the rest of this chapter, we'll assume that you are using an editor
233of your choice and a regular terminal window for executing your
234CHICKEN code.
236=== The Read-Eval-Print loop
238To invoke the CHICKEN interpreter, you use the {{csi}} command.
241 $ csi
243(c) 2008-2018, The CHICKEN Team
244(c) 2000-2007, Felix L. Winkelmann
245Version 5.0.0 (rev 6653dce)
246linux-unix-gnu-x86-64 [ 64bit dload ptables ]
248 #;1>
250This brings up a brief banner, and then the prompt. You can use this
251pretty much like any other Scheme system, e.g.,
253 #;1> (define (twice f) (lambda (x) (f (f x))))
254 #;2> ((twice (lambda (n) (* n 10))) 3)
255 300
257Suppose  we have already created a file {{fact.scm}} containing a
258function definition.
260 (define (fact n)
261   (if (= n 0)
262       1
263       (* n (fact (- n 1)))))
265We can now load this file and try out the function.
267 #;3> (load "fact.scm")
268 ; loading fact.scm ...
269 #;4> (fact 3)
270 6
272The '''read-eval-print loop''' ('''REPL''') is the component of the
273Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
274and ''prints'' out the result. The REPL's prompt can be customized
275(see the [[Using the interpreter]])
276but the default prompt, showing the number of the form, is quite
279The REPL also supports debugging commands:
280input lines beginning with a {{,}} (comma) are treated as special
281commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
284==== Scripts
286You can use the interpreter to run a Scheme program from the command
287line. For the following example we create a program that does a quick
288search-and-replace on an input file; the arguments are a regular
289expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
291 xyzabcghi
292 abxawxcgh
293 foonly
295Next create the scheme code in a file called ''quickrep.scm'' with the
296following little program:
298<enscript highlight=scheme>
299;; irregex, the regular expression library, is one of the
300;; libraries included with CHICKEN.
301(import (chicken irregex))
303(define (process-line line re rplc)
304  (irregex-replace/all re line rplc))
306(define (quickrep re rplc)
307  (let ((line (read-line)))
308    (if (not (eof-object? line))
309        (begin
310          (display (process-line line re rplc))
311          (newline)
312          (quickrep re rplc)))))
314;;; Does a lousy job of error checking!
315(define (main args)
316  (quickrep (irregex (car args)) (cadr args)))
320To run it enter this in your shell:
322 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
323 xyzAghi
324 Agh
325 foonly
327The {{-ss}} option sets several options that work smoothly together to
328execute a script. You can make the command directly executable from
329the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]
330at the beginning of the program.
332The {{-ss}} option arranges to call a procedure named {{main}}, with
333the command line arguments, packed in a list, as its arguments. (There
334are a number of ways this program could be made more idiomatic CHICKEN
335Scheme, see the rest of the manual for details.)
337=== The compiler
339There are several reasons you might want to compile your code.
341* Compiled code executes substantially faster than interpreted
342  code.
343* You might want to deploy an application onto machines where the
344  users aren't expected to have CHICKEN installed: compiled
345  applications can be self-contained.
346* Compiled code can access external libraries written in lower-level
347  languages that follow the C calling convention.
349The CHICKEN compiler is provided as the command {{chicken}}, but in
350almost all cases, you will want to use the {{csc}} command
351instead. {{csc}} is a convenient driver that automates compiling
352Scheme programs into C, compiling C code into object code, and linking
353the results into an executable file. (Note: in a Windows environment
354with Visual Studio, you may find that {{csc}} refers to Microsoft's
355C# compiler. There are a number of ways of sorting this out, of which
356the simplest is to rename one of the two tools, and/or to
357organize your {{PATH}} according to the task at hand.)
359Compiled code can be intermixed with interpreted code on systems that
360support dynamic loading, which includes modern versions of *BSD,
361Linux, Mac OS X, Solaris, and Windows.
363We can compile our factorial function, producing a file named
364{{}} (''shared object'' in Linux-ese, the same file extension is
365used in Windows, rather than {{dll}})
367 chicken$ csc -shared fact.scm
368 chicken$ csi -quiet
369 #;1> (load "")
370 ; loading ...
371 #;2> (fact 6)
372 720
374On any system, we can just compile a program directly into an
375executable. Here's a program that tells you whether its argument is a
378<enscript highlight=scheme>
379(import (chicken process-context)) ; for "command-line-arguments"
381(define (palindrome? x)
382  (define (check left right)
383    (if (>= left right)
384        #t
385        (and (char=? (string-ref x left) (string-ref x right))
386             (check (add1 left) (sub1 right)))))
387  (check 0 (sub1 (string-length x))))
389(let ((arg (car (command-line-arguments))))
390  (display
391   (string-append arg
392                  (if (palindrome? arg)
393                      " is a palindrome\n"
394                      " isn't a palindrome\n"))))
397We can compile this program using {{csc}}, creating an executable
398named {{palindrome}}.
400 $ csc -o palindrome palindrome.scm
401 $ ./palindrome level
402 level is a palindrome
403 $ ./palindrome liver
404 liver isn't a palindrome
406CHICKEN supports separate compilation, using some extensions to
407Scheme. Let's divide our palindrome program into a library module
408({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
410Here's the external library. We {{declare}} that {{pal-proc}} is a
411''unit'', which is the basis of separately-compiled modules in
412CHICKEN. (Units deal with separate compilation, but don't necessarily
413involve separated namespaces; namespaces can be implemented by
416<enscript highlight=scheme>
417;;; Library pal-proc.scm
418(declare (unit pal-proc))
420(define (palindrome? x)
421  (define (check left right)
422    (if (>= left right)
423        #t
424        (and (char=? (string-ref x left) (string-ref x right))
425             (check (add1 left) (sub1 right)))))
426  (check 0 (sub1 (string-length x))))
429Next we have some  client code that ''uses'' this separately-compiled
432<enscript highlight=scheme>
433;;; Client pal-user.scm
434(declare (uses pal-proc))
436(import (chicken process-context))
438(let ((arg (car (command-line-arguments))))
439  (display
440   (string-append arg
441                  (if (palindrome? arg)
442                      " is a palindrome\n"
443                      " isn't a palindrome\n"))))
446Now we can compile and link everything together. (We show the compile
447and link operations separately, but they can of course be combined
448into one command.)
450 $ csc -c pal-proc.scm
451 $ csc -c pal-user.scm
452 $ csc -o pal-separate pal-proc.o pal-user.o
453 $ ./pal-separate level
454 level is a palindrome
456The "unit" mechanism is relatively low-level and requires some
457familiarity with underlying mechanism used to manage compilation
458units. See [[Units and linking model]] for more information.
460=== Installing an egg
462Installing eggs is quite straightforward on systems that support
463dynamic loading (again, that would include *BSD, Linux, Mac OS X,
464Solaris, and Windows).  The command {{chicken-install}} will fetch an
465egg from the master CHICKEN repository, and install it on your local
468In this example, we install the {{uri-common}} egg, for parsing
469Uniform Resource Identifiers.
471 $ chicken-install uri-common
473{{chicken-install}} connects to a mirror of the egg repository and
474retrieves the egg contents.  If the egg has any uninstalled
475dependencies, it recursively installs them.  Then it builds the egg
476code and installs the resulting extension into the
477local CHICKEN repository.
479Now we can use our new egg.
481 #;1> (import uri-common)
482 ; loading /usr/lib/chicken/9/ ...
483 ; [... other loaded files omitted for clarity ...]
485 #;2> (uri-host (uri-reference ""))
486 ""
488=== Accessing C libraries
490Because CHICKEN compiles to C, and because a foreign function
491interface is built into the compiler, interfacing to a C library is
492quite straightforward. This means that any facility available
493on the host system is accessible from CHICKEN, with more or less
496Let's create a simple C library, to demonstrate how this
497works. Here we have a function that will compute and return the '''n'''th
498Fibonacci number. (This isn't a particularly good use of C here,
499because we could write this function just as easily in Scheme, but a
500real example would take far too much space here.)
502 /* fib.c */
503 int fib(int n) {
504   int prev = 0, curr = 1;
505   int next;
506   int i;
507   for (i = 0; i < n; i++) {
508     next = prev + curr;
509     prev = curr;
510     curr = next;
511   }
512   return curr;
513 }
515Now we can call this function from CHICKEN.
517 ;;; fib-user.scm
518 (import (chicken format))
520 #>
521   extern int fib(int n);
522 <#
523 (define xfib (foreign-lambda int "fib" int))
524 (do ((i 0 (+ i 1))) ((> i 10))
525   (printf "~A " (xfib i)))
526 (newline)
528The syntax {{#>...<#}} allows you to include literal C (typically
529external declarations) in your CHICKEN code. We access {{fib}} by
530defining a {{foreign-lambda}} for it, in this case saying that the
531function takes one integer argument (the {{int}} after the function
532name), and that it returns an integer result (the {{int}} before.) Now we can invoke
533{{xfib}} as though it were an ordinary Scheme function.
535 $ gcc -c fib.c
536 $ csc -o fib-user fib.o fib-user.scm
537 $ ./fib-user
538 0 1 1 2 3 5 8 13 21 34 55
540Those who are interfacing to substantial C libraries should consider
541using the [[/egg/bind|bind egg]].
545Back to [[The User's Manual]]
547Next: [[Using the interpreter]]
Note: See TracBrowser for help on using the repository browser.