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

Last change on this file since 35525 was 35525, checked in by felix, 5 months ago

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

File size: 20.1 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, Emacs Lisp and Clojure are other 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 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.
35
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.
46
47CHICKEN fully complies with R5RS and, by using a separately available
48extension also with the "R7RS small" language.
49
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.
57
58A good starting point for Scheme knowledge is
59[[http://www.schemers.org]]. There you will find the defining reports,
60FAQs, lists of useful books and other resources, and the SRFIs.
61
62=== CHICKEN
63
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.
73
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.
79
80CHICKEN includes
81
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
91
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.
94
95Scheme cognoscenti will appreciate the method of compilation and the
96design of the runtime-system, which follow closely Henry Baker's
97[[http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not
98CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
99number of interesting properties.
100
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.
104
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.
108
109The generated C code fully supports tail-call optimization (TCO.)
110
111Some of the features supported by CHICKEN:
112
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
122
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:
126
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
138
139This chapter provides you with an overview of the entire system, with
140enough information to get started writing and running small Scheme
141programs.
142
143=== CHICKEN repositories, websites and community
144
145The master CHICKEN website is
146[[http://www.call-cc.org]]. Here you can find
147basic information about CHICKEN, downloads and pointers to other key
148resources.
149
150The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most
151current version of the User's manual, along with various tutorials and
152other useful documents. The list of eggs is at
153[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].
154
155A very useful search facility for questions about procedures and syntax
156available for CHICKEN can be found at
157[[http://api.call-cc.org]]. The CHICKEN issue tracker is at
158[[http://bugs.call-cc.org]].
159
160The CHICKEN community has two major mailing lists. If you are a
161CHICKEN user, {{chicken-users}}
162([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be
163of interest. The crew working on the CHICKEN system itself uses the
164very low-volume {{chicken-hackers}} list
165([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for
166communication.  For other topic-specific mailing lists (e.g.,
167announcements, security) and discussion groups, see
168[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].
169
170There is also an IRC channel ({{#chicken}}) on
171[[http://freenode.net|Freenode]].
172
173=== Installing CHICKEN
174
175CHICKEN is available as C sources. Refer to the
176{{README}} file in the distribution for instructions on installing it
177on your system.
178
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.)
182
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 ([[http://sourceware.org/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 ([[http://mingw.sourceforge.net]]). 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.
209
210Refer to the {{README}} file for the version you're installing for
211more information on the installation process.
212
213Alternatively, third party packages in binary format are
214available. See
215[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]
216for information about how to obtain them.
217
218=== Development environments
219
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).
227
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
230indentation.
231
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.
235
236=== The Read-Eval-Print loop
237
238To invoke the CHICKEN interpreter, you use the {{csi}} command.
239
240
241 $ csi
242 CHICKEN
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 ]
247
248 #;1>
249
250This brings up a brief banner, and then the prompt. You can use this
251pretty much like any other Scheme system, e.g.,
252
253 #;1> (define (twice f) (lambda (x) (f (f x))))
254 #;2> ((twice (lambda (n) (* n 10))) 3)
255 300
256
257Suppose  we have already created a file {{fact.scm}} containing a
258function definition.
259
260 (define (fact n)
261   (if (= n 0)
262       1
263       (* n (fact (- n 1)))))
264
265We can now load this file and try out the function.
266
267 #;3> (load "fact.scm")
268 ; loading fact.scm ...
269 #;4> (fact 3)
270 6
271
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
277convenient.
278
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]].)
282
283
284==== Scripts
285
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:
290
291 xyzabcghi
292 abxawxcgh
293 foonly
294
295Next create the scheme code in a file called ''quickrep.scm'' with the
296following little program:
297
298<enscript highlight=scheme>
299;; irregex, the regular expression library, is one of the
300;; libraries included with CHICKEN.
301(import (chicken irregex))
302
303(define (process-line line re rplc)
304  (irregex-replace/all re line rplc))
305
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)))))
313
314;;; Does a lousy job of error checking!
315(define (main args)
316  (quickrep (irregex (car args)) (cadr args)))
317</enscript>
318
319
320To run it enter this in your shell:
321
322 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
323 xyzAghi
324 Agh
325 foonly
326
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.
331
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.)
336
337=== The compiler
338
339There are several reasons you might want to compile your code.
340
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.
348
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.)
358
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.
362
363We can compile our factorial function, producing a file named
364{{fact.so}} (''shared object'' in Linux-ese, the same file extension is
365used in Windows, rather than {{dll}})
366
367 chicken$ csc -shared fact.scm
368 chicken$ csi -quiet
369 #;1> (load "fact.so")
370 ; loading fact.so ...
371 #;2> (fact 6)
372 720
373
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
376palindrome.
377
378<enscript highlight=scheme>
379(import (chicken process-context)) ; for "command-line-arguments"
380
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))))
388
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"))))
395</enscript>
396
397We can compile this program using {{csc}}, creating an executable
398named {{palindrome}}.
399
400 $ csc -o palindrome palindrome.scm
401 $ ./palindrome level
402 level is a palindrome
403 $ ./palindrome liver
404 liver isn't a palindrome
405
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}}).
409
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
414[[/manual/Modules|modules]].)
415
416<enscript highlight=scheme>
417;;; Library pal-proc.scm
418(declare (unit pal-proc))
419
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))))
427</enscript>
428
429Next we have some  client code that ''uses'' this separately-compiled
430module. 
431
432<enscript highlight=scheme>
433;;; Client pal-user.scm
434(declare (uses pal-proc))
435
436(import (chicken process-context))
437
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"))))
444</enscript>
445
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.)
449
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
455
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.
459
460=== Installing an egg
461
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
466system.
467
468In this example, we install the {{uri-common}} egg, for parsing
469Uniform Resource Identifiers.
470
471 $ chicken-install uri-common
472 
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.
478
479Now we can use our new egg.
480
481 #;1> (import uri-common)
482 ; loading /usr/lib/chicken/9/uri-common.import.so ...
483 ; [... other loaded files omitted for clarity ...]
484 
485 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
486 "www.foobar.org"
487
488=== Accessing C libraries
489
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
494work.
495
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.)
501
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 }
514
515Now we can call this function from CHICKEN.
516
517 ;;; fib-user.scm
518 (import (chicken format))
519
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)
527
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.
534
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
539
540Those who are interfacing to substantial C libraries should consider
541using the [[/egg/bind|bind egg]].
542
543---
544
545Back to [[The User's Manual]]
546
547Next: [[Using the interpreter]]
Note: See TracBrowser for help on using the repository browser.