This manual is for SCM (version 5f4, January 2024), an implementation of the algorithmic language Scheme.
Copyright © 1990-2007 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License.”
SCM is a portable Scheme implementation written in C. SCM provides a machine independent platform for [JACAL], a symbolic algebra system. SCM supports and requires the SLIB Scheme library. SCM, SLIB, and JACAL are GNU projects.
logand, logor, logxor,
lognot, ash, logcount, integer-length,
bit-extract, defmacro, macroexpand,
macroexpand1, gentemp, defvar, force-output,
software-type, get-decoded-time,
get-internal-run-time, get-internal-real-time,
delete-file, rename-file, copy-tree, acons,
and eval.
Char-code-limit, most-positive-fixnum,
most-negative-fixnum, and internal-time-units-per-second
constants. slib:features and *load-pathname* variables.
verbose function).
Restart, quit, and exec.
Most of SCM.
Arrays, gsubrs, compiled closures, records, Ecache, syntax-rules
macros, and safeports.
Real and Complex functions. Fast mixed type arithmetics.
Syntax checking and memoization of special forms by evaluator. Storage allocation strategy and parameters.
Siod, written by George Carrette, was the starting point for SCM. The major innovations taken from Siod are the evaluator’s use of the C-stack and being able to garbage collect off the C-stack (see Garbage Collection).
There are many other contributors to SCM. They are acknowledged in the file ChangeLog, a log of changes that have been made to scm.
Authors have assigned their SCM copyrights to:
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Paradigm Associates Inc not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
PARADIGM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL PARADIGM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
gjc@paradigm.com
Phone: 617-492-6079
Paradigm Associates Inc 29 Putnam Ave, Suite 6 Cambridge, MA 02138
Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text.
The “publisher” means any person or entity that distributes copies of the Document to the public.
A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles.
You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.”
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
“Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site.
“CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
“Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document.
An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with…Texts.” line with this:
with the Invariant Sections being list their titles, with
the Front-Cover Texts being list, and with the Back-Cover Texts
being list.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
IEEE Standard 1178-1990. IEEE Standard for the Scheme Programming Language. IEEE, New York, 1991.
William Clinger and Jonathan Rees, Editors. Revised(4) Report on the Algorithmic Language Scheme. ACM Lisp Pointers Volume IV, Number 3 (July-September 1991), pp. 1-55.
Richard Kelsey and William Clinger and Jonathan (Rees, editors) Revised(5) Report on the Algorithmic Language Scheme. Higher-Order and Symbolic Computation Volume 11, Number 1 (1998), pp. 7-105, and ACM SIGPLAN Notices 33(9), September 1998.
William Clinger Hygienic Macros Through Explicit Renaming Lisp Pointers Volume IV, Number 4 (December 1991), pp 17-23.
Harold Abelson and Gerald Jay Sussman with Julie Sussman. Structure and Interpretation of Computer Programs. MIT Press, Cambridge, 1985.
Brian Harvey and Matthew Wright. Simply Scheme: Introducing Computer Science MIT Press, 1994 ISBN 0-262-08226-8
$B8$;tBg(B(Dai Inukai) $BF~Lg(BScheme 1999$BG/(B12$B7n=iHG(B ISBN4-87966-954-7
Todd R. Eigenschink, Dave Love, and Aubrey Jaffer. SLIB, The Portable Scheme Library. Version 2c8, June 2000.
Aubrey Jaffer. JACAL Symbolic Mathematics System. Version 1b0, Sep 1999.
Documentation of scm extensions (beyond Scheme standards).
Documentation on the internal representation and how to extend or
include scm in other programs.
Documentation of the Xlib - SCM Language X Interface.
SCM runs on a wide variety of platforms. “Distributions” is the starting point for all platforms. The process described in “GNU configure and make” will work on most Unix and GNU/Linux platforms. If it works for you, then you may skip the later sections of “Installing SCM”.
The SCM homepage contains links to precompiled binaries and source distributions.
Downloads and instructions for installing the precompiled binaries are at http://people.csail.mit.edu/jaffer/SCM#QuickStart.
If there is no precompiled binary for your platform, you may be able to build from the source distribution. The rest of these instructions deal with building and installing SCM and SLIB from sources.
Download (both SCM and SLIB of) either the last release or current development snapshot from http://people.csail.mit.edu/jaffer/SCM#BuildFromSource.
Unzip both the SCM and SLIB zips. For example, if you are working in /usr/local/src/, this will create directories /usr/local/src/scm/ and /usr/local/src/slib/.
scm/configure and slib/configure are Shell scripts which create the files scm/config.status and slib/config.status on Unix and MinGW systems.
The config.status files are used (included) by the Makefile to
control where the packages will be installed by make install.
With GNU shell (bash) and utilities, the following commands should
build and install SCM and SLIB:
bash$ (cd slib; ./configure --prefix=/usr/local/) bash$ (cd scm > ./configure --prefix=/usr/local/ > make scmlit > sudo make all > sudo make install) bash$ (cd slib; sudo make install)
If the install commands worked, skip to Testing.
If configure doesn’t work on your system, make scm/config.status and slib/config.status be empty files.
For additional help on using the configure script, run ‘./configure --help’.
‘make all’ will attempt to create a dumped executable (see Saving Executable Images), which has very small startup latency. If that fails, it will try to compile an ordinary ‘scm’ executable.
Note that the compilation output may contain error messages; be concerned only if the ‘make install’ transcripts contain errors.
‘sudo’ runs the command after it as user root. On recent GNU/Linux systems, dumping requires that ‘make all’ be run as user root; hence the use of ‘sudo’.
‘make install’ requires root privileges if you are installing to standard Unix locations as specified to (or defaulted by) ‘./configure’. Note that this is independent of whether you did ‘sudo make all’ or ‘make all’.
The SCM distribution Makefile contains rules for making scmlit, a “bare-bones” version of SCM sufficient for running build. build is a Scheme program used to compile (or create scripts to compile) full featured versions of SCM (see Building SCM). To create scmlit, run ‘make scmlit’ in the scm/ directory.
Makefiles are not portable to the majority of platforms. If you need to compile SCM without ‘scmlit’, there are several ways to proceed:
If you didn’t create scmlit using ‘make scmlit’, then you must create a file named scm/require.scm. For most installations, scm/require.scm can just be copied from scm/requires.scm, which is part of the SCM distribution.
If, when executing ‘scmlit’ or ‘scm’, you get a message like:
ERROR: "LOAD couldn't find file " "/usr/local/src/scm/require"
then create a file require.scm in the SCM implementation-vicinity (this is the same directory as where the file Init5f4.scm is). require.scm should have the contents:
(define (library-vicinity) "/usr/local/lib/slib/")
where the pathname string /usr/local/lib/slib/ is to be replaced by the pathname into which you unzipped (or installed) SLIB.
Alternatively, you can set the (shell) environment variable
SCHEME_LIBRARY_PATH to the pathname of the SLIB directory
(see Environment Variables).
If set, this environment variable overrides scm/require.scm.
Absolute pathnames are recommended here; if you use a relative pathname, SLIB can get confused when the working directory is changed (see chmod). The way to specify a relative pathname is to append it to the implementation-vicinity, which is absolute:
(define library-vicinity
(let ((lv (string-append (implementation-vicinity) "../slib/")))
(lambda () lv)))
Each of the following four ‘make’ targets creates an executable named scm. Each target takes its build options from a file with an ‘.opt’ suffix. If that options file doesn’t exist, making that target will create the file with the ‘-F’ features: cautious, bignums, arrays, inexact, engineering-notation, and dynamic-linking. Once that ‘.opt’ file exists, you can edit it to your taste and it will be preserved.
make scm4Produces a R4RS executable named scm lacking hygienic macros (but with defmacro). The build options are taken from scm4.opt. If build or the executable fails, try removing ‘dynamic-linking’ from scm4.opt.
make scm5R5RS; like ‘make scm4’ but with ‘-F macro’. The build options are taken from scm5.opt. If build or the executable fails, try removing ‘dynamic-linking’ from scm5.opt.
make dscm4Produces a R4RS executable named udscm4, which it starts and dumps to a low startup latency executable named scm. The build options are taken from udscm4.opt.
If the build fails, then ‘build scm4’ instead. If the dumped executable fails to run, then send me a bug report (and use ‘build scm4’ until the problem with dump is corrected).
make dscm5Like ‘make dscm4’ but with ‘-F macro’. The build options are taken from udscm5.opt.
If the build fails, then ‘build scm5’ instead. If the dumped executable fails to run, then send me a bug report (and use ‘build scm5’ until the problem with dump is corrected).
If the above builds fail because of ‘-F dynamic-linking’, then (because they can’t be dynamically linked) you will likely want to add some other features to the build’s ‘.opt’ file. See the ‘-F’ build option in Build Options.
If dynamic-linking is working, then you will likely want to compile most of the modules as DLLs. The build options for compiling DLLs are in dlls.opt.
make x.soThe Xlib module;
SCM Language X Interface in Xlibscm.
make myturtleCreates a DLL named turtlegr.so which is a simple graphics API.
make wbscm.soThe wb module;
B-tree database implementation in wb.
Compiling this requires that wb source be in a peer directory to scm.
make dllsCompiles all the distributed library modules, but not wbscm.so. Many of the module compiles are recursively invoked in such a way that failure of one (which could be due to a system library not being installed) doesn’t cause the top-level ‘make dlls’ to fail. If ‘make dlls’ fails as a whole, it is time to submit a bug report (see Reporting Problems).
The file build loads the file build.scm, which constructs a relational database of how to compile and link SCM executables. build.scm has information for the platforms which SCM has been ported to (of which I have been notified). Some of this information is old, incorrect, or incomplete. Send corrections and additions to agj@alum.mit.edu.
This section teaches how to use build, a Scheme program for creating compilation scripts to produce SCM executables and library modules. The options accepted by ‘build’ are documented in Build Options.
Use the any method if you encounter problems with the other two methods (MS-DOS, Unix).
From the SCM source directory, type ‘build’ followed by up to 9 command line arguments.
From the SCM source directory, type ‘./build’ followed by command line arguments.
From the SCM source directory, start ‘scm’ or ‘scmlit’ and
type (load "build"). Alternatively, start ‘scm’ or
‘scmlit’ with the command line argument ‘-ilbuild’.
This method will also work for MS-DOS and Unix.
After loading various SLIB modules, the program will print:
type (b "build <command-line>") to build type (b*) to enter build command loop
The ‘b*’ procedure enters into a build shell where you can enter commands (with or without the ‘build’). Blank lines are ignored. To create a build script with all defaults type ‘build’.
If the build-shell encouters an error, you can reenter the build-shell by typing ‘(b*)’. To exit scm type ‘(quit)’.
Here is a transcript of an interactive (b*) build-shell.
bash$ scmlit SCM version 5e7, Copyright (C) 1990-2006 Free Software Foundation. SCM comes with ABSOLUTELY NO WARRANTY; for details type `(terms)'. This is free software, and you are welcome to redistribute it under certain conditions; type `(terms)' for details. > (load "build") ;loading build ; loading /home/jaffer/slib/getparam ; loading /home/jaffer/slib/coerce ... ; done loading build.scm type (b "build <command-line>") to build type (b*) to enter build command loop ;done loading build #<unspecified> > (b*) ;loading /home/jaffer/slib/comparse ;done loading /home/jaffer/slib/comparse.scm build> -t exe #! /bin/sh # unix (linux) script created by SLIB/batch Wed Oct 26 17:14:23 2011 # [-p linux] # ================ Write file with C defines rm -f scmflags.h echo '#define IMPLINIT "Init5e7.scm"'>>scmflags.h echo '#define BIGNUMS'>>scmflags.h echo '#define FLOATS'>>scmflags.h echo '#define ARRAYS'>>scmflags.h # ================ Compile C source files gcc -c continue.c scm.c scmmain.c findexec.c script.c time.c repl.c scl.c eval.c sys.c subr.c debug.c unif.c rope.c # ================ Link C object files gcc -rdynamic -o scm continue.o scm.o scmmain.o findexec.o script.o time.o repl.o scl.o eval.o sys.o subr.o debug.o unif.o rope.o -lm -lc "scm" build> -t exe -w myscript.sh "scm" build> (quit)
No compilation was done. The ‘-t exe’ command shows the compile script. The ‘-t exe -w myscript.sh’ line creates a file myscript.sh containing the compile script. To actually compile and link it, type ‘./myscript.sh’.
Invoking build without the ‘-F’ option will build or create a
shell script with the arrays, inexact, and
bignums options as defaults. Invoking ‘build’ with
‘-F lit -o scmlit’ will make a script for compiling
‘scmlit’.
bash$ ./build -| #! /bin/sh # unix (linux) script created by SLIB/batch # ================ Write file with C defines rm -f scmflags.h echo '#define IMPLINIT "Init5f4.scm"'>>scmflags.h echo '#define BIGNUMS'>>scmflags.h echo '#define FLOATS'>>scmflags.h echo '#define ARRAYS'>>scmflags.h # ================ Compile C source files gcc -O2 -c continue.c scm.c scmmain.c findexec.c script.c time.c repl.c scl.c eval.c sys.c subr.c debug.c unif.c rope.c # ================ Link C object files gcc -rdynamic -o scm continue.o scm.o scmmain.o findexec.o script.o time.o repl.o scl.o eval.o sys.o subr.o debug.o unif.o rope.o -lm -lc
To cross compile for another platform, invoke build with the ‘-p’ or ‘--platform=’ option. This will create a script for the platform named in the ‘-p’ or ‘--platform=’ option.
bash$ ./build -o scmlit -p darwin -F lit -| #! /bin/sh # unix (darwin) script created by SLIB/batch # ================ Write file with C defines rm -f scmflags.h echo '#define IMPLINIT "Init5f4.scm"'>>scmflags.h # ================ Compile C source files cc -O3 -c continue.c scm.c scmmain.c findexec.c script.c time.c repl.c scl.c eval.c sys.c subr.c debug.c unif.c rope.c # ================ Link C object files mv -f scmlit scmlit~ cc -o scmlit continue.o scm.o scmmain.o findexec.o script.o time.o repl.o scl.o eval.o sys.o subr.o debug.o unif.o rope.o
The options to build specify what, where, and how to build a SCM program or dynamically linked module. These options are unrelated to the SCM command line options.
specifies that the compilation should be for a computer/operating-system combination called platform-name. Note The case of platform-name is distinguised. The current platform-names are all lower-case.
The platforms defined by table platform in build.scm are:
Table: platform name processor operating-system compiler #f processor-family operating-system #f symbol processor-family operating-system symbol symbol symbol symbol symbol ================= ================= ================= ================= *unknown* *unknown* unix cc acorn-unixlib acorn *unknown* cc aix powerpc aix cc alpha-elf alpha unix cc alpha-linux alpha linux gcc amiga-aztec m68000 amiga cc amiga-dice-c m68000 amiga dcc amiga-gcc m68000 amiga gcc amiga-sas m68000 amiga lc atari-st-gcc m68000 atari-st gcc atari-st-turbo-c m68000 atari-st tcc borland-c i8086 ms-dos bcc darwin powerpc unix cc djgpp i386 ms-dos gcc freebsd *unknown* unix cc gcc *unknown* unix gcc gnu-win32 i386 unix gcc highc i386 ms-dos hc386 hp-ux hp-risc hp-ux cc irix mips irix gcc linux *unknown* linux gcc linux-aout i386 linux gcc linux-ia64 ia64 linux gcc microsoft-c i8086 ms-dos cl microsoft-c-nt i386 ms-dos cl microsoft-quick-c i8086 ms-dos qcl ms-dos i8086 ms-dos cc netbsd *unknown* unix gcc openbsd *unknown* unix gcc os/2-cset i386 os/2 icc os/2-emx i386 os/2 gcc osf1 alpha unix cc plan9-8 i386 plan9 8c sunos sparc sunos cc svr4 *unknown* unix cc svr4-gcc-sun-ld sparc sunos gcc turbo-c i8086 ms-dos tcc unicos cray unicos cc unix *unknown* unix cc vms vax vms cc vms-gcc vax vms gcc watcom-9.0 i386 ms-dos wcc386p
specifies that the build options contained in pathname be spliced into the argument list at this point. The use of option files can separate functional features from platform-specific ones.
The Makefile calls out builds with the options in ‘.opt’ files:
Options for Makefile targets dlls, myturtle, and x.so.
Options for udgdbscm and gdbscm.
Options for libscm.a.
Options for pgscm, which instruments C functions.
Options for targets udscm4 and dscm4 (scm).
Options for targets udscm5 and dscm5 (scm).
The Makefile creates options files it depends on only if they do not already exist.
specifies that the compilation should produce an executable or object name of filename. The default is ‘scm’. Executable suffixes will be added if neccessary, e.g. ‘scm’ ⇒ ‘scm.exe’.
specifies that the libname should be linked with the executable produced. If compile flags or include directories (‘-I’) are needed, they are automatically supplied for compilations. The ‘c’ library is always included. SCM features specify any libraries they need; so you shouldn’t need this option often.
specifies that the definition should be made in any C source compilations. If compile flags or include directories (‘-I’) are needed, they are automatically supplied for compilations. SCM features specify any flags they need; so you shouldn’t need this option often.
specifies that that flag will be put on compiler command-lines.
specifies that that flag will be put on linker command-lines.
specifies that pathname should be the default location of the SCM initialization file Init5f4.scm. SCM tries several likely locations before resorting to pathname (see File-System Habitat). If not specified, the current directory (where build is building) is used.
specifies that the C source files pathname … are to be compiled.
specifies that the object files pathname … are to be linked.
specifies that the C functions call … are to be invoked during initialization.
specifies in general terms what sort of thing to build. The choices are:
executable program.
library module.
archived dynamically linked library object files.
dynamically linked library object file.
The default is to build an executable.
specifies how to build. The default is to create a batch file for the host system. The SLIB file batch.scm knows how to create batch files for:
This option executes the compilation and linking commands through the
use of the system procedure.
This option outputs Scheme code.
specifies where to write the build script. The default is to display it
on (current-output-port).
specifies to build the given features into the executable. The defined features are:
Alias for ARRAYS
array-map! and array-for-each (arrays must also be featured).
Use if you want arrays, uniform-arrays and uniform-vectors.
Large precision integers.
Treating strings as byte-vectors.
Byte/number conversions
Define this for extra checking of interrupt masking and some simple checks for proper use of malloc and free. This is for debugging C code in sys.c, eval.c, repl.c and makes the interpreter several times slower than usual.
Normally, the number of arguments arguments to interpreted closures (from LAMBDA) are checked if the function part of a form is not a symbol or only the first time the form is executed if the function part is a symbol. defining ‘reckless’ disables any checking. If you want to have SCM always check the number of arguments to interpreted closures define feature ‘cautious’.
If you only need straight stack continuations, executables compile with this feature will run faster and use less storage than not having it. Machines with unusual stacks need this. Also, if you incorporate new C code into scm which uses VMS system services or library routines (which need to unwind the stack in an ordrly manner) you may need to use this feature.
Use if you want to use compiled closures.
For the curses screen management package.
Turns on the features ‘cautious’ and
‘careful-interrupt-masking’; uses
-g flags for debugging SCM source code.
Sequence comparison
SCM normally converts references to local variables to ILOCs, which make programs run faster. If SCM is badly broken, try using this option to disable the MEMOIZE_LOCALS feature.
Convert a running scheme program into an executable file.
Be able to load compiled files while running.
interface to the editline or GNU readline library.
Use if you want floats to display in engineering notation (exponents always multiples of 3) instead of scientific notation.
make_gsubr for arbitrary (< 11) arguments to C functions.
Commonly available I/O extensions: exec, line I/O, file positioning, file delete and rename, and directory functions.
Use if you want floating point numbers.
Lightweight – no features
C level support for hygienic and referentially transparent macros (syntax-rules macros).
Client connections to the mysql databases.
Use if you want segments of unused heap to not be freed up after garbage collection. This may increase time in GC for *very* large working sets.
No features
Posix functions available on all Unix-like systems. fork and process functions, user and group IDs, file permissions, and link.
If your scheme code runs without any errors you can disable almost all error checking by compiling all files with ‘reckless’.
The Record package provides a facility for user to define their own record data types. See SLIB for documentation.
String regular expression matching.
These procedures were specified in the Revised^2 Report on Scheme but not in R4RS.
Use if you want to run code from:
Harold Abelson and Gerald Jay Sussman with Julie Sussman. Structure and Interpretation of Computer Programs. The MIT Press, Cambridge, Massachusetts, USA, 1985.
Differences from R5RS are:
Use if you want all inexact real numbers to be single precision. This only has an effect if SINGLES is also defined (which is the default). This does not affect complex numbers.
BSD socket interface. Socket addr functions require inexacts or bignums for 32-bit precision.
Use if you want the ticks and ticks-interrupt functions.
Turtle graphics calls for both Borland-C and X11 from sjm@ee.tut.fi.
Those unix features which have not made it into the Posix specs: nice, acct, lstat, readlink, symlink, mknod and sync.
WB database with relational wrapper.
no-comment
Microsoft Windows executable.
Alias for Xlib feature.
Interface to Xlib graphics routines.
A correspondent asks:
How can we link in our own c files to the SCM interpreter so that we can add our own functionality? (e.g. we have a bunch of tcp functions we want access to). Would this involve changing build.scm or the Makefile or both?
(see Changing Scm has instructions describing the C code format). Suppose a C file foo.c has functions you wish to add to SCM. To compile and link your file at compile time, use the ‘-c’ and ‘-i’ options to build:
bash$ ./build -c foo.c -i init_foo
-|
#! /bin/sh
rm -f scmflags.h
echo '#define IMPLINIT "/home/jaffer/scm/Init5f4.scm"'>>scmflags.h
echo '#define COMPILED_INITS init_foo();'>>scmflags.h
echo '#define BIGNUMS'>>scmflags.h
echo '#define FLOATS'>>scmflags.h
echo '#define ARRAYS'>>scmflags.h
gcc -O2 -c continue.c scm.c findexec.c script.c time.c repl.c scl.c \
eval.c sys.c subr.c unif.c rope.c foo.c
gcc -rdynamic -o scm continue.o scm.o findexec.o script.o time.o \
repl.o scl.o eval.o sys.o subr.o unif.o rope.o foo.o -lm -lc
To make a dynamically loadable object file use the -t dll option:
bash$ ./build -t dll -c foo.c -| #! /bin/sh rm -f scmflags.h echo '#define IMPLINIT "/home/jaffer/scm/Init5f4.scm"'>>scmflags.h echo '#define BIGNUMS'>>scmflags.h echo '#define FLOATS'>>scmflags.h echo '#define ARRAYS'>>scmflags.h echo '#define DLL'>>scmflags.h gcc -O2 -fpic -c foo.c gcc -shared -o foo.so foo.o -lm -lc
Once foo.c compiles correctly (and your SCM build supports
dynamic-loading), you can load the compiled file with the Scheme command
(load "./foo.so"). See Configure Module Catalog for how to
add a compiled dll file to SLIB’s catalog.
In SCM, the ability to save running program images is called dump
(see Dump). In order to make dump available to SCM, build
with feature ‘dump’. dumped executables are compatible with
dynamic linking.
Most of the code for dump is taken from emacs-19.34/src/unex*.c. No modifications to the emacs source code were required to use unexelf.c. Dump has not been ported to all platforms. If unexec.c or unexelf.c don’t work for you, try using the appropriate unex*.c file from emacs.
The ‘dscm4’ and ‘dscm5’ targets in the SCM Makefile save images from udscm4 and udscm5 executables respectively.
Address space layout randomization interferes with dump.
Here are the fixes for various operating-systems:
Remove the ‘#’ from the line ‘#SETARCH = setarch i386’ in the Makefile.
http://jamesthornton.com/writing/emacs-compile.html [For FC3] combreloc has become the default for recent GNU ld, which breaks the unexec/undump on all versions of both Emacs and XEmacs...
Override by adding the following to udscm5.opt: ‘--linker-options="-z nocombreloc"’
http://www.opensubscriber.com/message/emacs-devel@gnu.org/1007118.html
mentions the exec-shield feature. Kernels later than 2.6.11 must do (as root):
echo 0 > /proc/sys/kernel/randomize_va_space
before dumping. Makefile has this randomize_va_space stuffing scripted for targets ‘dscm4’ and ‘dscm5’. You must either set randomize_va_space to 0 or run as root to dump.
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man1/dyld.1.html
The dynamic linker uses the following environment variables. They affect any program that uses the dynamic linker.
DYLD_NO_PIE
Causes dyld to not randomize the load addresses of images in a process where the main executable was built position independent. This can be helpful when trying to reproduce and debug a problem in a PIE.
Once scmlit, scm, and dlls have been built, these
commands will install them to the locations specified when you ran
‘./configure’:
bash$ (cd scm; make install) bash$ (cd slib; make install)
Note that installation to system directories (like ‘/usr/bin/’) will require that those commands be run as root:
bash$ (cd scm; sudo make install) bash$ (cd slib; sudo make install)
| FILE | PROBLEM / MESSAGE | HOW TO FIX |
| *.c | include file not found. | Correct the status of STDC_HEADERS in scmfig.h. |
fix #include statement or add #define for system type to scmfig.h. | ||
| *.c | Function should return a value. | Ignore. |
| Parameter is never used. | ||
| Condition is always false. | ||
| Unreachable code in function. | ||
| scm.c | assignment between incompatible types. | Change SIGRETTYPE in scm.c. |
| time.c | CLK_TCK redefined. | incompatablility between <stdlib.h> and <sys/types.h>. |
Remove STDC_HEADERS in scmfig.h. | ||
| Edit <sys/types.h> to remove incompatability. | ||
| subr.c | Possibly incorrect assignment in function lgcd. | Ignore. |
| sys.c | statement not reached. | Ignore. |
| constant in conditional expression. | ||
| sys.c | undeclared, outside of functions. | #undef STDC_HEADERS in scmfig.h. |
| scl.c | syntax error. | #define SYSTNAME to your system type in scl.c (softtype). |
Loading r4rstest.scm in the distribution will run an [R4RS]
conformance test on scm.
> (load "r4rstest.scm")
-|
;loading r4rstest.scm
SECTION(2 1)
SECTION(3 4)
#<primitive-procedure boolean?>
#<primitive-procedure char?>
#<primitive-procedure null?>
#<primitive-procedure number?>
...
Loading pi.scm in the distribution will enable you to compute digits of pi.
> (load "pi.scm") ;loading pi.scm ;done loading pi.scm #<unspecified> > (pi 100 5) 00003 14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59230 78164 06286 20899 86280 34825 34211 70679 ;Evaluation took 550 ms (60 in gc) 36976 cells work, 1548.B other #<unspecified>
Loading bench.scm will compute and display performance statistics of SCM running pi.scm. ‘make bench’ or ‘make benchlit’ appends the performance report to the file BenchLog, facilitating tracking effects of changes to SCM on performance.
| PROBLEM | HOW TO FIX |
| /bin/bash: scm: program not found | Is ‘scm’ in a ‘$PATH’ directory? |
| /bin/bash: /usr/local/bin/scm: Permission denied | chmod +x /usr/local/bin/scm |
| Opening message and then machine crashes. | Change memory model option to C compiler (or makefile). |
Make sure sizet definition is correct in scmfig.h. | |
Reduce the size of HEAP_SEG_SIZE in setjump.h. | |
| Input hangs. | #define NOSETBUF |
| ERROR: heap: need larger initial. | Increase initial heap allocation using -a<kb> or INIT_HEAP_SIZE. |
| ERROR: Could not allocate. | Check sizet definition. |
| Use 32 bit compiler mode. | |
| Don’t try to run as subproccess. | |
| remove <FLAG> in scmfig.h and recompile scm. | Do so and recompile files. |
| add <FLAG> in scmfig.h and recompile scm. | |
| ERROR: Init5f4.scm not found. | Assign correct IMPLINIT in makefile or scmfig.h. |
Define environment variable SCM_INIT_PATH to be the full pathname of Init5f4.scm. | |
| WARNING: require.scm not found. | Define environment variable SCHEME_LIBRARY_PATH to be the full pathname of the scheme library [SLIB]. |
Change library-vicinity in Init5f4.scm to point to library or remove. | |
Make sure the value of (library-vicinity) has a trailing file separator (like / or \). |
| PROBLEM | HOW TO FIX |
| Runs some and then machine crashes. | See above under machine crashes. |
| Runs some and then ERROR: … (after a GC has happened). | Remove optimization option to C compiler and recompile. |
#define SHORT_ALIGN in scmfig.h. | |
| Some symbol names print incorrectly. | Change memory model option to C compiler (or makefile). |
Check that HEAP_SEG_SIZE fits within sizet. | |
Increase size of HEAP_SEG_SIZE (or INIT_HEAP_SIZE if it is smaller than HEAP_SEG_SIZE). | |
| ERROR: Rogue pointer in Heap. | See above under machine crashes. |
| Newlines don’t appear correctly in output files. | Check file mode (define OPEN_… in Init5f4.scm). |
| Spaces or control characters appear in symbol names. | Check character defines in scmfig.h. |
| Negative numbers turn positive. | Check SRS in scmfig.h. |
| ;ERROR: bignum: numerical overflow | Increase NUMDIGS_MAX in scmfig.h and recompile. |
| VMS: Couldn’t unwind stack. | #define CHEAP_CONTINUATIONS in scmfig.h. |
| VAX: botched longjmp. |
Reported problems and solutions are grouped under Compiling, Linking,
Running, and Testing. If you don’t find your problem listed there,
you can send a bug report to agj@alum.mit.edu or
scm-discuss@gnu.org. The bug report should include:
SCM_INIT_PATH and
SCHEME_LIBRARY_PATH.
scm [-a kbytes] [-muvbiq] [--version] [--help]
[[-]-no-init-file] [--no-symbol-case-fold] [-p int] [-r feature] [-h feature] [-d filename] [-f filename] [-l filename] [-c expression] [-e expression] [-o dumpname] [-- | - | -s] [filename] [arguments ...]
Upon startup scm loads the file specified by by the environment
variable SCM_INIT_PATH.
If SCM_INIT_PATH is not defined or if the file it names is not
present, scm tries to find the directory containing the
executable file. If it is able to locate the executable, scm
looks for the initialization file (usually
Init5f4.scm) in platform-dependent directories
relative to this directory. See File-System Habitat for a
blow-by-blow description.
As a last resort (if initialization file cannot be located), the C compile parameter IMPLINIT (defined in the makefile or scmfig.h) is tried.
Unless the option -no-init-file or --no-init-file occurs
in the command line, or if scm is being invoked as a script,
Init5f4.scm checks to see if there is file
ScmInit.scm in the path specified by the environment variable
HOME (or in the current directory if HOME is undefined).
If it finds such a file, then it is loaded.
Init5f4.scm then looks for command input from one of three sources: From an option on the command line, from a file named on the command line, or from standard input.
This explanation applies to SCMLIT or other builds of SCM.
Scheme-code files can also invoke SCM and its variants. See #!.
The options are processed in the order specified on the command line.
specifies that scm should allocate an initial heapsize of k
kilobytes. This option, if present, must be the first on the command
line. If not specified, the default is INIT_HEAP_SIZE in source
file setjump.h which the distribution sets at
25000*sizeof(cell).
Inhibits the loading of ScmInit.scm as described above.
Symbol (and identifier) names will be case sensitive.
prints usage information and URI; then exit.
prints version information and exit.
requires feature. This will load a file from [SLIB] if that
feature is not already provided. If feature is 2, 2rs, or
r2rs; 3, 3rs, or r3rs; 4, 4rs, or r4rs; 5, 5rs, or r5rs; scm
will require the features neccessary to support [R2RS]; [R3RS];
[R4RS]; or [R5RS], respectively.
provides feature.
loads filename. Scm will load the first (unoptioned)
file named on the command line if no -c, -e, -f,
-l, or -s option preceeds it.
Loads SLIB databases feature and opens filename as a
database.
specifies that the scheme expression expression is to be
evaluated. These options are inspired by perl and sh
respectively. On Amiga systems the entire option and argument need to be
enclosed in quotes. For instance ‘"-e(newline)"’.
saves the current SCM session as the executable program dumpname.
This option works only in SCM builds supporting dump
(see Dump).
If options appear on the command line after ‘-o dumpname’, then the saved session will continue with processing those options when it is invoked. Otherwise the (new) command line is processed as usual when the saved image is invoked.
sets the prolixity (verboseness) to level. This is the same as
the scm command (verobse level).
(verbose mode) specifies that scm will print prompts, evaluation
times, notice of loading files, and garbage collection statistics. This
is the same as -p3.
(quiet mode) specifies that scm will print no extra
information. This is the same as -p0.
specifies that subsequent loads, evaluations, and user interactions will
be with syntax-rules macro capability. To use a specific syntax-rules
macro implementation from [SLIB] (instead of [SLIB]’s default) put
-r macropackage before -m on the command line.
specifies that subsequent loads, evaluations, and user interactions will
be without syntax-rules macro capability. Syntax-rules macro capability
can be restored by a subsequent -m on the command line or from
Scheme code.
specifies that scm should run interactively. That means that
scm will not terminate until the (quit) or (exit)
command is given, even if there are errors. It also sets the prolixity
level to 2 if it is less than 2. This will print prompts, evaluation
times, and notice of loading files. The prolixity level can be set by
subsequent options. If scm is started from a tty, it will assume
that it should be interactive unless given a subsequent -b
option.
specifies that scm should run non-interactively. That means that
scm will terminate after processing the command line or if there
are errors.
specifies, by analogy with sh, that scm should run
interactively and that further options are to be treated as program
aguments.
specifies that further options are to be treated as program aguments.
% scm foo.scmLoads and executes the contents of foo.scm and then enters interactive session.
% scm -f foo.scm arg1 arg2 arg3Parameters arg1, arg2, and arg3 are stored in the
global list *argv*; Loads and executes the contents of
foo.scm and exits.
% scm -s foo.scm arg1 arg2Sets *argv* to ("foo.scm" "arg1" "arg2") and enters interactive
session.
% scm -e `(write (list-ref *argv* *optind*))' barPrints ‘"bar"’.
% scm -rpretty-print -r format -iLoads pretty-print and format and enters interactive
session.
% scm -r5Loads dynamic-wind, values, and syntax-rules macros and
enters interactive (with macros) session.
% scm -r5 -r4Like above but rev4-optional-procedures are also loaded.
is the pathname where scm will look for its initialization
code. The default is the file Init5f4.scm in the
source directory.
is the [SLIB] Scheme library directory.
is the directory where Init5f4.scm will look for the user initialization file ScmInit.scm.
is the name of the program which ed will call. If EDITOR
is not defined, the default is ‘ed’.
contains the list of arguments to the program. *argv* can change
during argument processing. This list is suitable for use as an argument
to [SLIB] getopt.
controls whether loading and interaction support syntax-rules
macros. Define this in ScmInit.scm or files specified on the
command line. This can be overridden by subsequent -m and
-u options.
controls interactivity as explained for the -i and -b
options. Define this in ScmInit.scm or files specified on the
command line. This can be overridden by subsequent -i and
-b options.
Aliases for exit (see exit in SLIB). On many
systems, SCM can also tail-call another program.
See execp.
boot-tail is called by scm_top_level just before entering
interactive top-level. If boot-tail calls quit, then
interactive top-level is not entered.
Returns a list of strings of the arguments scm was called with.
Returns the (login) name of the user logged in on the controlling terminal of the process, or #f if this information cannot be determined.
For documentation of the procedures getenv and system
See System Interface in SLIB.
SCM extends getenv as suggested by draft SRFI-98:
Looks up name, a string, in the program environment. If name is
found a string of its value is returned. Otherwise, #f is returned.
Returns names and values of all the environment variables as an association-list.
(getenv) ⇒
(("PATH" . "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin")
("USERNAME" . "taro"))
If SCM is compiled under VMS this vms-debug will invoke the VMS
debugger.
The value of the environment variable EDITOR (or just ed
if it isn’t defined) is invoked as a command with arguments arg1
….
If SCM is compiled under VMS ed will invoke the editor with a
single the single argument filename.
Editing of Scheme code is supported by emacs. Buffers holding files ending in .scm are automatically put into scheme-mode.
If your Emacs can run a process in a buffer you can use the Emacs command ‘M-x run-scheme’ with SCM. Otherwise, use the emacs command ‘M-x suspend-emacs’; or see “other systems” below.
There is lisp (and scheme) mode available by use of the package ‘LISP.E’. It offers several different indentation formats. With this package, buffers holding files ending in ‘.L’, ‘.LSP’, ‘.S’, and ‘.SCM’ (my modification) are automatically put into lisp-mode.
It is possible to run a process in a buffer under Epsilon. With Epsilon 5.0 the command line options ‘-e512 -m0’ are neccessary to manage RAM properly. It has been reported that when compiling SCM with Turbo C, you need to ‘#define NOSETBUF’ for proper operation in a process buffer with Epsilon 5.0.
One can also call out to an editor from SCM if RAM is at a premium; See “under other systems” below.
Define the environment variable ‘EDITOR’ to be the name of the
editing program you use. The SCM procedure (ed arg1 …)
will invoke your editor and return to SCM when you exit the editor. The
following definition is convenient:
(define (e) (ed "work.scm") (load "work.scm"))
Typing ‘(e)’ will invoke the editor with the file of interest. After editing, the modified file will be loaded.
The cautious option of build
(see Build Options) supports debugging in Scheme.
If SCM is built with the ‘CAUTIOUS’ flag, then when an error occurs, a stack trace of certain pending calls are printed as part of the default error response. A (memoized) expression and newline are printed for each partially evaluated combination whose procedure is not builtin. See Memoized Expressions for how to read memoized expressions.
Also as the result of the ‘CAUTIOUS’ flag, both error and
user-interrupt (invoked by C-c) to print stack traces and
conclude by calling breakpoint
(see Breakpoints in SLIB) instead of aborting to top
level. Under either condition, program execution can be resumed by
(continue).
In this configuration one can interrupt a running Scheme program with
C-c, inspect or modify top-level values, trace or untrace
procedures, and continue execution with (continue).
If verbose (see verbose) is called with an
argument greater than 2, then the interpreter will check stack size
periodically. If the size of stack in use exceeds the C #define
STACK_LIMIT (default is HEAP_SEG_SIZE), SCM generates a
‘stack’ segment violation.
There are several SLIB macros which so useful that SCM automatically loads the appropriate module from SLIB if they are invoked.
Traces the top-level named procedures given as arguments.
With no arguments, makes sure that all the currently traced identifiers are traced (even if those identifiers have been redefined) and returns a list of the traced identifiers.
Turns tracing off for its arguments.
With no arguments, untraces all currently traced identifiers and returns a list of these formerly traced identifiers.
The routines I use most frequently for debugging are:
Print writes all its arguments, separated by spaces.
Print outputs a newline at the end and returns the value
of the last argument.
One can just insert ‘(print '<label>’ and ‘)’ around an expression in order to see its values as a program operates.
Pprint pretty-prints (see Pretty-Print in SLIB) all
its arguments, separated by newlines. Pprint returns the value
of the last argument.
One can just insert ‘(pprint '<label>’ and ‘)’ around an
expression in order to see its values as a program operates.
Note pretty-print does not format procedures.
When typing at top level, pprint is not a good way to see
nested structure because it will return the last object
pretty-printed, which could be large. pp is a better choice.
Pprint pretty-prints (see Pretty-Print in SLIB) all
its arguments, separated by newlines. pp returns
#<unspecified>.
Writes name if supplied; then writes the names and values of the
closest lexical bindings enclosing the call to Print-args.
(define (foo a b) (print-args foo) (+ a b)) (foo 3 6) -| In foo: a = 3; b = 6; ⇒ 9
Sometimes more elaborate measures are needed to print values in a useful manner. When the values to be printed may have very large (or infinite) external representations, Quick Print in SLIB, can be used.
When trace is not sufficient to find program flow problems,
SLIB-PSD, the Portable Scheme Debugger
offers source code debugging from
GNU Emacs. PSD runs slowly, so start by instrumenting only a few
functions at a time.
http://groups.csail.mit.edu/mac/ftpdir/scm/slib-psd1-3.tar.gz ftp.maths.tcd.ie:pub/bosullvn/jacal/slib-psd1-3.tar.gz ftp.cs.indiana.edu:/pub/scheme-repository/utl/slib-psd1-3.tar.gz
These functions are defined in debug.c, all operate on captured continuations:
Prints information about the code being executed and the environment scopes active for continuation frame n of continuation CONT. A "continuation frame" is an entry in the environment stack; a new frame is pushed when the environment is replaced or extended in a non-tail call context. Frame 0 is the top of the stack.
Prints the environment for continuation frame n of continuation cont. This contains just the names, not the values, of the environment.
will print information about active lexical scopes for environment env.
Evaluates expr in the environment defined by continuation frame n of continuation CONT and returns the result. Values in the environment may be returned or SET!.
stack-trace also now accepts an optional continuation
argument. stack-trace differs from frame-trace in that
it truncates long output using safeports and prints code from all
available frames.
(define k #f) (define (foo x y) (set! k (call-with-current-continuation identity)) #f) (let ((a 3) (b 4)) (foo a b) #f) (stack-trace k) -| ;STACK TRACE 1; ((#@set! #@k (#@call-with-current-continuation #@identity)) #f ... 2; (#@let ((a 3) (b 4)) (#@foo #@a #@b) #f) ... #t
(frame-trace k 0) -| (#@call-with-current-continuation #@identity) ; in scope: ; (x y) procedure foo#<unspecified>
(frame-trace k 1) -| ((#@set! #@k (#@call-with-current-continuation #@identity)) #f) ; in scope: ; (x y) procedure foo#<unspecified>
(frame-trace k 2) -| (#@let ((a 3) (b 4)) (#@foo #@a #@b) #f) ; in scope: ; (a b . #@let)#<unspecified>
(frame-trace k 3) -| (#@let ((a 3) (b 4)) (#@foo #@a #@b) #f) ; in top level environment.
(frame->environment k 0) -| ((x y) 2 foo)
(scope-trace (frame->environment k 0)) -| ; in scope: ; (x y) procedure foo#<unspecified>
(frame-eval k 0 'x) ⇒ 3 (frame-eval k 0 '(set! x 8)) (frame-eval k 0 'x) ⇒ 8
A computer-language implementation designer faces choices of how reflexive to make the implementation in handling exceptions and errors; that is, how much of the error and exception routines should be written in the language itself. The design of a portable implementation is further constrained by the need to have (almost) all errors print meaningful messages, even when the implementation itself is not functioning correctly. Therefore, SCM implements much of its error response code in C.
The following common error and conditions are handled by C code. Those with callback names after them can also be handled by Scheme code (see Interrupts). If the callback identifier is not defined at top level, the default error handler (C code) is invoked. There are many other error messages which are not treated specially.
Wrong type in argument
Wrong type in argument 1
Wrong type in argument 2
Wrong type in argument 3
Wrong type in argument 4
Wrong type in argument 5
Wrong number of args
numerical overflow
Argument out of range
(out-of-storage)
GC is (thrashing)
(end-of-program)
(hang-up)
(user-interrupt)
(arithmetic-error)
bus error
segment violation
(alarm-interrupt)
(virtual-alarm-interrupt)
(profile-alarm-interrupt)
When SCM encounters a non-fatal error, it aborts evaluation of the
current form, prints a message explaining the error, and resumes the top
level read-eval-print loop. The value of errobj is the offending
object if appropriate. The builtin procedure error does
not set errobj.
errno and perror report ANSI C errors encountered during a
call to a system or library function.
With no argument returns the current value of the system variable
errno. When given an argument, errno sets the system
variable errno to n and returns the previous value of
errno. (errno 0) will clear outstanding errors. This is
recommended after try-load returns #f since this occurs
when the file could not be opened.
Prints on standard error output the argument string, a colon,
followed by a space, the error message corresponding to the current
value of errno and a newline. The value returned is unspecified.
warn and error provide a uniform way for Scheme code to
signal warnings and errors.
Alias for warn in SLIB. Outputs an error
message containing the arguments. warn is defined in
Init5f4.scm.
Alias for error in SLIB. Outputs an error
message containing the arguments, aborts evaluation of the current form
and resumes the top level read-eval-print loop. Error is defined
in Init5f4.scm.
If SCM is built with the ‘CAUTIOUS’ flag, then when an error occurs, a stack trace of certain pending calls are printed as part of the default error response. A (memoized) expression and newline are printed for each partially evaluated combination whose procedure is not builtin. See Memoized Expressions for how to read memoized expressions.
Also as the result of the ‘CAUTIOUS’ flag, both error and
user-interrupt (invoked by C-c) are defined to print stack
traces and conclude by calling breakpoint
(see Breakpoints in SLIB). This allows the user to
interract with SCM as with Lisp systems.
Prints information describing the stack of partially evaluated
expressions. stack-trace returns #t if any lines were
printed and #f otherwise. See Init5f4.scm
for an example of the use of stack-trace.
SCM memoizes the address of each occurence of an identifier’s value when first encountering it in a source expression. Subsequent executions of that memoized expression is faster because the memoized reference encodes where in the top-level or local environment its value is.
When procedures are displayed, the memoized locations appear in a format different from references which have not yet been executed. I find this a convenient aid to locating bugs and untested expressions.
For instance, open-input-file is defined as follows in
Init5f4.scm:
(define (open-input-file str)
(or (open-file str open_read)
(and (procedure? could-not-open) (could-not-open) #f)
(error "OPEN-INPUT-FILE couldn't open file " str)))
If open-input-file has not yet been used, the displayed procedure
is similar to the original definition (lines wrapped for readability):
open-input-file ⇒ #<CLOSURE (str) (or (open-file str open_read) (and (procedure? could-not-open) (could-not-open) #f) (error "OPEN-INPUT-FILE couldn't open file " str))>
If we open a file using open-input-file, the sections of code
used become memoized:
(open-input-file "r4rstest.scm") ⇒ #<input-port 3> open-input-file ⇒ #<CLOSURE (str) (#@or (#@open-file #@0+0 #@open_read) (and (procedure? could-not-open) (could-not-open) #f) (error "OPEN-INPUT-FILE couldn't open file " str))>
If we cause open-input-file to execute other sections of code,
they too become memoized:
(open-input-file "foo.scm") ⇒ ERROR: No such file or directory ERROR: OPEN-INPUT-FILE couldn't open file "foo.scm" open-input-file ⇒ #<CLOSURE (str) (#@or (#@open-file #@0+0 #@open_read) (#@and (#@procedure? #@could-not-open) (could-not-open) #f) (#@error "OPEN-INPUT-FILE couldn't open file " #@0+0))>
The variable *interactive* determines whether the SCM session is interactive, or should quit after the command line is processed. *interactive* is controlled directly by the command-line options ‘-b’, ‘-i’, and ‘-s’ (see Invoking SCM). If none of these options are specified, the rules to determine interactivity are more complicated; see Init5f4.scm for details.
Resumes the top level Read-Eval-Print loop.
Restarts the SCM program with the same arguments as it was originally invoked. All ‘-l’ loaded files are loaded again; If those files have changed, those changes will be reflected in the new session.
Note When running a saved executable (see Dump),
restart is redefined to be exec-self.
Exits and immediately re-invokes the same executable with the same
arguments. If the executable file has been changed or replaced since
the beginning of the current session, the new executable will be
invoked. This differentiates exec-self from restart.
Controls how much monitoring information is printed. If n is:
no prompt or information is printed.
a prompt is printed.
messages bracketing file loading are printed.
the CPU time is printed after each top level form evaluated; notifications of heap growth printed; the interpreter checks stack depth periodically.
a garbage collection summary is printed after each top level form evaluated;
a message for each GC (see Garbage Collection) is printed; warnings issued for top-level symbols redefined.
Scans all of SCM objects and reclaims for further use those that are no longer accessible.
Garbage-collects only the ecache.
Prints out statistics about SCM’s current use of storage. (room #t)
also gives the hexadecimal heap segment and stack bounds.
Contains the version string (e.g. 5f4) of SCM.
In order to dump a saved executable or to dynamically-link using DLD,
SCM must know where its executable file is. Sometimes SCM
(see Executable Pathname) guesses incorrectly the location of the
currently running executable. In that case, the correct path can be set
by calling execpath with the pathname.
Returns the path (string) which SCM uses to find the executable file whose invocation the currently running session is, or #f if the path is not set.
Sets the path to #f or newpath, respectively. The old path
is returned.
For other configuration constants and procedures See Configuration in SLIB.
In reading this section, keep in mind that the first line of a script
file has (different) meanings to SCM and the operating system
(execve).
On unix systems, a Shell-Script is a file (with execute
permissions) whose first two characters are ‘#!’. The
interpreter argument must be the pathname of the program to
process the rest of the file. The directories named by environment
variable PATH are not searched to find interpreter.
When executing a shell-script, the operating system invokes interpreter with a single argument encapsulating the rest of the first line’s contents (if not just whitespace), the pathname of the Scheme Script file, and then any arguments which the shell-script was invoked with.
Put one space character between ‘#!’ and the first character of interpreter (‘/’). The interpreter name is followed by ‘ \’; SCM substitutes the second line of file for ‘\’ (and the rest of the line), then appends any arguments given on the command line invoking this Scheme-Script.
When SCM executes the script, the Scheme variable *script* will be set to the script pathname. The last argument before ‘!#’ on the second line should be ‘-’; SCM will load the script file, preserve the unprocessed arguments, and set *argv* to a list of the script pathname and the unprocessed arguments.
Note that the interpreter, not the operating system, provides the ‘\’ substitution; this will only take place if interpreter is a SCM or SCSH interpreter.
When the first two characters of the file being loaded are #! and
a ‘\’ is present before a newline in the file, all characters up
to ‘!#’ will be ignored by SCM read.
This combination of interpretatons allows SCM source files to be used as POSIX shell-scripts if the first line is:
#! /usr/bin/scm \
The following Scheme-Script prints factorial of its argument:
#! /usr/bin/scm \ %0 %*
- !#
(define (fact.script args)
(cond ((and (= 1 (length args))
(string->number (car args)))
=> (lambda (n) (print (fact n)) #t))
(else (fact.usage))))
(define (fact.usage)
(print *argv*)
(display "\
Usage: fact N
Returns the factorial of N.
"
(current-error-port))
#f)
(define (fact n) (if (< n 2) 1 (* n (fact (+ -1 n)))))
(if *script* (exit (fact.script (list-tail *argv* *optind*))))
./fact 32 ⇒ 263130836933693530167218012160000000
If the wrong number of arguments is given, fact prints its
argv with usage information.
./fact 3 2
-|
("./fact" "3" "2")
Usage: fact N
Returns the factorial of N.
It turns out that we can create scheme-scripts which run both under unix
and MS-DOS. To implement this, I have written the MS-DOS programs:
#!.bat and !#.exe,
which are available from:
http://groups.csail.mit.edu/mac/ftpdir/scm/sharpbang.zip
With these two programs installed in a PATH directory, we have
the following syntax for <program>.BAT files.
The first two characters of the Scheme-Script are ‘#!’. The interpreter can be either a unix style program path (using ‘/’ between filename components) or a DOS program name or path. The rest of the first line of the Scheme-Script should be literally ‘\ %0 %*’, as shown.
If interpreter has ‘/’ in it, interpreter is converted to a DOS style filename (‘/’ ⇒ ‘\’).
In looking for an executable named interpreter, #! first
checks this (converted) filename; if interpreter doesn’t exist, it
then tries to find a program named like the string starting after the
last ‘\’ (or ‘/’) in interpreter. When searching for
executables, #! tries all directories named by environment
variable PATH.
Once the interpreter executable path is found, arguments are
processed in the manner of scheme-shell, with all the text after the
‘\’ taken as part of the meta-argument. More precisely, #!
calls interpreter with any options on the second line of the
Scheme-Script up to ‘!#’, the name of the Scheme-Script file, and
then any of at most 8 arguments given on the command line invoking this
Scheme-Script.
The previous example Scheme-Script works in both MS-DOS and unix systems.
Scheme-scripts suffer from two drawbacks:
The following approach solves these problems at the expense of slower
startup. Make ‘#! /bin/sh’ the first line and prepend every
subsequent line to be executed by the shell with :;. The last
line to be executed by the shell should contain an exec command;
exec tail-calls its argument.
/bin/sh is thus invoked with the name of the script file, which
it executes as a *sh script. Usually the second line starts
‘:;exec scm -f$0’, which executes scm, which in turn loads the
script file. When SCM loads the script file, it ignores the first and
second lines, and evaluates the rest of the file as Scheme source code.
The second line of the script file does not have the length restriction
mentioned above. Also, /bin/sh searches the directories listed
in the ‘PATH’ environment variable for ‘scm’, eliminating the need
to use absolute locations in order to invoke a program.
The following example additionally sets *script* to the script argument, making it compatible with the scheme code of the previous example.
#! /bin/sh
:;exec scm -e"(set! *script* \"$0\")" -l$0 "$@"
(define (fact.script args)
(cond ((and (= 1 (length args))
(string->number (car args)))
=> (lambda (n) (print (fact n)) #t))
(else (fact.usage))))
(define (fact.usage)
(print *argv*)
(display "\
Usage: fact N
Returns the factorial of N.
"
(current-error-port))
#f)
(define (fact n) (if (< n 2) 1 (* n (fact (+ -1 n)))))
(if *script* (exit (fact.script (list-tail *argv* *optind*))))
./fact 6 ⇒ 720
Scm conforms to the IEEE Standard 1178-1990. IEEE Standard for the Scheme Programming Language. (see Bibliography), and Revised(5) Report on the Algorithmic Language Scheme. All the required features of these specifications are supported. Many of the optional features are supported as well.
- and / of more than 2 argumentsexplogsincostanasinacosatansqrtexptmake-rectangularmake-polarreal-partimag-partmagnitudeangleexact->inexactinexact->exactSee Numerical operations in Revised(5) Scheme.
with-input-from-filewith-output-to-fileSee Ports in Revised(5) Scheme.
loadtranscript-ontranscript-offSee System interface in Revised(5) Scheme.
numeratordenominatorrationalizeSee Numerical operations in Revised(5) Scheme.
delayfull-continuationieee-p1178object-hashrev4-reportsourceSee SLIB file Template.scm.
current-timeSee Time and Date in SLIB.
defmacroSee Defmacro in SLIB.
getenvsystemSee System Interface in SLIB.
hashSee Hashing in SLIB.
logicalSee Bit-Twiddling in SLIB.
multiarg-applySee Multi-argument Apply in SLIB.
multiarg/and-See Multi-argument / and - in SLIB.
rev4-optional-proceduresSee Rev4 Optional Procedures in SLIB.
string-portSee String Ports in SLIB.
tmpnamSee Input/Output in SLIB.
transcriptSee Transcripts in SLIB.
vicinitySee Vicinity in SLIB.
with-fileSee With-File in SLIB.
arraySee Arrays in SLIB.
array-for-eachSee Array Mapping in SLIB.
bignumcomplexinexactrationalrealSee Require in SLIB.
Change the length of string, vector, bit-vector, or uniform-array object to length. If this shortens object then the remaining contents are lost. If it enlarges object then the contents of the extended part are undefined but the original part is unchanged. It is an error to change the length of literal datums. The new object is returned.
See copy-tree in SLIB. This extends the SLIB
version by also copying vectors. Use @copy-tree if you
depend on this feature; copy-tree could get redefined.
Returns (cons (cons obj1 obj2) obj3).
(set! a-list (acons key datum a-list))
Adds a new association to a-list.
Allows a Scheme procedure to be run shortly after each garbage collection. This procedure will not be run recursively. If it runs long enough to cause a garbage collection before returning a warning will be printed.
To remove the gc-hook, (set! gc-hook #f).
object may be any garbage collected object, that is, any object
other than an immediate integer, character, or special token such
as #f or #t, See Immediates. finalizer is
a thunk, or procedure taking no arguments.
finalizer will be invoked asynchronously exactly once some time after object becomes eligible for garbage collection. A reference to object in the environment of finalizer will not prevent finalization, but will delay the reclamation of object at least until the next garbage collection. A reference to object in some other object’s finalizer will necessarily prevent finalization until both objects are eligible for garbage collection.
Finalizers are not run in any predictable order. All finalizers will be run by the time the program ends.
This facility was based on the paper by Simon Peyton Jones, et al, “Stretching the storage manager: weak pointers and stable names in Haskell”, Proc. 11th International Workshop on the Implementation of Functional Languages, The Netherlands, September 7-10 1999, Springer-Verlag LNCS.
Is the integer number of internal time units in a second.
Returns the integer run time in internal time units from an unspecified
starting time. The difference of two calls to
get-internal-run-time divided by
internal-time-units-per-second will give elapsed run time in
seconds.
Returns the integer time in internal time units from an unspecified
starting time. The difference of two calls to
get-internal-real-time divided by
internal-time-units-per-second will give elapsed real time in
seconds.
Returns the time since 00:00:00 GMT, January 1, 1970, measured in
seconds. See current-time in SLIB. current-time is
used in Time and Date in SLIB.
Returns the number of ticks remaining till the next tick interrupt. Ticks are an arbitrary unit of evaluation. Ticks can vary greatly in the amount of time they represent.
If n is 0, any ticks request is canceled. Otherwise a
ticks-interrupt will be signaled n from the current time.
ticks is supported if SCM is compiled with the ticks flag
defined.
Establishes a response for tick interrupts. Another tick interrupt will
not occur unless ticks is called again. Program execution will
resume if the handler returns. This procedure should (abort) or some
other action which does not return if it does not want processing to
continue.
Returns the number of seconds remaining till the next alarm interrupt.
If secs is 0, any alarm request is canceled. Otherwise an
alarm-interrupt will be signaled secs from the current
time. ALARM is not supported on all systems.
milli-alarm is similar to alarm, except that the first
argument millisecs, and the return value are measured in
milliseconds rather than seconds. If the optional argument
interval is supplied then alarm interrupts will be scheduled every
interval milliseconds until turned off by a call to
milli-alarm or alarm.
virtual-alarm and profile-alarm are similar.
virtual-alarm decrements process execution time rather than real
time, and causes SIGVTALRM to be signaled.
profile-alarm decrements both process execution time and
system execution time on behalf of the process, and causes
SIGPROF to be signaled.
milli-alarm, virtual-alarm, and profile-alarm are
supported only on systems providing the setitimer system call.
Establishes a response for SIGINT (control-C interrupt) and
SIGALRM, SIGVTALRM, and SIGPROF interrupts.
Program execution will resume if the handler returns. This procedure
should (abort) or some other action which does not return if it
does not want processing to continue after it returns.
Interrupt handlers are disabled during execution system and
ed procedures.
To unestablish a response for an interrupt set the handler symbol to
#f. For instance, (set! user-interrupt #f).
Establishes a response for storage allocation error, file opening error, end of program, SIGHUP (hang up interrupt) and arithmetic errors respectively. This procedure should (abort) or some other action which does not return if it does not want the default error message to also be displayed. If no procedure is defined for hang-up then end-of-program (if defined) will be called.
To unestablish a response for an error set the handler symbol to
#f. For instance, (set! could-not-open #f).
An exchanger is a procedure of one argument regulating mutually exclusive access to a resource. When a exchanger is called, its current content is returned, while being replaced by its argument in an atomic operation.
Returns a new exchanger with the argument obj as its initial content.
(define queue (make-exchanger (list a)))
A queue implemented as an exchanger holding a list can be protected from reentrant execution thus:
(define (pop queue)
(let ((lst #f))
(dynamic-wind
(lambda () (set! lst (queue #f)))
(lambda () (and lst (not (null? lst))
(let ((ret (car lst)))
(set! lst (cdr lst))
ret)))
(lambda () (and lst (queue lst))))))
(pop queue) ⇒ a
(pop queue) ⇒ #f
Returns an object of type arbiter and name name. Its state is initially unlocked.
Returns #t and locks arbiter if arbiter was unlocked.
Otherwise, returns #f.
Returns #t and unlocks arbiter if arbiter was locked.
Otherwise, returns #f.
These procedures generalize and extend the standard capabilities in Ports in Revised(5) Scheme.
Returns a port capable of receiving or delivering characters as
specified by the modes string. If a file cannot be opened
#f is returned.
Internal functions opening files callback to the SCM function
open-file. You can extend open-file by redefining it.
try-open-file is the primitive procedure; Do not redefine
try-open-file!
Contain modes strings specifying that a file is to be opened for reading, writing, and both reading and writing respectively.
Both input and output functions can be used with io-ports. An end of file must be read or a two-argument file-position done on the port between a read operation and a write operation or vice-versa.
Returns a version of modestr which when open-file is called
with it as the second argument will return an unbuffered port. An
input-port must be unbuffered in order for char-ready? and
wait-for-input to work correctly on it. The initial value of
(current-input-port) is unbuffered if the platform supports it.
Returns a version of modestr which when open-file is called
with it as the second argument will return a tracked port. A tracked
port maintains current line and column numbers, which may be queried
with port-line and port-column.
Returns a version of modestr which when open-file is called
with it as the second argument will return a port only if the named file
does not already exist. This functionality is provided by calling
try-create-file See I/O-Extensions, which is not available
for all platforms.
Returns a list of all currently open ports, excluding string ports, see See String Ports in SLIB. This may be useful after a fork See Posix Extensions, or for debugging. Bear in mind that ports that would be closed by gc will be kept open by a reference to this list.
Closes port. The same as close-input-port and close-output-port.
Returns #t if port is closed.
If obj is not a port returns false, otherwise returns a symbol describing the port type, for example string or pipe.
Returns the filename port was opened with. If port is not open to a file the result is unspecified.
Returns the current position of the character in port which will
next be read or written. If port is open to a non-file then
#f is returned.
Sets the current position in port which will next be read or
written. If successful, #f is returned. If port is open
to a non-file, then file-position returns #f.
If port is a tracked port, return the current line (column) number,
otherwise return #f. Line and column numbers begin with 1.
The column number applies to the next character to be read; if that
character is a newline, then the column number will be one more than
the length of the line.
Outputs a newline to optional argument port unless the current
output column number of port is known to be zero, ie output will
start at the beginning of a new line. port defaults to
current-output-port. If port is not a tracked port
freshline is equivalent to newline.
Returns #t if port is input or output to a serial non-file
device.
Returns #t if a character is ready on the input port and
returns #f otherwise. If char-ready? returns #t
then
the next read-char operation on the given port is
guaranteed
not to hang. If the port is at end of file then
char-ready? returns #t.
Port may be omitted, in which case it defaults to
the value returned by current-input-port.
Rationale Char-ready? exists to make it possible for a
program to
accept characters from interactive ports without getting stuck waiting
for input. Any input editors associated with such ports must ensure
that characters whose existence has been asserted by char-ready?
cannot be rubbed out. If char-ready? were to return #f at
end of file, a port at end of file would be indistinguishable from an
interactive port that has no ready characters.
Returns a list those ports port1 … which are char-ready?.
If none of port1 … become char-ready? within the time
interval of x seconds, then #f is returned. The
port1 … arguments may be omitted, in which case they default
to the list of the value returned by current-input-port.
Returns the current port to which diagnostic output is directed.
thunk must be a procedure of no arguments, and string must be a string naming a file. The file is opened for output, an output port connected to it is made the default value returned by current-error-port, and the thunk is called with no arguments. When the thunk returns, the port is closed and the previous default is restored. With-error-to-file returns the value yielded by thunk.
These routines differ from with-input-from-file, with-output-to-file, and with-error-to-file in that the first argument is a port, rather than a string naming a file.
Calls the thunk procedure while the current-output-port and current-error-port are directed to string-ports. If thunk returns, the proc procedure is called with the output-string, the error-string, and the value returned by thunk. If thunk does not return a value (perhaps because of error), proc is called with just the output-string and the error-string as arguments.
A soft-port is a port based on a vector of procedures capable of accepting or delivering characters. It allows emulation of I/O ports.
Returns a port capable of receiving or delivering characters as specified by the modes string (see open-file). vector must be a vector of length 5. Its components are as follows:
For an output-only port only elements 0, 1, 2, and 4 need be
procedures. For an input-only port only elements 3 and 4 need be
procedures. Thunks 2 and 4 can instead be #f if there is no useful
operation for them to perform.
If thunk 3 returns #f or an eof-object
(see eof-object? in Revised(5) Scheme) it indicates
that the port has reached end-of-file. For example:
If it is necessary to explicitly close the port when it is garbage collected, (see add-finalizer).
(define stdout (current-output-port))
(define p (make-soft-port
(vector
(lambda (c) (write c stdout))
(lambda (s) (display s stdout))
(lambda () (display "." stdout))
(lambda () (char-upcase (read-char)))
(lambda () (display "@" stdout)))
"rw"))
(write p p) ⇒ #<input-output-soft#\space45d10#\>
If the string filename names an existing file, the try-load
procedure reads Scheme source code expressions and definitions from the
file and evaluates them sequentially and returns #t. If not,
try-load returns #f. The try-load procedure does not affect the
values returned by current-input-port and
current-output-port.
Is set to the pathname given as argument to load,
try-load, and dyn:link
(see Compiling And Linking in Hobbit).
*load-pathname* is used to compute the value of
program-vicinity in SLIB.
Returns the result of reading an expression from str and
evaluating it. eval-string does not change
*load-pathname* or line-number.
Reads and evaluates all the expressions from str. As with
load, the value returned is unspecified. load-string does
not change *load-pathname* or line-number.
Returns the current line number of the file currently being loaded.
Scheme code defined by load may optionally contain line number information. Currently this information is used only for reporting expansion time errors, but in the future run-time error messages may also include line number information.
This is the primitive for loading, pathname is the name of
a file containing Scheme code, and optional argument reader is
a function of one argument, a port. reader should read and
return Scheme code as list structure. The default value is read,
which is used if reader is not supplied or is false.
Line number objects are disjoint from integers or other Scheme types. When evaluated or loaded as Scheme code, an s-expression containing a line-number in the car is equivalent to the cdr of the s-expression. A pair consisting of a line-number in the car and a vector in the cdr is equivalent to the vector. The meaning of s-expressions with line-numbers in other positions is undefined.
Behaves like read, except that
Returns a line-number object with value int. int should be an exact non-negative integer.
Returns the value of line-number object linum as an integer.
Returns true if and only if obj is a line-number object.
Behaves like read, except that load syntaxes are enabled.
The value of *load-reader* should be a value acceptable as
the second argument to try-load (note that #f is acceptable).
This value will be used to read code during calls to scm:load.
The value of *slib-load-reader* will similarly be used during
calls to slib:load and require.
In order to disable all line-numbering, it is sufficient to set!
*load-reader* and *slib-load-reader* to #f.
If token is a sequence of two or more digits, then this syntax is
equivalent to #.(integer->char (string->number token 8)).
If token is C-, c-, or ^ followed by a
character, then this syntax is read as a control character. If
token is M- or m- followed by a character, then a
meta character is read. c- and m- prefixes may be
combined.
If feature is provided? then form is read as a scheme
expression. If not, then form is treated as whitespace.
Feature is a boolean expression composed of symbols and and,
or, and not of boolean expressions.
For more information on provided?,
See Require in SLIB.
is equivalent to #+(not feature) expression.
Is a balanced comment. Everything up to the matching |# is
ignored by the read. Nested #|…|# can occur inside
any thing.
Load sytax is Read syntax enabled for read only when that
read is part of loading a file or string. This distinction was
made so that reading from a datafile would not be able to corrupt a
scheme program using ‘#.’.
Is read as the object resulting from the evaluation of expression. This substitution occurs even inside quoted structure.
In order to allow compiled code to work with #. it is good
practice to define those symbols used inside of expression with
#.(define …). For example:
#.(define foo 9) ⇒ #<unspecified> '(#.foo #.(+ foo foo)) ⇒ (9 18)
is equivalent to form (for compatibility with common-lisp).
#! is the unix mechanism for executing scripts. See Unix Scheme Scripts for the full description of how this comment supports scripting.
Return integers for the current line and column being read during a load.
Returns the string naming the file currently being loaded. This path
is the string passed to load, possibly with ‘.scm’
appended.
Returns the documentation string of proc if it exists, or
#f if not.
If the body of a lambda (or the definition of a procedure) has
more than one expression, and the first expression (preceeding any
internal definitions) is a string, then that string is the
documentation string of that procedure.
(procedure-documentation (lambda (x) "Identity" x)) ⇒ "Identity"
(define (square x)
"Return the square of X."
(* x x))
⇒ #<unspecified>
(procedure-documentation square) ⇒ "Return the square of X."
Appends string1 … to the strings given as arguments to
previous calls comment.
Returns the (appended) strings given as arguments to previous calls
comment and empties the current string collection.
Behaves as (comment "text-till-end-of-line").
If a # followed by a character (for a non-standard syntax) is
encountered by read, read will call the value of the
symbol read:sharp with arguments the character and the port being
read from. The value returned by this function will be the value of
read for this expression unless the function returns
#<unspecified> in which case the expression will be treated as
whitespace. #<unspecified> is the value returned by the
expression (if #f #f).
Dispatches like read:sharp, but only during loads. The
read-syntaxes handled by load:sharp are a superset of those
handled by read:sharp. load:sharp calls
read:sharp if none of its syntaxes match c.
If the sequence #\ followed by a non-standard character name is
encountered by read, read will call the value of the
symbol char:sharp with the token (a string of length at
least two) as argument. If the value returned is a character, then that
will be the value of read for this expression, otherwise an error
will be signaled.
Note When adding new # syntaxes, have your code save the
previous value of load:sharp, read:sharp, or
char:sharp when defining it. Call this saved value if an
invocation’s syntax is not recognized. This will allow #+,
#-, and Uniform Arrays to still be supported (as they
dispatch from read:sharp).
SCM provides a native implementation of defmacro. See Defmacro in SLIB.
When built with ‘-F macro’ build option (see Build Options) and
‘*syntax-rules*’ is non-false, SCM also supports [R5RS]
syntax-rules macros. See Macros in Revised(5) Scheme.
Other Scheme Syntax Extension Packages from SLIB can be employed through the use of ‘macro:eval’ and ‘macro:load’; Or by using the SLIB read-eval-print-loop:
(require 'repl) (repl:top-level macro:eval)
With the appropriate catalog entries (see Library Catalogs in SLIB), files using macro packages will automatically use the correct macro loader when ‘require’d.
Equivalent to #t if symbol is a syntactic keyword (such as
if) or a symbol with a value in the top level environment
(see Variables and regions in Revised(5) Scheme). Otherwise
equivalent to #f.
If identifier is unbound in the top level environment, then
identifier is defined to the result of evaluating the form
initial-value as if the defvar form were instead the form
(define identifier initial-value) . If identifier already
has a value, then initial-value is not evaluated and
identifier’s value is not changed. defvar is valid only
when used at top-level.
If identifier is unbound in the top level environment, then
identifier is defined to the result of evaluating the form
value as if the defconst form were instead the form
(define identifier value) . If identifier already has a
value, then value is not evaluated, identifier’s
value is not changed, and an error is signaled. defconst is
valid only when used at top-level.
The identifiers variable1, variable2, … must be bound either in some region enclosing the ‘set!’ expression or at top level.
<Expression> is evaluated, and the elements of the resulting list are stored in the locations to which each corresponding variable is bound. The result of the ‘set!’ expression is unspecified.
(define x 2) (define y 3) (+ x y) ⇒ 5 (set! (x y) (list 4 5)) ⇒ unspecified (+ x y) ⇒ 9
qase is an extension of standard Scheme case: Each
clause of a qase statement must have as first element a
list containing elements which are:
A qase statement is equivalent to a case statement in
which these symbolic constants preceded by commas have been replaced by
the values of the constants, and all symbolic constants preceded by
comma-at-signs have been replaced by the elements of the list values of
the constants. This use of comma, (or, equivalently, unquote) is
similar to that of quasiquote except that the unquoted
expressions must be symbolic constants.
Symbolic constants are defined using defconst, their values are
substituted in the head of each qase clause during macro
expansion. defconst constants should be defined before use.
qase can be substituted for any correct use of case.
(defconst unit '1)
(defconst semivowels '(w y))
(qase (* 2 3)
((2 3 5 7) 'prime)
((,unit 4 6 8 9) 'composite)) ==> composite
(qase (car '(c d))
((a) 'a)
((b) 'b)) ==> unspecified
(qase (car '(c d))
((a e i o u) 'vowel)
((,@semivowels) 'semivowel)
(else 'consonant)) ==> consonant
SCM supports the following constructs from Common Lisp:
defmacro, macroexpand, macroexpand-1, and
gentemp. See Defmacro in SLIB.
SCM defmacro is extended over that described for SLIB:
(defmacro (macro-name . arguments) body)
is equivalent to
(defmacro macro-name arguments body)
As in Common Lisp, an element of the formal argument list for
defmacro may be a possibly nested list, in which case the
corresponding actual argument must be a list with as many members as the
formal argument. Rest arguments are indicated by improper lists, as in
Scheme. It is an error if the actual argument list does not have the
tree structure required by the formal argument list.
For example:
(defmacro (let1 ((name value)) . body)
`((lambda (,name) ,@body) ,value))
(let1 ((x (foo))) (print x) x) ≡ ((lambda (x) (print x) x) (foo))
(let1 not legal syntax) error→ not "does not match" ((name value))
SCM supports [R5RS] syntax-rules macros
See Macros in Revised(5) Scheme.
The pattern language is extended by the syntax (... <obj>), which
is identical to <obj> except that ellipses in <obj> are
treated as ordinary identifiers in a template, or as literals in a
pattern. In particular, (... ...) quotes the ellipsis token
... in a pattern or template.
For example:
(define-syntax check-tree
(syntax-rules ()
((_ (?pattern (... ...)) ?obj)
(let loop ((obj ?obj))
(or (null? obj)
(and (pair? obj)
(check-tree ?pattern (car obj))
(loop (cdr obj))))))
((_ (?first . ?rest) ?obj)
(let ((obj ?obj))
(and (pair? obj)
(check-tree ?first (car obj))
(check-tree ?rest (cdr obj)))))
((_ ?atom ?obj) #t)))
(check-tree ((a b) ...) '((1 2) (3 4) (5 6))) ⇒ #t
(check-tree ((a b) ...) '((1 2) (3 4) not-a-2list) ⇒ #f
Note that although the ellipsis is matched as a literal token in the
defined macro it is not included in the literals list for
syntax-rules.
The pattern language is also extended to support identifier macros. A reference to an identifier macro keyword that is not the first identifier in a form may expand into Scheme code, rather than raising a “keyword as variable” error. The pattern for expansion of such a bare macro keyword is a single identifier, as in other syntax rules the identifier is ignored.
For example:
(define-syntax eight
(syntax-rules ()
(_ 8)))
(+ 3 eight) ⇒ 11
(eight) ⇒ ERROR
(set! eight 9) ⇒ ERROR
Returns a macro which, when a symbol defined to this value appears as the first symbol in an expression, returns the result of applying proc to the expression and the environment.
Returns a macro which, when a symbol defined to this value appears
as the first symbol in an expression, evaluates the result of applying
proc to the expression and the environment. The value returned
from proc which has been passed to
PROCEDURE->MEMOIZING-MACRO replaces the form passed to
proc. For example:
(defsyntax trace (procedure->macro (lambda (x env) `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x)))))) (trace foo) ≡ (set! foo (tracef foo 'foo)).
PROCEDURE->IDENTIFIER-MACRO is similar to
PROCEDURE->MEMOIZING-MACRO except that proc is also
called in case the symbol bound to the macro appears in an expression
but not as the first symbol, that is, when it looks like a
variable reference. In that case, the form passed to proc is
a single identifier.
Defines name as a macro keyword bound to the result of evaluating
expr, which should be a macro. Using define for this
purpose may not result in name being interpreted as a macro
keyword.
An environment is a list of frames representing lexical bindings. Only the names and scope of the bindings are included in environments passed to macro expanders – run-time values are not included.
There are several types of environment frames:
((lambda (variable1 …) …) value1 …)(let ((variable1 value1) (variable2 value2) …) …)(letrec ((variable1 value1) …) …)result in a single enviroment frame:
(variable1 variable2 ...)
(let ((variable1 value1)) …)(let* ((variable1 value1) …) …)result in an environment frame for each variable:
variable1 variable2 ...
(let-syntax ((key1 macro1) (key2 macro2)) …)(letrec-syntax ((key1 value1) (key2 value2)) …)Lexically bound macros result in environment frames consisting of a marker and an alist of keywords and macro objects:
(<env-syntax-marker> (key1 . value1) (key2 . value2))
Currently <env-syntax-marker> is the integer 6.
line numbersLine numbers (see Line Numbers) may be included in the environment as frame entries to indicate the line number on which a function is defined. They are ignored for variable lookup.
#<line 8>
miscellaneousDebugging information is stored in environments in a plist format: Any exact integer stored as an environment frame may be followed by any value. The two frame entries are ignored when doing variable lookup. Load file names, procedure names, and closure documentation strings are stored in this format.
<env-filename-marker> "foo.scm" <env-procedure-name-marker> foo ...
Currently <env-filename-marker> is the integer 1 and <env-procedure-name-marker> the integer 2.
Returns the result of applying procedure to argument-list.
@apply differs from apply when the identifiers bound by
the closure being applied are set!; setting affects
argument-list.
(define lst (list 'a 'b 'c)) (@apply (lambda (v1 v2 v3) (set! v1 (cons v2 v3))) lst) lst ⇒ ((b . c) b c)
Thus a mutable environment can be treated as both a list and local bindings.
SCM provides a synthetic identifier type for efficient implementation of
hygienic macros (for example, syntax-rules
see Macros in Revised(5) Scheme) A synthetic identifier
may be inserted in Scheme code by a macro expander in any context
where a symbol would normally be used. Collectively, symbols and
synthetic identifiers are identifiers.
Returns #t if obj is a symbol or a synthetic
identifier, and #f otherwise.
If it is necessary to distinguish between symbols and synthetic identifiers,
use the predicate symbol?.
A synthetic identifier includes two data: a parent, which is an
identifier, and an environment, which is either #f or a lexical
environment which has been passed to a macro expander
(a procedure passed as an argument to procedure->macro,
procedure->memoizing-macro, or procedure->syntax).
Returns a synthetic identifier. parent must be an identifier, and
env must either be #f or a lexical environment passed to a
macro expander. renamed-identifier returns a distinct object for
each call, even if passed identical arguments.
There is no direct way to access all of the data internal to a synthetic identifier, those data are used during variable lookup. If a synthetic identifier is inserted as quoted data then during macro expansion it will be repeatedly replaced by its parent, until a symbol is obtained.
Returns the symbol obtained by recursively extracting the parent of id, which must be an identifier.
renamed-identifier may be used as a replacement for gentemp:
(define gentemp
(let ((name (string->symbol "An unlikely variable")))
(lambda ()
(renamed-identifier name #f))))
If an identifier returned by this version of gentemp is inserted
in a binding position as the name of a variable then it is guaranteed
that no other identifier (except one produced by passing the first to
renamed-identifier) may denote that variable. If an identifier
returned by gentemp is inserted free, then it will denote the
top-level value bound to its parent, the symbol named “An unlikely
variable”. This behavior, of course, is meant to be put to good use:
(define top-level-foo
(procedure->memoizing-macro
(lambda (exp env)
(renamed-identifier 'foo #f))))
Defines a macro which may always be used to refer to the top-level binding
of foo.
(define foo 'top-level) (let ((foo 'local)) (top-level-foo)) ⇒ top-level
In other words, we can avoid capturing foo.
If a lexical environment is passed as the second argument to
renamed-identifier then if the identifier is inserted free
its parent will be looked up in that environment, rather than in
the top-level environment. The use of such an identifier must
be restricted to the lexical scope of its environment.
There is another restriction imposed for implementation convenience:
Macros passing their lexical environments to renamed-identifier
may be lexically bound only by the special forms let-syntax or
letrec-syntax. No error is signaled if this restriction is not
met, but synthetic identifier lookup will not work properly.
In order to maintain referential transparency it is necessary to
determine whether two identifiers have the same denotation. With
synthetic identifiers it is not necessary that two identifiers be
eq? in order to denote the same binding.
Returns #t if identifiers id1 and id2 denote the same
binding in lexical environment env, and #f otherwise.
env must either be a lexical environment passed to a macro transformer
during macro expansion or the empty list.
For example,
(define top-level-foo?
(procedure->memoizing-macro
(let ((foo-name (renamed-identifier 'foo #f)))
(lambda (exp env)
(identifier-equal? (cadr exp) foo-name env)))))
(top-level-foo? foo) ⇒ #t
(let ((foo 'local))
(top-level-foo? foo)) ⇒ #f
If the car of expr denotes a macro in env, then
if that macro is a primitive, expr will be returned, if the
macro was defined in Scheme, then a macro expansion will be returned.
If the car of expr does not denote a macro, the #f
is returned.
Returns a new environment object, equivalent to env, which must
either be an environment object or null, extended by one frame.
names must be an identifier, or an improper list of identifiers,
usable as a formals list in a lambda expression. values
must be a list of objects long enough to provide a binding for each of
the identifiers in names. If names is an identifier or an
improper list then vals may be, respectively, any object or an
improper list of objects.
Synthetic identifiers are converted to their parent symbols by quote
and quasiquote so that literal data in macro definitions will be
properly transcribed. syntax-quote behaves like quote, but
preserves synthetic identifier intact.
the-macro is the simplest of all possible macro transformers:
mac may be a syntactic keyword (macro name) or an expression
evaluating to a macro, otherwise an error is signaled. mac is
evaluated and returned once only, after which the same memoizied value is
returned.
the-macro may be used to protect local copies of macros against
redefinition, for example:
(@let-syntax ((let (the-macro let)))
;; code that will continue to work even if LET is redefined.
...)
A low-level “explicit renaming” macro facility very similar to that
proposed by W. Clinger [Exrename] is supported. Syntax may be defined
in define-syntax, let-syntax, and letrec-syntax
using renaming-transformer instead of syntax-rules.
proc should evaluate to a procedure accepting three arguments:
expr, rename, and compare. expr is a
representation of Scheme code to be expanded, as list structure.
rename is a procedure accepting an identifier and returning an
identifier renamed in the definition environment of the new syntax.
compare accepts two identifiers and returns true if and only if
both denote the same binding in the usage environment of the new syntax.