source: project/chicken/branches/scrutiny/manual/Using the compiler @ 14827

Last change on this file since 14827 was 14827, checked in by felix winkelmann, 10 years ago

merged trunk changes until 14826 into scrutiny branch

File size: 25.0 KB
Line 
1[[tags: manual]]
2[[toc:]]
3
4== Using the compiler
5
6The interface to {{chicken}} is intentionally simple.  System
7dependent makefiles, shell-scripts or batch-files should perform
8any necessary steps before and after invocation of {{chicken}}.
9A program named {{csc}} provides a much simpler
10interface to the Scheme- and C-compilers and linker. Enter
11
12 csc -help
13
14on the command line for more information.
15
16=== Compiler command line format
17
18 chicken FILENAME {OPTION}
19
20{{FILENAME}} is the complete pathname of the source file that is to
21be translated into C. A filename argument of {{-}} specifies that
22the source text should be read from standard input. Note that the filename
23has to be the first argument to {{chicken}}.
24
25Possible options are:
26
27; -analyze-only : Stop compilation after first analysis pass.
28
29; -benchmark-mode : Equivalent to {{-no-trace -no-lambda-info -optimize-level 4}} {{-fixnum-arithmetic -disable-interrupts -block -inline -lambda-lift}}.
30
31; -block : Enable block-compilation. When this option is specified, the compiler assumes that global variables are not modified outside this compilation-unit.  Specifically, toplevel bindings are not seen by {{eval}} and unused toplevel bindings are removed.
32
33; -case-insensitive : Enables the reader to read symbols case insensitive. The default is to read case sensitive (in violation of R5RS).  This option registers the {{case-insensitive}} feature identifier.
34
35; -check-syntax : Aborts compilation process after macro-expansion and syntax checks.
36
37; -debug MODES : Enables one or more compiler debugging modes. {{MODES}} is a string of characters that select debugging information about the compiler that will be printed to standard output.
38
39     t          show time needed for compilation
40     b          show breakdown of time needed for each compiler pass
41     o          show performed optimizations
42     r          show invocation parameters
43     s          show program-size information and other statistics
44     a          show node-matching during simplification
45     p          show execution of compiler sub-passes
46     l          show lambda-lifting information
47     m          show GC statistics during compilation
48     n          print the line-number database
49     c          print every expression before macro-expansion
50     u          lists all unassigned global variable references
51     d          lists all assigned global variables
52     x          display information about experimental features
53     D          when printing nodes, use node-tree output
54     N          show the real-name mapping table
55     U          show expressions after the secondary user pass
56     0          show database before lambda-lifting pass
57     L          show expressions after lambda-lifting
58     M          show syntax-/runtime-requirements
59     1          show source expressions
60     2          show canonicalized expressions
61     3          show expressions converted into CPS
62     4          show database after each analysis pass
63     5          show expressions after each optimization pass
64     6          show expressions after each inlining pass
65     7          show expressions after complete optimization
66     8          show database after final analysis
67     9          show expressions after closure conversion
68
69; -debug-level LEVEL : Selects amount of debug-information. {{LEVEL}} should be an integer.
70
71     -debug-level 0             is equivalent to -no-trace -no-lambda-info
72     -debug-level 1             is equivalent to -no-trace
73     -debug-level 2             does nothing (the default)
74
75; -disable-interrupts : Equivalent to the {{(disable-interrupts)}} declaration. No interrupt-checks are generated for compiled programs.
76
77; -disable-stack-overflow-checks : Disables detection of stack overflows. This is equivalent to running the compiled executable with the {{-:o}} runtime option.
78
79; -disable-warning CLASS : Disables specific class of warnings, may be given multiple times. The following classes are defined:
80
81     usage              warnings related to command-line arguments
82     type               warnings related to type-conversion
83     ext                warnings related to extension libraries
84     var                warnings related to variable- and syntax-definitions and use
85     const              warnings related to constant-definitions
86     syntax             syntax-related warnings
87     redef              warnings about redefinitions of standard- or extended-bindings
88     call               warnings related to known procedure calls
89     ffi                warnings related to the foreign function interface
90
91; -dynamic : This option should be used when compiling files intended to be loaded dynamically into a running Scheme program.
92
93; -epilogue FILENAME : Includes the file named {{FILENAME}} at the end of the compiled source file. The include-path is not searched. This option may be given multiple times.
94
95; -emit-external-prototypes-first : Emit prototypes for callbacks defined with {{define-external}} before any other foreign declarations. This is sometimes useful, when C/C++ code embedded into the a Scheme program has to access the callbacks. By default the prototypes are emitted after foreign declarations.
96
97; -emit-import-library MODULE : Specifies that an import library named {{MODULE.import.scm}} for the named module should be generated (equivalent to using the {{emit-import-library}} declaration).
98
99; -emit-inline-file FILENAME : Write procedures that can be globally inlined in internal form to {{FILENAME}}, if global inlining is enabled. Implies {{-inline -local}}.
100
101; -explicit-use : Disables automatic use of the units {{library, eval}} and {{extras}}. Use this option if compiling a library unit instead of an application unit.
102
103; -extend FILENAME : Loads a Scheme source file or compiled Scheme program (on systems that support it) before compilation commences. This feature can be used to extend the compiler.  This option may be given multiple times. The file is also searched in the current include path and in the extension-repository.
104
105; -feature SYMBOL : Registers {{SYMBOL}} to be a valid feature identifier for {{cond-expand}}. Multiple symbols may be given, if comma-separated.
106
107; -fixnum-arithmetic : Equivalent to {{(fixnum-arithmetic)}} declaration. Assume all mathematical operations use small integer arguments.
108
109; -heap-size NUMBER : Sets a fixed heap size of the generated executable to {{NUMBER}} bytes. The parameter may be followed by a  {{M}} ({{m}}) or {{K}} ({{k}}) suffix which stand for mega- and kilobytes, respectively.  The default heap size is 5 kilobytes. Note that only half of it is in use at every given time.
110
111; -heap-initial-size NUMBER : Sets the size that the heap of the compiled application should have at startup time.
112
113; -heap-growth PERCENTAGE : Sets the heap-growth rate for the compiled program at compile time (see: {{-:hg}}).
114
115; -heap-shrinkage PERCENTAGE : Sets the heap-shrinkage rate for the compiled program at compile time (see: {{-:hs}}).
116
117; -help : Print a summary of available options and the format of the command line parameters and exit the compiler.
118
119; -ignore-repository : Do not load any extensions from the repository (treat repository as empty). Also do not consult compiled (only interpreted) import libraries in {{import}} forms.
120
121; -include-path PATHNAME : Specifies an additional search path for files included via the {{include}} special form. This option may be given multiple times. If the environment variable {{CHICKEN_INCLUDE_PATH}} is set, it should contain a list of alternative include pathnames separated by {{;}}.
122
123; -inline : Enable procedure inlining for known procedures of a size below the threshold (which can be set through the {{-inline-limit}} option).
124
125; -inline-global : Enable cross-module inlining (in addition to local inlining). Implies {{-inline}}. For more information, see also [[Declarations]].
126
127; -inline-limit THRESHOLD : Sets the maximum size of a potentially inlinable procedure. The default threshold is {{20}}.
128
129; -keyword-style STYLE : Enables alternative keyword syntax, where {{STYLE}} may be either {{prefix}} (as in Common Lisp), {{suffix}} (as in DSSSL) or {{none}}. Any other value is ignored. The default is {{suffix}}.
130
131; -keep-shadowed-macros : Do not remove macro definitions with the same name as assigned toplevel variables (the default is to remove the macro definition).
132
133; -lambda-lift : Enable the optimization known as lambda-lifting.
134
135; -local : Assume toplevel variables defined in the current compilation unit are not externally modified.
136
137; -no-lambda-info : Don't emit additional information for each {{lambda}} expression (currently the argument-list, after alpha-conversion/renaming).
138
139; -no-parentheses-synonyms STYLE : Disables list delimiter synonyms, [..] and {...} for (...).
140
141; -no-symbol-escape : Disables support for escaped symbols, the |...| form.
142
143; -no-trace : Disable generation of tracing information. If a compiled executable should halt due to a runtime error, then a list of the name and the line-number (if available) of the last procedure calls is printed, unless {{-no-trace}} is specified. With this option the generated code is slightly faster.
144
145; -no-warnings : Disable generation of compiler warnings.
146
147; -nursery NUMBER :
148; -stack-size NUMBER : Sets the size of the first heap-generation of the generated executable to {{NUMBER}} bytes. The parameter may be followed by a {{M}} ({{m}}) or {{K}} ({{k}}) suffix.  The default stack-size depends on the target platform.
149
150; -optimize-leaf-routines : Enable leaf routine optimization.
151
152; -optimize-level LEVEL : Enables certain sets of optimization options. {{LEVEL}} should be an integer.
153
154     -optimize-level 0          does nothing.
155     -optimize-level 1          is equivalent to -optimize-leaf-routines
156     -optimize-level 2          is currently the same as -optimize-level 1
157     -optimize-level 3          is equivalent to -optimize-leaf-routines -local -inline
158     -optimize-level 4          is equivalent to -optimize-leaf-routines -local -inline -unsafe
159
160; -output-file FILENAME : Specifies the pathname of the generated C file. Default is {{FILENAME.c}}.
161
162; -postlude EXPRESSIONS : Add {{EXPRESSIONS}} after all other toplevel expressions in the compiled file.  This option may be given multiple times. Processing of this option takes place after processing of {{-epilogue}}.
163
164; -prelude EXPRESSIONS : Add {{EXPRESSIONS}} before all other toplevel expressions in the compiled file.  This option may be given multiple times. Processing of this option takes place before processing of {{-prologue}}.
165
166; -profile :
167; -accumulate-profile : Instruments the source code to count procedure calls and execution times. After the program terminates (either via an explicit {{exit}} or implicitly), profiling statistics are written to a file named {{PROFILE}}. Each line of the generated file contains a list with the procedure name, the number of calls and the time spent executing it. Use the {{chicken-profile}} program to display the profiling information in a more user-friendly form. Enter {{chicken-profile}} with no arguments at the command line to get a list of available options. The {{-accumulate-profile}} option is similar to {{-profile}}, but the resulting profile information will be appended to any existing {{PROFILE}} file. {{chicken-profile}} will merge and sum up the accumulated timing information, if several entries for the same procedure calls exist.
168
169; -profile-name FILENAME : Specifies name of the generated profile information (which defaults to {{PROFILE}}. Implies {{-profile}}.
170
171; -prologue FILENAME : Includes the file named {{FILENAME}} at the start of the compiled source file.  The include-path is not searched. This option may be given multiple times.
172
173; -r5rs-syntax : Disables the Chicken extensions to R5RS syntax. Does not disable [[Non-standard read syntax|non-standard read syntax]].
174
175; -raw : Disables the generation of any implicit code that uses the Scheme libraries (that is all runtime system files besides {{runtime.c}} and {{chicken.h}}).
176
177; -require-extension NAME : Loads the extension {{NAME}} before the compilation process commences. This is identical to adding {{(require-extension NAME)}} at the start of the compiled program. If {{-uses NAME}} is also given on the command line, then any occurrences of {{-require-extension NAME}} are replaced with {{(declare (uses NAME))}}. Multiple names may be given and should be separated by {{,}}.
178
179; -scrutinize : Enable simple flow-analysis to catch common type errors and argument/result mismatches. You can also use the {{scrutinize}} declaration to enable scrutiny.
180
181; -static-extension NAME : similar to {{-require-extension NAME}}, but links extension statically (also applies for an explicit {{(require-extension NAME)}}).
182
183; -types FILENAME : load additional type database from {{FILENAME}}. Type-definitions in {{FILENAME}} will override previous type-definitions.
184
185; -compile-syntax : Makes macros also available at run-time. By default macros are not available at run-time.
186
187; -to-stdout : Write compiled code to standard output instead of creating a {{.c}} file.
188
189; -unit NAME : Compile this file as a library unit. Equivalent to {{-prelude "(declare (unit NAME))"}}
190
191; -unsafe : Disable runtime safety checks.
192
193; -unsafe-libraries : Marks the generated file for being linked with the unsafe runtime system. This should be used when generating shared object files that are to be loaded dynamically. If the marker is present, any attempt to load code compiled with this option will signal an error.
194
195; -uses NAME : Use definitions from the library unit {{NAME}}. This is equivalent to {{-prelude "(declare (uses NAME))"}}. Multiple arguments may be given, separated by {{,}}.
196
197; -no-usual-integrations : Specifies that standard procedures and certain internal procedures may be redefined, and can not be inlined. This is equivalent to declaring {{(not usual-integrations)}}.
198
199; -version : Prints the version and some copyright information and exit the compiler.
200
201; -verbose : Prints progress information to standard output during compilation.
202
203The environment variable {{CHICKEN_OPTIONS}} can be set to a string
204with default command-line options for the compiler.
205
206=== Runtime options
207
208After successful compilation a C source file is generated and can be
209compiled with a C compiler. Executables generated with CHICKEN (and the
210compiler itself) accept a small set of runtime options:
211
212; {{-:?}} : Shows a list of the available runtime options and exits the program.
213
214; {{-:aNUMBER}} : Specifies the length of the buffer for recording a trace of the last invoked procedures. Defaults to 16.
215
216; {{-:b}} : Enter a read-eval-print-loop when an error is encountered.
217
218; {{-:B}} : Sounds a bell (ASCII 7) on every major garbage collection.
219
220; {{-:c}} : Forces console mode. Currently this is only used in the interpreter ({{csi}}) to force output of the {{#;N>}} prompt even if stdin is not a terminal (for example if running in an {{emacs}} buffer under Windows).
221
222; {{-:d}} : Prints some debug-information at runtime.
223
224; {{-:D}} : Prints some more debug-information at runtime.
225
226; {{-:fNUMBER}} : Specifies the maximal number of currently pending finalizers before finalization is forced.
227
228; {{-:hNUMBER}} : Specifies fixed heap size
229
230; {{-:hgPERCENTAGE}} : Sets the growth rate of the heap in percent. If the heap is exhausted, then it will grow by {{PERCENTAGE}}. The default is 200.
231
232; {{-:hiNUMBER}} : Specifies the initial heap size
233
234; {{-:hmNUMBER}} : Specifies a maximal heap size. The default is (2GB - 15).
235
236; {{-:hsPERCENTAGE}} : Sets the shrink rate of the heap in percent. If no more than a quarter of {{PERCENTAGE}} of the heap is used, then it will shrink to {{PERCENTAGE}}. The default is 50.  Note: If you want to make sure that the heap never shrinks, specify a value of {{0}}.  (this can be useful in situations where an optimal heap-size is known in advance).
237
238; {{-:o}} : Disables detection of stack overflows at run-time.
239
240; {{-:r}} : Writes trace output to stderr. This option has no effect with in files compiled with the {{-no-trace}} options.
241
242; {{-:sNUMBER}} : Specifies stack size.
243
244; {{-:tNUMBER}} : Specifies symbol table size.
245
246; {{-:w}} : Enables garbage collection of unused symbols. By default unused and unbound symbols are not garbage collected.
247
248; {{-:x}} : Raises uncaught exceptions of separately spawned threads in primordial thread. By default uncaught exceptions in separate threads are not handled, unless the primordial one explicitly joins them. When warnings are enabled (the default) and {{-:x}} is not given, a warning will be shown, though.
249
250The argument values may be given in bytes, in kilobytes (suffixed with
251{{K}} or {{k}}), in megabytes (suffixed with {{M}}
252or {{m}}), or in gigabytes (suffixed with {{G}}
253or {{g}}). Runtime options may be combined, like {{-:dc}},
254but everything following a {{NUMBER}} argument is ignored. So
255{{-:wh64m}} is OK, but {{-:h64mw}} will not enable GC of
256unused symbols.
257=== Examples
258
259==== A simple example (with one source file)
260
261To compile a Scheme program (assuming a UNIX-like environment) consisting of a single source file, perform the following steps.
262
263===== Writing your source file
264
265In this example we will assume your source file is called {{foo.scm}}:
266
267<enscript highlight=scheme>
268;;; foo.scm
269
270(define (fac n)
271  (if (zero? n)
272      1
273      (* n (fac (- n 1))) ) )
274
275(write (fac 10))
276(newline)
277</enscript>
278
279===== Compiling your program
280
281Compile the file {{foo.scm}}:
282
283 % csc foo.scm
284
285This will produce the {{foo}} executable:
286
287 % ls
288 foo  foo.scm
289
290===== Running your program
291
292To run your newly compiled executable use:
293
294 % foo
295 3628800
296
297If you get a {{foo: command not found}} error, you might want to try with {{./foo}} instead
298(or, in Unix machines, modify your {{PATH}} environment variable to include your current directory).
299==== An example with multiple files
300
301If multiple bodies of Scheme code are to be combined into a single
302executable, then we have to compile each file and link the resulting
303object files together with the runtime system.
304
305Let's consider an example where your program consists of multiple source files.
306
307===== Writing your source files
308
309The declarations in these files specify which of the compiled files is the main
310module, and which is the library module. An executable can only have
311one main module, since a program has only a single entry-point. In this
312case {{foo.scm}} is the main module, because it doesn't have a
313{{unit}} declaration:
314
315<enscript highlight=scheme>
316;;; foo.scm
317
318; The declaration marks this source file as dependant on the symbols provided
319; by the bar unit:
320(declare (uses bar))
321
322(write (fac 10)) (newline)
323</enscript>
324
325{{bar.scm}} will be our library:
326
327<enscript highlight=scheme>
328;;; bar.scm
329
330; The declaration marks this source file as the bar unit.  The names of the
331; units and your files don't need to match.
332(declare (unit bar))
333
334(define (fac n)
335  (if (zero? n)
336      1
337      (* n (fac (- n 1))) ) )
338</enscript>
339
340===== Compiling and running your program
341
342You should compile your two files with the following commands:
343
344 % csc -c bar.scm
345 % csc -c foo.scm
346
347That should produce two files, {{bar.o}} and {{foo.o}}.
348They contain the code from your source files in compiled form.
349
350To link your compiled files use the following command:
351
352 % csc foo.o bar.o -o foo
353
354This should produce the {{foo}} executable, which you can run just as in the previous example.
355At this point you can also erase the {{*.o}} files.
356
357You could avoid one step and link the two files just as {{foo.scm}} is compiled:
358
359 % csc -c bar.scm
360 % csc foo.scm bar.o -o foo
361
362Note that if you want to distribute your program, you might want it to
363follow the GNU Coding Standards.  One relatively easy way to achieve
364this is to use Autoconf and Automake, two tools made for this specific
365purpose.
366
367=== Extending the compiler
368
369The compiler supplies a couple of hooks to add user-level passes to the
370compilation process. Before compilation commences any Scheme source files
371or compiled code specified using the {{-extend}} option are loaded
372and evaluated.  The parameters {{user-options-pass, user-read-pass,
373user-preprocessor-pass, user-pass}} and {{user-post-analysis-pass}} can be set
374to procedures that are called to perform certain compilation passes
375instead of the usual processing (for more information about parameters
376see: [[Supported language]].
377
378; [parameter] user-options-pass : Holds a procedure that will be called with a list of command-line arguments and should return two values: the source filename and the actual list of options, where compiler switches have their leading {{-}} (hyphen) removed and are converted to symbols.  Note that this parameter is invoked '''before''' processing of the {{-extend}} option, and so can only be changed in compiled user passes.
379
380; [parameter] user-read-pass : Holds a procedure of three arguments. The first argument is a list of strings with the code passed to the compiler via {{-prelude}} options. The second argument is a list of source files including any files specified by {{-prologue}} and {{-epilogue}}. The third argument is a list of strings specified using {{-postlude}} options. The procedure should return a list of toplevel Scheme expressions.
381
382; [parameter] user-preprocessor-pass : Holds a procedure of one argument. This procedure is applied to each toplevel expression in the source file '''before''' macro-expansion. The result is macro-expanded and compiled in place of the original expression.
383
384; [parameter] user-pass : Holds a procedure of one argument. This procedure is applied to each toplevel expression '''after''' macro-expansion.  The result of the procedure is then compiled in place of the original expression.
385
386; [parameter] user-post-analysis-pass : Holds a procedure that will be called after every performed program analysis pass. The procedure (when defined) will be called with seven arguments: a symbol indicating the analysis pass, the program database, the current node graph, a getter and a setter-procedure which can be used to access and manipulate the program database, which holds various information about the compiled program, a pass iteration count, and an analysis continuation flag. The getter procedure should be called with two arguments: a symbol representing the binding for which information should be retrieved, and a symbol that specifies the database-entry. The current value of the database entry will be returned or {{#f}}, if no such entry is available. The setter procedure is called with three arguments: the symbol and key and the new value. The pass iteration count currently is meaningful only for the 'opt pass. The analysis continuation flag will be {{#f}} for the last 'opt pass. For information about the contents of the program database contact the author.
387
388Loaded code (via the {{-extend}} option) has access to the library
389units {{extras, srfi-1, srfi-4, utils, regex}} and the pattern matching macros.
390Multithreading is not available.
391
392Note that the macroexpansion/canonicalization phase of the compiler adds
393certain forms to the source program.  These extra expressions are not
394seen by {{user-preprocessor-pass}} but by {{user-pass}}.
395
396=== Distributing compiled C files
397
398It is relatively easy to create distributions of Scheme projects that
399have been compiled to C.  The runtime system of CHICKEN consists of only
400two handcoded C files ({{runtime.c}} and {{chicken.h}}), plus
401the file {{chicken-config.h}}, which is generated by the build process. All
402other modules of the runtime system and the extension libraries are just
403compiled Scheme code. The following example shows a minimal application, which
404should run without changes on the most frequent operating systems, like Windows,
405Linux or FreeBSD:
406
407Let's take a simple example.
408
409<enscript highlight=scheme>
410; hello.scm
411
412(print "Hello, world!")
413</enscript>
414
415  % chicken hello.scm -optimize-level 3 -output-file hello.c
416
417Compiled to C, we get {{hello.c}}. We need the files {{chicken.h}} and
418{{runtime.c}}, which contain the basic runtime system, plus the three
419basic library files {{library.c}}, {{eval.c}} and {{extras.c}} which
420contain the same functionality as the library linked into a plain
421CHICKEN-compiled application, or which is available by default in the
422interpreter, {{csi}}:
423
424  % cd /tmp
425  %echo '(print "Hello World.")' > hello.scm
426  % cp $CHICKEN_BUILD/runtime.c .
427  % cp $CHICKEN_BUILD/library.c .
428  % cp $CHICKEN_BUILD/eval.c    .
429  % cp $CHICKEN_BUILD/extras.c  .
430  % gcc -static -Os -fomit-frame-pointer runtime.c library.c eval.c \
431    extras.c hello.c -o hello -lm
432
433Now we have all files together, and can create an tarball containing all the files:
434
435 % tar cf hello.tar Makefile hello.c runtime.c library.c eval.c extras.c chicken.h
436 % gzip hello.tar
437
438This is naturally rather simplistic. Things like enabling dynamic loading, estimating
439the optimal stack-size and selecting supported features of the host system would need
440more configuration- and build-time support. All this can be addressed using more
441elaborate build-scripts, makefiles or by using autoconf/automake.
442
443Note also that the size of the application can still be reduced by removing {{extras}} and
444{{eval}} and compiling {{hello.scm}} with the {{-explicit-use}} option.
445
446For more information, study the CHICKEN source code and/or get in
447contact with the author.
448
449---
450Previous: [[The User's Manual]]
451
452Next: [[Using the interpreter]]
Note: See TracBrowser for help on using the repository browser.