source: project/wiki/man/4/Getting started @ 32241

Last change on this file since 32241 was 32241, checked in by felix winkelmann, 6 years ago

removed some call/cc.org links

File size: 22.9 KB
Line 
1[[tags: manual]]
2
3== Getting started
4
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
9compilation.
10
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.
18
19=== Scheme
20
21Scheme is a member of the Lisp family of languages, of which Common
22Lisp and Emacs Lisp are the other two widely-known members. As with
23Lisp dialects, Scheme features
24
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
28
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 any one program
32(Emacs), and has a somewhat more modern language design.
33
34Scheme is defined in a document called ''The Revised^5 Report on the
35Algorithmic Language Scheme'', or ''R5RS'' for short. (Yes, it really
36has been revised five times, so an expanded version of its name would
37be ''The Revised Revised Revised Revised Revised Report''.)  A newer
38report, ''R6RS'', was
39released in 2007, but this report has attracted considerable
40controversy, and not all Scheme implementations will be made compliant
41with it. CHICKEN essentially complies with R5RS.
42
43Even though Scheme is consciously minimalist, it is recognized that a
44language must be more than a minimal core in order to be
45useful. Accordingly, the Scheme community uses a process known as
46`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
47define new language features. A typical Scheme system therefore
48complies with one of the Scheme reports plus some or all of the
49accepted SRFIs.
50
51A good starting point for Scheme knowledge is
52[[http://www.schemers.org]]. There you will find the defining reports,
53FAQs, lists of useful books and other resources, and the SRFIs.
54
55The CHICKEN community is at present developing tutorials for
56programmers who are new to Scheme but experienced with Python, Ruby,
57or other languages. These can be found on the CHICKEN wiki.
58
59=== CHICKEN
60
61CHICKEN is an implementation of Scheme that has many advantages.
62
63CHICKEN Scheme combines an optimising compiler with a reasonably fast
64interpreter.  It supports almost all of R5RS and the important SRFIs.
65The compiler generates portable C code that supports tail recursion,
66first-class continuations, and lightweight threads, and the interface to
67and from C libraries is flexible, efficient, and easy to use.  There are
68hundreds of contributed CHICKEN libraries that make the programmer's
69task easier.  The interpreter allows interactive use, fast prototyping,
70debugging, and scripting.  The active and helpful CHICKEN community
71fixes bugs and provides support.  Extensive documentation is supplied.
72
73CHICKEN was developed by Felix L. Winkelmann over the period from 2000
74through 2007. In early 2008, Felix
75asked the community to take over the responsibility of developing and
76maintaining the system, though he still takes a strong interest in it,
77and participates actively.
78
79CHICKEN includes
80
81* a Scheme interpreter that supports almost all of  R5RS Scheme, with
82  only a few relatively minor omissions, and with many extensions
83* a compatible compiler whose target is C, thus making porting to new
84  machines and architectures relatively straightforward
85** the C support allows Scheme code to include `embedded' C code,
86  thus making it relatively easy to invoke host OS or library
87  functions
88* a framework for language extensions, library modules that broaden
89  the functionality of the system
90
91This package is distributed under the '''BSD license''' and as such is free
92to use and modify.
93
94Scheme cognoscenti will appreciate the method of compilation and the
95design of the runtime-system, which follow closely Henry Baker's
96[[http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not
97CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
98number of interesting properties.
99
100* Consing (creation of data on the heap) is relatively inexpensive,
101  because a generational garbage collection scheme is used, in which
102  short-lived data structures are reclaimed extremely quickly.
103
104* Moreover, {{call-with-current-continuation}} is practically for free
105  and CHICKEN does not suffer under any performance penalties if
106  first-class continuations are used in complex ways.
107
108The generated C code is fully tail-recursive.
109
110Some of the features supported by CHICKEN:
111
112* SRFIs 0, 1, 2, 4, 6, 8-18, 23, 26, 28, 30, 31, 39, 46, 55, 61, 62, 69, 85, 88 and 98.
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* Create interpreted or compiled shell scripts written in Scheme for
119  UNIX or Windows
120* Compiled C files can be easily distributed
121* Allows the creation of fully self-contained statically linked executables
122* On systems that support it, compiled code can be loaded dynamically
123* Built-in support for cross-compilation and deployment
124
125CHICKEN has been used in many environments ranging from embedded
126systems through desktop machines to large-scale server deployments. 
127The number of language extensions, or '''eggs''', is constantly growing.
128
129* extended language features
130* development tools, such as documentation generators, debugging, and
131  automated testing libraries
132* interfaces to other languages such as Java, Python, and Objective-C
133* interfaces to database systems, GUIs, and other large-scale
134  libraries,
135* network applications, such as servers and clients for ftp,
136  smtp/pop3, irc, and http 
137* web servers and related tools, including URL parsing, HTML
138  generation, AJAX, and HTTP session management
139* data formats, including XML, JSON, and Unicode support
140
141CHICKEN is supported by SWIG (Simplified Wrapper and Interface
142Generator), a tool that produces quick-and-dirty interface modules
143for C libraries ([[http://www.swig.org]]).
144
145This chapter provides you with an overview of the entire system, with
146enough information to get started writing and running small Scheme
147programs.
148
149=== CHICKEN repositories, websites, and community
150
151The master CHICKEN website is
152[[http://www.call-cc.org]]. Here you can find
153basic information about CHICKEN, downloads, and pointers to other key
154resources.
155
156The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most
157current version of the User's manual, along with various tutorials and
158other useful documents. The list of eggs is at
159[[/egg-index]].
160
161A very useful search facility for questions about CHICKEN is found at
162[[http://api.call-cc.org]]. The CHICKEN issue tracker is at
163[[http://bugs.call-cc.org]].
164
165The CHICKEN community has two major mailing lists. If you are a
166CHICKEN user, {{chicken-users}}
167([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be
168of interest. The crew working on the CHICKEN system itself uses the
169very low-volume {{chicken-hackers}} list
170([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for
171communication. 
172
173=== Installing CHICKEN
174
175CHICKEN is [[/platforms|available]] in binary form for Windows and Linux/x86
176systems, and in source form for all other platforms. Refer to the
177{{README}} file in the distribution for instructions on installing it
178on your system.
179
180Because it compiles to C, CHICKEN requires that a C compiler be
181installed on your system. (If you're not writing embedded C code, you
182can pretty much ignore the C compiler once you have installed it.)
183
184* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be
185  installed as part of the basic operating system, or should be
186  available through the package management system (e.g., APT,
187  Synaptic, RPM, or Yum, depending upon your Linux distribution).
188* On Macintosh OS X, you will need the XCode tools, which are shipped
189  on the OS X DVD with recent versions of the operating system.
190* On Windows, you have three choices.
191** Cygwin ([[http://sourceware.org/cygwin/]]) provides a relatively
192  full-featured Unix environment for Windows.  CHICKEN works
193  substantially the same in Cygwin and Unix.
194** The GNU Compiler Collection has been ported to Windows, in the
195  MinGW system ([[http://mingw.sourceforge.net]]). Unlike Cygwin,
196  executables produced with MinGW do not need the Cygwin DLLs in order
197  to run.   MSys is a companion package to MinGW; it provides a minimum
198  Unix-style development/build environment, again ported from free
199  software.
200*** You can build CHICKEN either with MinGW alone or with MinGW plus
201  MSYS. Both approaches produce a CHICKEN built against the mingw headers
202  and import libraries.
203  The only difference is the environment where you actually run make.
204  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
205  that comes with mingw.  {{Makefile.mingw-msys}}
206  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
207  same.
208
209Refer to the {{README}} file for the version you're installing for
210more information on the installation process.
211
212Alternatively, third party packages in binary format are available.
213See [[/platforms]] for information about how to
214obtain them.
215
216=== Development environments
217
218The simplest development environment is a text editor and terminal
219window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
220using the interpreter and/or calling the compiler. If you
221[[/egg/readline|install the {{readline}} egg]], you
222have all the benefits of command history in the interpreter, Emacs or
223vi-compatible line editing, and customization.
224
225You will need a text editor that knows Scheme; it's just too painful
226with editors that don't do parenthesis matching and proper
227indentation. Some editors allow you to execute Scheme code directly in
228the editor. This makes programming very interactive: you can type in a
229function and then try it right away. This feature is very highly
230recommended.
231
232As programmers have very specific tastes about editors, the editors
233listed here are shown in alphabetic order. We aren't about to tell you
234which editor to use, and there may be editors not shown here that
235might satisfy your needs. We would be very interested in reports of
236other editors that have been used with CHICKEN, especially those that
237support interactive evaluation of forms during editing. Pointers to
238these (and to any editor customization files appropriate) should be
239put on the CHICKEN wiki, and will likely be added to future editions
240of this manual. (We have had a request for editors that support
241proportional fonts, in particular.)
242
243* Emacs ([[http://www.gnu.org/software/emacs]]) is an
244extensible, customizable, self-documenting editor available for
245Linux/Unix, Macintosh, and Windows systems; See
246[[/emacs]] for more information about the available options.
247
248* Epsilon ([[http://www.lugaru.com]]) is a commercial (proprietary) text
249editor whose design was inspired by Emacs. Although Scheme support
250isn't provided, a Lisp mode is available on Lugaru's FTP site, and
251could with some work be made to duplicate the Emacs support. 
252
253* SciTE ([[http://scintilla.sourceforge.net/SciTE.html]]),
254unlike Emacs or Vim, follows typical graphical UI design conventions
255and control-key mappings, and for simple tasks is as familiar and
256easy to use as Notepad, KEdit, TeachText etc.  However it has many
257programming features such as multiple open files, syntax
258highlighting for a large number of languages (including Lisps),
259matching of brackets, ability to fold sections of code based on the
260matched brackets, column selections, comment/uncomment, and the
261ability to run commands in the same directory as the current file
262(such as make, grep, etc.)  SciTE is written with the GTK toolkit
263and is portable to any GTK platform, including Windows, Linux and
264MacOS.  It uses the Scintilla text-editing component, which lends
265itself well to embedding within other IDEs and graphical toolkits.
266It does not have any other Scheme-specific features, but being
267open-source and modular, features like auto-formatting of
268S-expressions could be added.  The syntax highlighting can be
269configured to use different fonts for different types of syntax,
270including proportional fonts.
271
272* Vim ([[http://www.vim.org]]) is a highly configurable text
273editor built to enable efficient and fast text editing. It is an
274improved version of the vi editor distributed with most UNIX
275systems. Vim comes with generic Lisp (and therefore Scheme) editing
276capabilities out of the box. See [[/Vim]]
277for a few tips on using Vim with CHICKEN.
278
279In the rest of this chapter, we'll assume that you are using an editor
280of your choice and a regular terminal window for executing your
281CHICKEN code.
282
283=== The Read-Eval-Print loop
284
285To invoke the CHICKEN interpreter, you use the {{csi}} command.
286
287
288 $ csi
289 
290 CHICKEN
291 (c)2008-2010 The Chicken Team
292 (c)2000-2007 Felix L. Winkelmann
293 Version 4.6.0
294 macosx-unix-gnu-x86 [ manyargs dload ptables ]
295 
296 #;1>
297
298This brings up a brief banner, and then the prompt. You can use this
299pretty much like any other Scheme system, e.g.,
300
301 #;1> (define (twice f) (lambda (x) (f (f x))))
302 #;2> ((twice (lambda (n) (* n 10))) 3)
303 300
304
305Suppose  we have already created a file {{fact.scm}} containing a
306function definition.
307
308 (define (fact n)
309   (if (= n 0)
310       1
311       (* n (fact (- n 1)))))
312
313We can now load this file and try out the function.
314
315 #;3> (load "fact.scm")
316 ; loading fact.scm ...
317 #;4> (fact 3)
318 6
319
320The '''read-eval-print loop''' ('''REPL''') is the component of the
321Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
322and ''prints'' out the result. The REPL's prompt can be customized
323(see the [[Using the interpreter]])
324but the default prompt, showing the number of the form, is quite
325convenient.
326
327The REPL also supports debugging commands:
328input lines beginning with a {{,}} (comma) are treated as special
329commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
330
331
332==== Scripts
333
334You can use the interpreter to run a Scheme program from the command
335line. For the following example we create a program that does a quick
336search-and-replace on an input file; the arguments are a regular
337expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
338
339 xyzabcghi
340 abxawxcgh
341 foonly
342
343Next create the scheme code in a file called ''quickrep.scm'' with the
344following little program:
345
346<enscript highlight=scheme>
347
348(use irregex) ; irregex, the regular expression library, is one of the
349              ; libraries included with CHICKEN.
350
351(define (process-line line re rplc)
352  (irregex-replace/all re line rplc))
353
354(define (quickrep re rplc)
355  (let ((line (read-line)))
356    (if (not (eof-object? line))
357        (begin
358          (display (process-line line re rplc))
359          (newline)
360          (quickrep re rplc)))))
361
362;;; Does a lousy job of error checking!
363(define (main args)
364  (quickrep (irregex (car args)) (cadr args)))
365</enscript>
366
367
368To run it enter this in your shell:
369
370 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
371 xyzAghi
372 Agh
373 foonly
374
375The {{-ss}} option sets several options that work smoothly together to
376execute a script. You can make the command directly executable from
377the shell by inserting a `[[Using the interpreter#Writing Scheme scripts|shebang line]]' at the beginning of the
378program.
379
380The {{-ss}} option arranges to call a procedure named {{main}}, with
381the command line arguments, packed in a list, as its arguments. (There
382are a number of ways this program could be made more idiomatic CHICKEN
383Scheme, see the rest of the manual for details.)
384
385=== The compiler
386
387There are several reasons you might want to compile your code.
388
389* Compiled code executes substantially faster than interpreted
390  code.
391* You might want to deploy an application onto machines where the
392  users aren't expected to have CHICKEN installed: compiled
393  applications can be self-contained.
394
395The CHICKEN compiler is provided as the command {{chicken}}, but in
396almost all cases, you will want to use the {{csc}} command
397instead. {{csc}} is a convenient driver that automates compiling
398Scheme programs into C, compiling C code into object code, and linking
399the results into an executable file. (Note: in a Windows environment
400with Visual Studio, you may find that {{csc}} refers to Microsoft's
401C# compiler. There are a number of ways of sorting this out, of which
402the simplest is to rename one of the two tools, and/or to
403organize your {{PATH}} according to the task at hand.)
404
405Compiled code can be intermixed with interpreted code on systems that
406support dynamic loading, which includes modern versions of *BSD,
407Linux, Mac OS X, Solaris, and Windows.
408
409We can compile our factorial function, producing a file named
410{{fact.so}} (`shared object' in Linux-ese, the same file type is used
411in OS X and Windows, rather than {{dylib}} or {{dll}}, respectively).
412
413 chicken$ csc -dynamic fact.scm
414 chicken$ csi -quiet
415 #;1> (load "fact.so")
416 ; loading fact.so ...
417 #;2> (fact 6)
418 720
419
420On any system, we can just compile a program directly into an
421executable. Here's a program that tells you whether its argument is a
422palindrome.
423
424<enscript highlight=scheme>
425(define (palindrome? x)
426  (define (check left right)
427    (if (>= left right)
428        #t
429        (and (char=? (string-ref x left) (string-ref x right))
430             (check (add1 left) (sub1 right)))))
431  (check 0 (sub1 (string-length x))))
432(let ((arg (car (command-line-arguments))))
433  (display
434   (string-append arg
435                  (if (palindrome? arg)
436                      " is a palindrome\n"
437                      " isn't a palindrome\n"))))
438</enscript>
439
440We can compile this program using {{csc}}, creating an executable
441named {{palindrome}}.
442
443 $ csc -o palindrome palindrome.scm
444 $ ./palindrome level
445 level is a palindrome
446 $ ./palindrome liver
447 liver isn't a palindrome
448
449CHICKEN supports separate compilation, using some extensions to
450Scheme. Let's divide our palindrome program into a library module
451({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
452
453Here's the external library. We {{declare}} that {{pal-proc}} is a
454`unit', which is the basis of separately-compiled modules in
455CHICKEN. (Units deal with separate compilation, but don't involve
456separated namespaces; namespaced module systems are available as
457eggs.)
458
459<enscript highlight=scheme>
460;;; Library pal-proc.scm
461(declare (unit pal-proc))
462(define (palindrome? x)
463  (define (check left right)
464    (if (>= left right)
465        #t
466        (and (char=? (string-ref x left) (string-ref x right))
467             (check (add1 left) (sub1 right)))))
468  (check 0 (sub1 (string-length x))))
469</enscript>
470
471Next we have some  client code that `uses' this separately-compiled
472module. 
473
474<enscript highlight=scheme>
475;;; Client pal-user.scm
476(declare (uses pal-proc))
477(let ((arg (car (command-line-arguments))))
478  (display
479   (string-append arg
480                  (if (palindrome? arg)
481                      " is a palindrome\n"
482                      " isn't a palindrome\n"))))
483</enscript>
484
485Now we can compile and link everything together. (We show the compile
486and link operations separately, but they can of course be combined
487into one command.)
488
489 $ csc -c pal-proc.scm
490 $ csc -c pal-user.scm
491 $ csc -o pal-separate pal-proc.o pal-user.o
492 $ ./pal-separate level
493 level is a palindrome
494
495=== Installing an egg
496
497Installing eggs is quite straightforward on systems that support
498dynamic loading (again, that would include *BSD, Linux, Mac OS X,
499Solaris, and Windows).  The command {{chicken-install}} will fetch an
500egg from the master CHICKEN repository, and install it on your local
501system.
502
503In this example, we install the {{uri-common}} egg, for parsing
504Uniform Resource Identifiers. The installation produces a lot of
505output, which we have edited for space.
506
507 $ chicken-install uri-common
508 
509 retrieving ...
510 resolving alias `kitten-technologies' to: http://chicken.kitten-technologies.co.uk/henrietta.cgi
511 connecting to host "chicken.kitten-technologies.co.uk", port 80 ...
512 requesting "/henrietta.cgi?name=uri-common&mode=default" ...
513 reading response ...
514 [...]
515 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.scm -j uri-common
516 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.import.scm
517 cp -r uri-common.so /usr/lib/chicken/5/uri-common.so
518 chmod a+r /usr/lib/chicken/5/uri-common.so
519 cp -r uri-common.import.so /usr/lib/chicken/5/uri-common.import.so
520 chmod a+r /usr/lib/chicken/5/uri-common.import.so
521 chmod a+r /usr/lib/chicken/5/uri-common.setup-info
522
523{{chicken-install}} connects to a mirror of the egg repository and
524retrieves the egg contents.  If the egg has any uninstalled
525dependencies, it recursively installs them.  Then it builds the egg
526code and installs the resulting extension into the
527local CHICKEN repository.
528
529Now we can use our new egg.
530
531 #;1> (use uri-common)
532 ; loading /usr/lib/chicken/5/uri-common.import.so ...
533 ; [... other loaded files omitted for clarity ...]
534 
535 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
536 "www.foobar.org"
537
538=== Accessing C libraries
539
540Because CHICKEN compiles to C, and because a foreign function
541interface is built into the compiler, interfacing to a C library is
542quite straightforward. This means that nearly any facility available
543on the host system is accessible from CHICKEN, with more or less
544work.
545
546Let's create a simple C library, to demonstrate how this
547works. Here we have a function that will compute and return the '''n'''th
548Fibonacci number. (This isn't a particularly good use of C here,
549because we could write this function just as easily in Scheme, but a
550real example would take far too much space here.)
551
552 /* fib.c */
553 int fib(int n) {
554   int prev = 0, curr = 1;
555   int next;
556   int i;
557   for (i = 0; i < n; i++) {
558     next = prev + curr;
559     prev = curr;
560     curr = next;
561   }
562   return curr;
563 }
564
565Now we can call this function from CHICKEN.
566
567 ;;; fib-user.scm
568 #>
569   extern int fib(int n);
570 <#
571 (define xfib (foreign-lambda int "fib" int))
572 (do ((i 0 (+ i 1))) ((> i 10))
573   (printf "~A " (xfib i)))
574 (newline)
575
576The syntax {{#>...<#}} allows you to include literal C (typically
577external declarations) in your CHICKEN code. We access {{fib}} by
578defining a {{foreign-lambda}} for it, in this case saying that the
579function takes one integer argument (the {{int}} after the function
580name), and that it returns an integer result (the {{int}} before.) Now we can invoke
581{{xfib}} as though it were an ordinary Scheme function.
582
583 $ gcc -c fib.c
584 $ csc -o fib-user fib.o fib-user.scm
585 $ ./fib-user
586 0 1 1 2 3 5 8 13 21 34 55
587
588Those who are interfacing to substantial C libraries should consider
589using the [[/egg/bind|bind egg]].
590
591---
592
593Back to [[The User's Manual]]
594
595Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.