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

Last change on this file since 33157 was 33157, checked in by anonymous, 5 years ago

revert spam

File size: 23.0 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
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[[/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 [[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
228You will need a text editor that knows Scheme; it's just too painful
229with editors that don't do parenthesis matching and proper
230indentation. Some editors allow you to execute Scheme code directly in
231the editor. This makes programming very interactive: you can type in a
232function and then try it right away. This feature is very highly
233recommended.
234
235As programmers have very specific tastes about editors, the editors
236listed here are shown in alphabetic order. We aren't about to tell you
237which editor to use, and there may be editors not shown here that
238might satisfy your needs. We would be very interested in reports of
239other editors that have been used with CHICKEN, especially those that
240support interactive evaluation of forms during editing. Pointers to
241these (and to any editor customization files appropriate) should be
242put on the CHICKEN wiki, and will likely be added to future editions
243of this manual. (We have had a request for editors that support
244proportional fonts, in particular.)
245
246* Emacs ([[http://www.gnu.org/software/emacs]]) is an
247extensible, customizable, self-documenting editor available for
248Linux/Unix, Macintosh, and Windows systems; See
249[[/emacs]] for more information about the available options.
250
251* SciTE ([[http://scintilla.sourceforge.net/SciTE.html]]),
252unlike Emacs or Vim, follows typical graphical UI design conventions
253and control-key mappings, and for simple tasks is as familiar and
254easy to use as Notepad, KEdit, TeachText etc.  However it has many
255programming features such as multiple open files, syntax
256highlighting for a large number of languages (including Lisps),
257matching of brackets, ability to fold sections of code based on the
258matched brackets, column selections, comment/uncomment, and the
259ability to run commands in the same directory as the current file
260(such as make, grep, etc.)  SciTE is written with the GTK toolkit
261and is portable to any GTK platform, including Windows, Linux and
262MacOS.  It uses the Scintilla text-editing component, which lends
263itself well to embedding within other IDEs and graphical toolkits.
264It does not have any other Scheme-specific features, but being
265open-source and modular, features like auto-formatting of
266S-expressions could be added.  The syntax highlighting can be
267configured to use different fonts for different types of syntax,
268including proportional fonts.
269
270* Vim ([[http://www.vim.org]]) is a highly configurable text
271editor built to enable efficient and fast text editing. It is an
272improved version of the vi editor distributed with most UNIX systems.
273Vim comes with generic Lisp (and therefore Scheme) editing capabilities
274out of the box. See [[/Vim]] for a few tips on using Vim with CHICKEN.
275
276In the rest of this chapter, we'll assume that you are using an editor
277of your choice and a regular terminal window for executing your
278CHICKEN code.
279
280=== The Read-Eval-Print loop
281
282To invoke the CHICKEN interpreter, you use the {{csi}} command.
283
284
285 $ csi
286 
287 CHICKEN
288 (c) 2008-2015, The CHICKEN Team
289 (c) 2000-2007, Felix L. Winkelmann
290 Version 4.9.0.1 (stability/4.9.0) (rev 8b3189b)
291 linux-unix-gnu-x86-64 [ 64bit manyargs dload ptables ]
292 bootstrapped 2014-06-07
293 
294 #;1>
295
296This brings up a brief banner, and then the prompt. You can use this
297pretty much like any other Scheme system, e.g.,
298
299 #;1> (define (twice f) (lambda (x) (f (f x))))
300 #;2> ((twice (lambda (n) (* n 10))) 3)
301 300
302
303Suppose  we have already created a file {{fact.scm}} containing a
304function definition.
305
306 (define (fact n)
307   (if (= n 0)
308       1
309       (* n (fact (- n 1)))))
310
311We can now load this file and try out the function.
312
313 #;3> (load "fact.scm")
314 ; loading fact.scm ...
315 #;4> (fact 3)
316 6
317
318The '''read-eval-print loop''' ('''REPL''') is the component of the
319Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
320and ''prints'' out the result. The REPL's prompt can be customized
321(see the [[Using the interpreter]])
322but the default prompt, showing the number of the form, is quite
323convenient.
324
325The REPL also supports debugging commands:
326input lines beginning with a {{,}} (comma) are treated as special
327commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
328
329
330==== Scripts
331
332You can use the interpreter to run a Scheme program from the command
333line. For the following example we create a program that does a quick
334search-and-replace on an input file; the arguments are a regular
335expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
336
337 xyzabcghi
338 abxawxcgh
339 foonly
340
341Next create the scheme code in a file called ''quickrep.scm'' with the
342following little program:
343
344<enscript highlight=scheme>
345
346(use irregex) ; irregex, the regular expression library, is one of the
347              ; libraries included with CHICKEN.
348
349(define (process-line line re rplc)
350  (irregex-replace/all re line rplc))
351
352(define (quickrep re rplc)
353  (let ((line (read-line)))
354    (if (not (eof-object? line))
355        (begin
356          (display (process-line line re rplc))
357          (newline)
358          (quickrep re rplc)))))
359
360;;; Does a lousy job of error checking!
361(define (main args)
362  (quickrep (irregex (car args)) (cadr args)))
363</enscript>
364
365
366To run it enter this in your shell:
367
368 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
369 xyzAghi
370 Agh
371 foonly
372
373The {{-ss}} option sets several options that work smoothly together to
374execute a script. You can make the command directly executable from
375the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]
376at the beginning of the program.
377
378The {{-ss}} option arranges to call a procedure named {{main}}, with
379the command line arguments, packed in a list, as its arguments. (There
380are a number of ways this program could be made more idiomatic CHICKEN
381Scheme, see the rest of the manual for details.)
382
383=== The compiler
384
385There are several reasons you might want to compile your code.
386
387* Compiled code executes substantially faster than interpreted
388  code.
389* You might want to deploy an application onto machines where the
390  users aren't expected to have CHICKEN installed: compiled
391  applications can be self-contained.
392
393The CHICKEN compiler is provided as the command {{chicken}}, but in
394almost all cases, you will want to use the {{csc}} command
395instead. {{csc}} is a convenient driver that automates compiling
396Scheme programs into C, compiling C code into object code, and linking
397the results into an executable file. (Note: in a Windows environment
398with Visual Studio, you may find that {{csc}} refers to Microsoft's
399C# compiler. There are a number of ways of sorting this out, of which
400the simplest is to rename one of the two tools, and/or to
401organize your {{PATH}} according to the task at hand.)
402
403Compiled code can be intermixed with interpreted code on systems that
404support dynamic loading, which includes modern versions of *BSD,
405Linux, Mac OS X, Solaris, and Windows.
406
407We can compile our factorial function, producing a file named
408{{fact.so}} (''shared object'' in Linux-ese, the same file type is
409used in OS X and Windows, rather than {{dylib}} or {{dll}},
410respectively).
411
412 chicken$ csc -dynamic fact.scm
413 chicken$ csi -quiet
414 #;1> (load "fact.so")
415 ; loading fact.so ...
416 #;2> (fact 6)
417 720
418
419On any system, we can just compile a program directly into an
420executable. Here's a program that tells you whether its argument is a
421palindrome.
422
423<enscript highlight=scheme>
424(define (palindrome? x)
425  (define (check left right)
426    (if (>= left right)
427        #t
428        (and (char=? (string-ref x left) (string-ref x right))
429             (check (add1 left) (sub1 right)))))
430  (check 0 (sub1 (string-length x))))
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
439We can compile this program using {{csc}}, creating an executable
440named {{palindrome}}.
441
442 $ csc -o palindrome palindrome.scm
443 $ ./palindrome level
444 level is a palindrome
445 $ ./palindrome liver
446 liver isn't a palindrome
447
448CHICKEN supports separate compilation, using some extensions to
449Scheme. Let's divide our palindrome program into a library module
450({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
451
452Here's the external library. We {{declare}} that {{pal-proc}} is a
453''unit'', which is the basis of separately-compiled modules in
454CHICKEN. (Units deal with separate compilation, but don't necessarily
455involve separated namespaces; namespaces can be implemented by
456[[/manual/Modules|modules]].)
457
458<enscript highlight=scheme>
459;;; Library pal-proc.scm
460(declare (unit pal-proc))
461(define (palindrome? x)
462  (define (check left right)
463    (if (>= left right)
464        #t
465        (and (char=? (string-ref x left) (string-ref x right))
466             (check (add1 left) (sub1 right)))))
467  (check 0 (sub1 (string-length x))))
468</enscript>
469
470Next we have some  client code that ''uses'' this separately-compiled
471module. 
472
473<enscript highlight=scheme>
474;;; Client pal-user.scm
475(declare (uses pal-proc))
476(let ((arg (car (command-line-arguments))))
477  (display
478   (string-append arg
479                  (if (palindrome? arg)
480                      " is a palindrome\n"
481                      " isn't a palindrome\n"))))
482</enscript>
483
484Now we can compile and link everything together. (We show the compile
485and link operations separately, but they can of course be combined
486into one command.)
487
488 $ csc -c pal-proc.scm
489 $ csc -c pal-user.scm
490 $ csc -o pal-separate pal-proc.o pal-user.o
491 $ ./pal-separate level
492 level is a palindrome
493
494=== Installing an egg
495
496Installing eggs is quite straightforward on systems that support
497dynamic loading (again, that would include *BSD, Linux, Mac OS X,
498Solaris, and Windows).  The command {{chicken-install}} will fetch an
499egg from the master CHICKEN repository, and install it on your local
500system.
501
502In this example, we install the {{uri-common}} egg, for parsing
503Uniform Resource Identifiers. The installation produces a lot of
504output, which we have edited for space.
505
506 $ chicken-install uri-common
507 
508 retrieving ...
509 resolving alias `kitten-technologies' to: http://chicken.kitten-technologies.co.uk/henrietta.cgi
510 connecting to host "chicken.kitten-technologies.co.uk", port 80 ...
511 requesting "/henrietta.cgi?name=uri-common&mode=default" ...
512 reading response ...
513 [...]
514 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.scm -j uri-common
515 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.import.scm
516 cp -r uri-common.so /usr/lib/chicken/5/uri-common.so
517 chmod a+r /usr/lib/chicken/5/uri-common.so
518 cp -r uri-common.import.so /usr/lib/chicken/5/uri-common.import.so
519 chmod a+r /usr/lib/chicken/5/uri-common.import.so
520 chmod a+r /usr/lib/chicken/5/uri-common.setup-info
521
522{{chicken-install}} connects to a mirror of the egg repository and
523retrieves the egg contents.  If the egg has any uninstalled
524dependencies, it recursively installs them.  Then it builds the egg
525code and installs the resulting extension into the
526local CHICKEN repository.
527
528Now we can use our new egg.
529
530 #;1> (use uri-common)
531 ; loading /usr/lib/chicken/5/uri-common.import.so ...
532 ; [... other loaded files omitted for clarity ...]
533 
534 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
535 "www.foobar.org"
536
537=== Accessing C libraries
538
539Because CHICKEN compiles to C, and because a foreign function
540interface is built into the compiler, interfacing to a C library is
541quite straightforward. This means that nearly any facility available
542on the host system is accessible from CHICKEN, with more or less
543work.
544
545Let's create a simple C library, to demonstrate how this
546works. Here we have a function that will compute and return the '''n'''th
547Fibonacci number. (This isn't a particularly good use of C here,
548because we could write this function just as easily in Scheme, but a
549real example would take far too much space here.)
550
551 /* fib.c */
552 int fib(int n) {
553   int prev = 0, curr = 1;
554   int next;
555   int i;
556   for (i = 0; i < n; i++) {
557     next = prev + curr;
558     prev = curr;
559     curr = next;
560   }
561   return curr;
562 }
563
564Now we can call this function from CHICKEN.
565
566 ;;; fib-user.scm
567 #>
568   extern int fib(int n);
569 <#
570 (define xfib (foreign-lambda int "fib" int))
571 (do ((i 0 (+ i 1))) ((> i 10))
572   (printf "~A " (xfib i)))
573 (newline)
574
575The syntax {{#>...<#}} allows you to include literal C (typically
576external declarations) in your CHICKEN code. We access {{fib}} by
577defining a {{foreign-lambda}} for it, in this case saying that the
578function takes one integer argument (the {{int}} after the function
579name), and that it returns an integer result (the {{int}} before.) Now we can invoke
580{{xfib}} as though it were an ordinary Scheme function.
581
582 $ gcc -c fib.c
583 $ csc -o fib-user fib.o fib-user.scm
584 $ ./fib-user
585 0 1 1 2 3 5 8 13 21 34 55
586
587Those who are interfacing to substantial C libraries should consider
588using the [[/egg/bind|bind egg]].
589
590---
591
592Back to [[The User's Manual]]
593
594Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.