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

Last change on this file since 33355 was 33355, checked in by sjamaan, 5 years ago

Update example csi banner in "Getting started" section to the one printed by 4.11.0

File size: 23.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 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 a single program
32(Emacs), and has a 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
141This chapter provides you with an overview of the entire system, with
142enough information to get started writing and running small Scheme
143programs.
144
145=== CHICKEN repositories, websites, and community
146
147The master CHICKEN website is
148[[http://www.call-cc.org]]. Here you can find
149basic information about CHICKEN, downloads, and pointers to other key
150resources.
151
152The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most
153current version of the User's manual, along with various tutorials and
154other useful documents. The list of eggs is at
155[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].
156
157A very useful search facility for questions about CHICKEN is found at
158[[http://api.call-cc.org]]. The CHICKEN issue tracker is at
159[[http://bugs.call-cc.org]].
160
161The CHICKEN community has two major mailing lists. If you are a
162CHICKEN user, {{chicken-users}}
163([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be
164of interest. The crew working on the CHICKEN system itself uses the
165very low-volume {{chicken-hackers}} list
166([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for
167communication.  For other topic-specific mailing lists (e.g.,
168announcements, security) and discussion groups, see
169[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].
170
171There is also an IRC channel ({{#chicken}}) on
172[[http://freenode.net|Freenode]].
173
174=== Installing CHICKEN
175
176CHICKEN is available as C sources. 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, a C toolchain (e.g., GCC, clang) 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 were shipped
189  on the OS X DVD with older versions of the operating system, and are
190  installable from the App Store with recent versions of the operating
191  system.
192* On Windows, you have three choices:
193** Cygwin ([[http://sourceware.org/cygwin/]]) provides a relatively
194  full-featured Unix environment for Windows.  CHICKEN works
195  substantially the same in Cygwin and Unix.
196** The GNU Compiler Collection has been ported to Windows, in the
197  MinGW system ([[http://mingw.sourceforge.net]]). Unlike Cygwin,
198  executables produced with MinGW do not need the Cygwin DLLs in order
199  to run.   MSYS is a companion package to MinGW; it provides a minimum
200  Unix-style development/build environment, again ported from free
201  software.
202*** You can build CHICKEN either with MinGW alone or with MinGW plus
203  MSYS. Both approaches produce a CHICKEN built against the mingw headers
204  and libraries.
205  The only difference is the environment where you actually run make.
206  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
207  that comes with mingw.  {{Makefile.mingw-msys}}
208  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
209  same.
210
211Refer to the {{README}} file for the version you're installing for
212more information on the installation process.
213
214Alternatively, third party packages in binary format are
215available. See
216[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]
217for information about how to obtain them.
218
219=== Development environments
220
221The simplest development environment is a text editor and terminal
222window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
223using the interpreter and/or calling the compiler.  If you install one
224of the line editing extensions (e.g., [[/egg/readline|readline]],
225[[/egg/parley|parley]], [[/egg/linenoise|linenoise]], you have some
226useful command line editing features in the interpreter (e.g., Emacs
227or vi-compatible line editing, customization).
228
229You will need a text editor that knows Scheme; it's just too painful
230with editors that don't do parenthesis matching and proper
231indentation. Some editors allow you to execute Scheme code directly in
232the editor. This makes programming very interactive: you can type in a
233function and then try it right away. This feature is very highly
234recommended.
235
236As programmers have very specific tastes about editors, the editors
237listed here are shown in alphabetic order. We aren't about to tell you
238which editor to use, and there may be editors not shown here that
239might satisfy your needs. We would be very interested in reports of
240other editors that have been used with CHICKEN, especially those that
241support interactive evaluation of forms during editing. Pointers to
242these (and to any editor customization files appropriate) should be
243put on the CHICKEN wiki, and will likely be added to future editions
244of this manual. (We have had a request for editors that support
245proportional fonts, in particular.)
246
247* Emacs ([[http://www.gnu.org/software/emacs]]) is an
248extensible, customizable, self-documenting editor available for
249Linux/Unix, Macintosh, and Windows systems; See
250[[http://wiki.call-cc.org/emacs|http://wiki.call-cc.org/emacs]]
251for more information about the available options.
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 systems.
275Vim comes with generic Lisp (and therefore Scheme) editing capabilities
276out of the box. See [[/Vim]] for a few tips on using Vim with CHICKEN.
277
278In the rest of this chapter, we'll assume that you are using an editor
279of your choice and a regular terminal window for executing your
280CHICKEN code.
281
282=== The Read-Eval-Print loop
283
284To invoke the CHICKEN interpreter, you use the {{csi}} command.
285
286
287 $ csi
288 
289 CHICKEN
290 (c) 2008-2016, The CHICKEN Team
291 (c) 2000-2007, Felix L. Winkelmann
292 Version 4.11.0 (rev ce980c4)
293 linux-unix-gnu-x86-64 [ 64bit manyargs dload ptables ]
294 compiled 2016-05-28 on yves.more-magic.net (Linux)
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]]
378at the beginning of the program.
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
411used in OS X and Windows, rather than {{dylib}} or {{dll}},
412respectively).
413
414 chicken$ csc -dynamic fact.scm
415 chicken$ csi -quiet
416 #;1> (load "fact.so")
417 ; loading fact.so ...
418 #;2> (fact 6)
419 720
420
421On any system, we can just compile a program directly into an
422executable. Here's a program that tells you whether its argument is a
423palindrome.
424
425<enscript highlight=scheme>
426(define (palindrome? x)
427  (define (check left right)
428    (if (>= left right)
429        #t
430        (and (char=? (string-ref x left) (string-ref x right))
431             (check (add1 left) (sub1 right)))))
432  (check 0 (sub1 (string-length x))))
433(let ((arg (car (command-line-arguments))))
434  (display
435   (string-append arg
436                  (if (palindrome? arg)
437                      " is a palindrome\n"
438                      " isn't a palindrome\n"))))
439</enscript>
440
441We can compile this program using {{csc}}, creating an executable
442named {{palindrome}}.
443
444 $ csc -o palindrome palindrome.scm
445 $ ./palindrome level
446 level is a palindrome
447 $ ./palindrome liver
448 liver isn't a palindrome
449
450CHICKEN supports separate compilation, using some extensions to
451Scheme. Let's divide our palindrome program into a library module
452({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
453
454Here's the external library. We {{declare}} that {{pal-proc}} is a
455''unit'', which is the basis of separately-compiled modules in
456CHICKEN. (Units deal with separate compilation, but don't necessarily
457involve separated namespaces; namespaces can be implemented by
458[[/manual/Modules|modules]].)
459
460<enscript highlight=scheme>
461;;; Library pal-proc.scm
462(declare (unit pal-proc))
463(define (palindrome? x)
464  (define (check left right)
465    (if (>= left right)
466        #t
467        (and (char=? (string-ref x left) (string-ref x right))
468             (check (add1 left) (sub1 right)))))
469  (check 0 (sub1 (string-length x))))
470</enscript>
471
472Next we have some  client code that ''uses'' this separately-compiled
473module. 
474
475<enscript highlight=scheme>
476;;; Client pal-user.scm
477(declare (uses pal-proc))
478(let ((arg (car (command-line-arguments))))
479  (display
480   (string-append arg
481                  (if (palindrome? arg)
482                      " is a palindrome\n"
483                      " isn't a palindrome\n"))))
484</enscript>
485
486Now we can compile and link everything together. (We show the compile
487and link operations separately, but they can of course be combined
488into one command.)
489
490 $ csc -c pal-proc.scm
491 $ csc -c pal-user.scm
492 $ csc -o pal-separate pal-proc.o pal-user.o
493 $ ./pal-separate level
494 level is a palindrome
495
496=== Installing an egg
497
498Installing eggs is quite straightforward on systems that support
499dynamic loading (again, that would include *BSD, Linux, Mac OS X,
500Solaris, and Windows).  The command {{chicken-install}} will fetch an
501egg from the master CHICKEN repository, and install it on your local
502system.
503
504In this example, we install the {{uri-common}} egg, for parsing
505Uniform Resource Identifiers. The installation produces a lot of
506output, which we have edited for space.
507
508 $ chicken-install uri-common
509 
510 retrieving ...
511 resolving alias `kitten-technologies' to: http://chicken.kitten-technologies.co.uk/henrietta.cgi
512 connecting to host "chicken.kitten-technologies.co.uk", port 80 ...
513 requesting "/henrietta.cgi?name=uri-common&mode=default" ...
514 reading response ...
515 [...]
516 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.scm -j uri-common
517 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.import.scm
518 cp -r uri-common.so /usr/lib/chicken/5/uri-common.so
519 chmod a+r /usr/lib/chicken/5/uri-common.so
520 cp -r uri-common.import.so /usr/lib/chicken/5/uri-common.import.so
521 chmod a+r /usr/lib/chicken/5/uri-common.import.so
522 chmod a+r /usr/lib/chicken/5/uri-common.setup-info
523
524{{chicken-install}} connects to a mirror of the egg repository and
525retrieves the egg contents.  If the egg has any uninstalled
526dependencies, it recursively installs them.  Then it builds the egg
527code and installs the resulting extension into the
528local CHICKEN repository.
529
530Now we can use our new egg.
531
532 #;1> (use uri-common)
533 ; loading /usr/lib/chicken/5/uri-common.import.so ...
534 ; [... other loaded files omitted for clarity ...]
535 
536 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
537 "www.foobar.org"
538
539=== Accessing C libraries
540
541Because CHICKEN compiles to C, and because a foreign function
542interface is built into the compiler, interfacing to a C library is
543quite straightforward. This means that nearly any facility available
544on the host system is accessible from CHICKEN, with more or less
545work.
546
547Let's create a simple C library, to demonstrate how this
548works. Here we have a function that will compute and return the '''n'''th
549Fibonacci number. (This isn't a particularly good use of C here,
550because we could write this function just as easily in Scheme, but a
551real example would take far too much space here.)
552
553 /* fib.c */
554 int fib(int n) {
555   int prev = 0, curr = 1;
556   int next;
557   int i;
558   for (i = 0; i < n; i++) {
559     next = prev + curr;
560     prev = curr;
561     curr = next;
562   }
563   return curr;
564 }
565
566Now we can call this function from CHICKEN.
567
568 ;;; fib-user.scm
569 #>
570   extern int fib(int n);
571 <#
572 (define xfib (foreign-lambda int "fib" int))
573 (do ((i 0 (+ i 1))) ((> i 10))
574   (printf "~A " (xfib i)))
575 (newline)
576
577The syntax {{#>...<#}} allows you to include literal C (typically
578external declarations) in your CHICKEN code. We access {{fib}} by
579defining a {{foreign-lambda}} for it, in this case saying that the
580function takes one integer argument (the {{int}} after the function
581name), and that it returns an integer result (the {{int}} before.) Now we can invoke
582{{xfib}} as though it were an ordinary Scheme function.
583
584 $ gcc -c fib.c
585 $ csc -o fib-user fib.o fib-user.scm
586 $ ./fib-user
587 0 1 1 2 3 5 8 13 21 34 55
588
589Those who are interfacing to substantial C libraries should consider
590using the [[/egg/bind|bind egg]].
591
592---
593
594Back to [[The User's Manual]]
595
596Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.