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

Last change on this file since 35527 was 35527, checked in by felix, 6 months ago

man/5: fixes in "Getting started"

File size: 19.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, 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 inexpensive,
102  because a generational garbage collection scheme is used in combination
103  with allocating on the C stack, in which short-lived data structures are reclaimed
104  extremely quickly.
105
106* Moreover, {{call-with-current-continuation}} involves only minimal
107  overhead and CHICKEN does not suffer under any performance penalties if
108  first-class continuations are used in complex ways.
109
110The generated C code fully supports tail-call optimization (TCO).
111
112Some of the features supported by CHICKEN:
113
114* Lightweight threads based on first-class continuations
115* Record structures
116* Extended comment- and string-literal syntaxes
117* Libraries for regular expressions, string handling
118* UNIX system calls and extended data structures
119* Compiled C files can be easily distributed
120* Allows the creation of fully self-contained statically linked executables
121* On systems that support it, compiled code can be loaded dynamically
122* Built-in support for cross-compilation
123
124CHICKEN has been used in many environments ranging from embedded
125systems through desktop machines to large-scale server deployments. 
126The number of language extensions, or '''eggs''', is constantly growing:
127
128* extended language features
129* development tools, such as documentation generators, debugging, and
130  automated testing libraries
131* interfaces to other languages such as Java, Python, and Objective-C
132* interfaces to database systems, GUIs, and other 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 are
188  installable from the App Store.
189* On Windows, you have three choices:
190* Cygwin ([[http://sourceware.org/cygwin/]]) provides a relatively
191  full-featured Unix environment for Windows.  CHICKEN works
192  substantially the same in Cygwin and Unix.
193* The GNU Compiler Collection has been ported to Windows, in the
194  MinGW system ([[http://mingw.sourceforge.net]]). Unlike Cygwin,
195  executables produced with MinGW do not need the Cygwin DLLs in order
196  to run.   MSYS is a companion package to MinGW; it provides a minimum
197  Unix-style development/build environment, again ported from free
198  software.
199* You can build CHICKEN either with MinGW alone or with MinGW plus
200  MSYS. Both approaches produce a CHICKEN built against the mingw headers
201  and libraries.
202  The only difference is the environment where you actually run make.
203  {{Makefile.mingw}} can be used in {{cmd.exe}} with the version of make
204  that comes with mingw.  {{Makefile.mingw-msys}}
205  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
206  same.
207
208Refer to the {{README}} file for the version you're installing for
209more information on the installation process.
210
211Alternatively, third party packages in binary format are
212available. See
213[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]
214for information about how to obtain 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 invoking the compiler.  If you install one
221of the line editing extensions (e.g., [[/egg/readline|readline]],
222[[/egg/parley|parley]], [[/egg/linenoise|linenoise]]), you have some
223useful command line editing features in the interpreter (e.g., Emacs
224or vi-compatible line editing, customization).
225
226It will be helpful to use a text editor that knows Scheme; it can be painful
227with editors that don't do parenthesis matching and automatic
228indentation.
229
230In the rest of this chapter, we'll assume that you are using an editor
231of your choice and a regular terminal window for executing your
232CHICKEN code.
233
234=== The Read-Eval-Print loop
235
236To invoke the CHICKEN interpreter, you use the {{csi}} command.
237
238 $ csi
239 CHICKEN
240 (c) 2008-2018, The CHICKEN Team
241 (c) 2000-2007, Felix L. Winkelmann
242 Version 5.0.0 (rev 6653dce)
243 linux-unix-gnu-x86-64 [ 64bit dload ptables ]
244
245 #;1>
246
247This brings up a brief banner, and then the prompt. You can use this
248pretty much like any other Scheme system, e.g.,
249
250 #;1> (define (twice f) (lambda (x) (f (f x))))
251 #;2> ((twice (lambda (n) (* n 10))) 3)
252 300
253
254Suppose  we have already created a file {{fact.scm}} containing a
255function definition.
256
257 (define (fact n)
258   (if (= n 0)
259       1
260       (* n (fact (- n 1)))))
261
262We can now load this file and try out the function.
263
264 #;3> (load "fact.scm")
265 ; loading fact.scm ...
266 #;4> (fact 3)
267 6
268
269The '''read-eval-print loop''' ('''REPL''') is the component of the
270Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
271and ''prints'' out the result. The REPL's prompt can be customized
272(see the [[Using the interpreter]])
273but the default prompt, showing the number of the form, is quite
274convenient.
275
276The REPL also supports debugging commands:
277input lines beginning with a {{,}} (comma) are treated as special
278commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
279
280
281==== Scripts
282
283You can use the interpreter to run a Scheme program from the command
284line. For the following example we create a program that does a quick
285search-and-replace on an input file; the arguments are a regular
286expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
287
288 xyzabcghi
289 abxawxcgh
290 foonly
291
292Next create the scheme code in a file called ''quickrep.scm'' with the
293following little program:
294
295<enscript highlight=scheme>
296;; irregex, the regular expression library, is one of the
297;; libraries included with CHICKEN.
298(import (chicken irregex))
299
300(define (process-line line re rplc)
301  (irregex-replace/all re line rplc))
302
303(define (quickrep re rplc)
304  (let ((line (read-line)))
305    (if (not (eof-object? line))
306        (begin
307          (display (process-line line re rplc))
308          (newline)
309          (quickrep re rplc)))))
310
311;;; Does a lousy job of error checking!
312(define (main args)
313  (quickrep (irregex (car args)) (cadr args)))
314</enscript>
315
316
317To run it enter this in your shell:
318
319 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
320 xyzAghi
321 Agh
322 foonly
323
324The {{-ss}} option sets several options that work smoothly together to
325execute a script. You can make the command directly executable from
326the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]
327at the beginning of the program.
328
329The {{-ss}} option arranges to call a procedure named {{main}}, with
330the command line arguments, packed in a list, as its arguments. (There
331are a number of ways this program could be made more idiomatic CHICKEN
332Scheme, see the rest of the manual for details.)
333
334=== The compiler
335
336There are several reasons you might want to compile your code.
337
338* Compiled code executes substantially faster than interpreted
339  code.
340* You might want to deploy an application onto machines where the
341  users aren't expected to have CHICKEN installed: compiled
342  applications can be self-contained.
343* Compiled code can access external libraries written in lower-level
344  languages that follow the C calling convention.
345
346The CHICKEN compiler is provided as the command {{chicken}}, but in
347almost all cases, you will want to use the {{csc}} command
348instead. {{csc}} is a convenient driver that automates compiling
349Scheme programs into C, compiling C code into object code, and linking
350the results into an executable file. (Note: in a Windows environment
351with Visual Studio, you may find that {{csc}} refers to Microsoft's
352C# compiler. There are a number of ways of sorting this out, of which
353the simplest is to rename one of the two tools, and/or to
354organize your {{PATH}} according to the task at hand.)
355
356We can compile our factorial function, producing a file named
357{{fact.so}} (''shared object'' in Linux-ese, the same file extension is
358used in Windows, rather than {{dll}})
359
360 chicken$ csc -shared fact.scm
361 chicken$ csi -quiet
362 #;1> (load "fact.so")
363 ; loading fact.so ...
364 #;2> (fact 6)
365 720
366
367On any system, we can just compile a program directly into an
368executable. Here's a program that tells you whether its argument is a
369palindrome.
370
371<enscript highlight=scheme>
372(import (chicken process-context)) ; for "command-line-arguments"
373
374(define (palindrome? x)
375  (define (check left right)
376    (if (>= left right)
377        #t
378        (and (char=? (string-ref x left) (string-ref x right))
379             (check (add1 left) (sub1 right)))))
380  (check 0 (sub1 (string-length x))))
381
382(let ((arg (car (command-line-arguments))))
383  (display
384   (string-append arg
385                  (if (palindrome? arg)
386                      " is a palindrome\n"
387                      " isn't a palindrome\n"))))
388</enscript>
389
390We can compile this program using {{csc}}, creating an executable
391named {{palindrome}}.
392
393 $ csc -o palindrome palindrome.scm
394 $ ./palindrome level
395 level is a palindrome
396 $ ./palindrome liver
397 liver isn't a palindrome
398
399CHICKEN supports separate compilation, using some extensions to
400Scheme. Let's divide our palindrome program into a library module
401({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
402
403Here's the external library. We {{declare}} that {{pal-proc}} is a
404''unit'', which is the basis of separately-compiled modules in
405CHICKEN. (Units deal with separate compilation, but don't necessarily
406involve separated namespaces; namespaces can be implemented by
407[[/manual/Modules|modules]].)
408
409<enscript highlight=scheme>
410;;; Library pal-proc.scm
411(declare (unit pal-proc))
412
413(define (palindrome? x)
414  (define (check left right)
415    (if (>= left right)
416        #t
417        (and (char=? (string-ref x left) (string-ref x right))
418             (check (add1 left) (sub1 right)))))
419  (check 0 (sub1 (string-length x))))
420</enscript>
421
422Next we have some  client code that ''uses'' this separately-compiled
423module. 
424
425<enscript highlight=scheme>
426;;; Client pal-user.scm
427(declare (uses pal-proc))
428
429(import (chicken process-context))
430
431(let ((arg (car (command-line-arguments))))
432  (display
433   (string-append arg
434                  (if (palindrome? arg)
435                      " is a palindrome\n"
436                      " isn't a palindrome\n"))))
437</enscript>
438
439Now we can compile and link everything together. (We show the compile
440and link operations separately, but they can of course be combined
441into one command.)
442
443 $ csc -c pal-proc.scm
444 $ csc -c pal-user.scm
445 $ csc -o pal-separate pal-proc.o pal-user.o
446 $ ./pal-separate level
447 level is a palindrome
448
449The "unit" mechanism is relatively low-level and requires some
450familiarity with underlying mechanism used to manage compilation
451units. See [[Units and linking model]] for more information.
452
453=== Installing an egg
454
455Installing eggs is quite straightforward on systems that support
456dynamic loading (that would include *BSD, Linux, Mac OS X,
457Solaris, and Windows).  The command {{chicken-install}} will fetch an
458egg from the master CHICKEN repository, and install it on your local
459system.
460
461In this example, we install the {{uri-common}} egg, for parsing
462Uniform Resource Identifiers.
463
464 $ chicken-install uri-common
465 
466{{chicken-install}} connects to a mirror of the egg repository and
467retrieves the egg contents.  If the egg has any uninstalled
468dependencies, it recursively installs them.  Then it builds the egg
469code and installs the resulting extension into the
470local CHICKEN repository.
471
472Now we can use our new egg.
473
474 #;1> (import uri-common)
475 ; loading /usr/lib/chicken/9/uri-common.import.so ...
476 ; [... other loaded files omitted for clarity ...]
477 
478 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
479 "www.foobar.org"
480
481=== Accessing C libraries
482
483Because CHICKEN compiles to C, and because a foreign function
484interface is built into the compiler, interfacing to a C library is
485quite straightforward. This means that any facility available
486on the host system is accessible from CHICKEN, with more or less
487work.
488
489Let's create a simple C library, to demonstrate how this
490works. Here we have a function that will compute and return the '''n'''th
491Fibonacci number. (This isn't a particularly good use of C here,
492because we could write this function just as easily in Scheme, but a
493real example would take far too much space here.)
494
495 /* fib.c */
496 int fib(int n) {
497   int prev = 0, curr = 1;
498   int next;
499   int i;
500   for (i = 0; i < n; i++) {
501     next = prev + curr;
502     prev = curr;
503     curr = next;
504   }
505   return curr;
506 }
507
508Now we can call this function from CHICKEN.
509
510 ;;; fib-user.scm
511 (import (chicken foreign) (chicken format))
512
513 #>
514   extern int fib(int n);
515 <#
516 (define xfib (foreign-lambda int "fib" int))
517 (do ((i 0 (+ i 1))) ((> i 10))
518   (printf "~A " (xfib i)))
519 (newline)
520
521The syntax {{#>...<#}} allows you to include literal C (typically
522external declarations) in your CHICKEN code. We access {{fib}} by
523defining a {{foreign-lambda}} for it, in this case saying that the
524function takes one integer argument (the {{int}} after the function
525name), and that it returns an integer result (the {{int}} before.) Now we can invoke
526{{xfib}} as though it were an ordinary Scheme function.
527
528 $ gcc -c fib.c
529 $ csc -o fib-user fib.o fib-user.scm
530 $ ./fib-user
531 0 1 1 2 3 5 8 13 21 34 55
532
533Those who are interfacing to substantial C libraries should consider
534using the [[/egg/bind|bind egg]].
535
536---
537
538Back to [[The User's Manual]]
539
540Next: [[Using the interpreter]]
Note: See TracBrowser for help on using the repository browser.