.\" t '\" vim:set syntax=groff:
.\"Copyright (C) 2009-2016 Kaz Kylheku <kaz@kylheku.com>.
.\"All rights reserved.
.\"
.\"BSD License:
.\"
.\"Redistribution and use in source and binary forms, with or without
.\"modification, are permitted provided that the following conditions
.\"are met:
.\"
.\"  1. Redistributions of source code must retain the above copyright
.\"     notice, this list of conditions and the following disclaimer.
.\"  2. Redistributions in binary form must reproduce the above copyright
.\"     notice, this list of conditions and the following disclaimer in
.\"     the documentation and/or other materials provided with the
.\"     distribution.
.\"  3. The name of the author may not be used to endorse or promote
.\"     products derived from this software without specific prior
.\"     written permission.
.\"
.\"THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
.\"IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
.\"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
.\"
.\" Useful groff definitions.
.\"
.\" Some constants that depend on troff/nroff mode:
.ie n \{\
.ds vspc 1
.\}
.el \{\
.ds vspc 0.5
.\}
.\" Mount numeric fonts when not running under man2html
.if !\n(M2 \{\
. fp 4 CR
. fp 5 CI
.\}
.\" Base font
.nr fsav 1
.\" start of code block: switch to monospace font
.de cblk
.  ft 4
..
.\" end of code block: restore font
.de cble
.  ft 1
..
.\" typeset argument in monospace
.\" .code x  ->  \f[CR]x\f[]
.de code
\f[4]\\$1\f[]
..
.\" like .code typesets meta-syntax
.\" which is done in angle brackets in nroff or oblique
.\" courier in PDF/HTML.
.de meta
.  ie n \{\
<\\$1>
.  \}
.  el \{\
\f[5]\\$1\f[]
.  \}
..
.\" like .meta but tack on second argument with no space.
.de metn
.  ie n \{\
<\\$1>\\$2
.  \}
.  el \{\
\f[5]\\$1\f[]\\$2
.  \}
..
.\" like .code but wraps in quotes
.\" .str x y z ->  \f[CR]"x y z"\f[].
.de str
\f[4]"\\$*"\f[]
..
.\" wrap first argument in quotes, tack no second one with no space
.\" .strn x y ->  \f[CR]"x"\f[]y.
.de strn
\f[4]"\\$1"\f[]\\$2
..
.\" like .IP but use monospace too
.de coIP
.  IP "\\f[4]\\$*\\f[]"
..
.\" Directive heading
.de dir
.  NP* The \f[4]\\$1\f[] directive
..
.\" Multiple directive heading
.de dirs
.  ds s "
.  while (\\n[.$]>2) \{\
.    as s \f[4]\\$1\f[], 
.    shift
.  \}
.  if (\\n[.$]>1) \{\
.    as s \f[4]\\$1\f[] 
.    shift
.  \}
.  if (\\n[.$]>0) \{\
.    as s and \f[4]\\$1\f[]
.  \}
.  NP* The \\*s directives
..
.\" heading with code in position 1
.de c1NP
.  ds s \\f[4]\\$1\\f[]
.  shift
.  as s " \\$*
.  NP* \\*s
..
.\" utility macro for gathering material into "s" string.
.\" a pair of arguments "@ arg" becomes arg set in code
.\" a pair of arguments "@, arg" becomes "arg," where
.\" arg is set in code, followed by comma not in code.
.de gets
.  ds s "
.  while (\\n[.$]>0) \{\
.    ie "\\$1"@" \{\
.      shift
.      as s \f[4]\\$1\f[] 
.      shift
.    \}
.    el \{\
.      ie "\\$1"@," \{\
.        shift
.        as s \f[4]\\$1\f[], 
.        shift
.      \}
.      el \{\
.        as s \\$1 
.        shift
.      \}
.    \}
.  \}
..
.\" a macro for gathering material into "s"
.\" a pair of arguments "< arg" is typeset like
.\" .meta arg. "<< arg arg" is like .metn arg arg.
.ie n \{\
.  de getm
.    ds s "
.    while (\\n[.$]>0) \{\
.      ie "\\$1"<" \{\
.        shift
.        as s <\\$1> 
.        shift
.      \}
.      el \{\
.        ie "\\$1"<<" \{\
.          shift
.          as s <\\$1>\\$2 
.          shift
.          shift
.        \}
.        el \{\
.          ie "\\$1">>" \{\
.            shift
.            as s \\$1<\\$2> 
.            shift
.            shift
.          \}
.          el \{\
.            ie "\\$1"<>" \{\
.              shift
.              as s \\$1<\\$2>\\$3 
.              shift
.              shift
.              shift
.            \}
.            el \{\
.              as s \\$1 
.              shift
.            \}
.          \}
.        \}
.      \}
.    \}
.  .
.\}
.el \{\
.  de getm
.    ds s "
.    while (\\n[.$]>0) \{\
.      ie "\\$1"<" \{\
.        shift
.        as s \\f5\\$1\\f4 
.        shift
.      \}
.      el \{\
.        ie "\\$1"<<" \{\
.          shift
.          as s \\f5\\$1\\f4\\$2 
.          shift
.          shift
.        \}
.        el \{\
.          ie "\\$1">>" \{\
.            shift
.            as s \\$1\\f5\\$2\\f4 
.            shift
.            shift
.          \}
.          el \{\
.            ie "\\$1"<>" \{\
.              shift
.              as s \\$1\\f5\\$2\f4\\$3 
.              shift
.              shift
.              shift
.            \}
.            el \{\
.              as s \\$1 
.              shift
.            \}
.          \}
.        \}
.      \}
.    \}
.  .
.\}
.\" typeset left argument in monospace, then right one
.\" in previous font, with no space between.
.\" .codn x y \f[CR]x\f[]y
.de codn
\f[4]\\$1\f[]\\$2
..
.\" .cod1 a b c ->  abc  where a is typeset as code
.de cod1
\&\\$1\f[4]\\$2\f[]\$3
..
.\" .cod2 a b ->  ab  where b is typeset as code
.de cod2
\&\\$1\f[4]\\$2\f[]
..
.\" .cod3 a b c ->  abc  where a and c are typeset as code
.de cod3
\f[4]\\$1\f[]\\$2\f[4]\\$3\f[]
..
.\" Syntax section markup
.de synb
.  TP* Syntax:
.  cblk
..
.de syne
.  cble
..
.\" Used for meta-variables in syntax blocks
.de mets
.  nr fsav \\n[.f]
.  getm \\$*
.  \"workaround for man2html:
.  as s \\f\\n[fsav]
  \\*s
.  ft \\n[fsav]
..
.\" Used for meta-variables in inline blocks
.de meti
.  nr fsav \\n[.f]
.  getm \\$*
.  \"workaround for man2html:
.  as s \\f\\n[fsav]
\&\\*s
.  ft \\n[fsav]
..
.\" Used for meta-variables in .coIP
.de meIP
.  nr fsav \\n[.f]
.  getm \\$*
.  \"workaround for man2html:
.  as s \\f\\n[fsav]
.coIP \\*s
.  ft \\n[fsav]
..
.\" Description section
.de desc
.  TP* Description:
..
.\" Section counters: heading, section, paragraph.
.nr shco 0 1
.nr ssco 0 1
.nr spco 0 1
.\" wrapper for .SH
.de SH*
.  SH \\n+[shco] \\$*
.  rs
.  nr ssco 0
.  nr spco 0
.  sp \*[vspc]
.  ns
..
.\" wrapper for .SS
.de SS*
.  SS \\n[shco].\\n+[ssco] \\$*
.  rs
.  nr spco 0
.  sp \*[vspc]
.  ns
..
.\" wrapper for .TP
.de TP*
.  ds s \\$1
.  shift
.  TP \\$*
\&\\*s
.  sp \*[vspc]
.  ns
..
.\" numbered paragraph
.de NP*
.  ie \n(M2 \{\
.  M2SS 2 h4 "\\n[shco].\\n[ssco].\\n+[spco] \\$*"
.  \}
.  el \{\
.  TP* "\f[B]\\n[shco].\\n[ssco].\\n+[spco] \\$*\f[]"
.  \}
.  PP
..
.\" process arguments using .gets so that some material
.\" is typeset as code. Then pass to .SS* section macro.
.de coSS
.  gets \\$*
.  SS* \\*s
..
.\" like coSS but targeting NP*
.de coNP
.  gets \\$*
.  NP* \\*s
..
.\" like coSS but use monospace IP
.de ccIP
.  gets \\$*
.  IP "\\*s"
..
.\" TXR name
.ds TX \f[B]TXR\f[]
.ds TL \f[B]TXR Lisp\f[]
.\" Start of man page:
.TH TXR 1 2016-05-20 "Utility Commands" "TXR Data Processing Language" "Kaz Kylheku"
.SH* NAME
\*(TX \- text processing language (version 141)

.SH* SYNOPSIS
.cblk
.meti txr >> [ options ] < query-file < data-files ..
.cble

.SH* DESCRIPTION
\*(TX is a language oriented toward processing text from files or streams, using
multiple programming paradigms.

A \*(TX script is called a query, and it specifies a pattern which matches (a
prefix of) an entire file, or multiple files.  Patterns can consists of large
chunks of multi-line free-form text, which is matched literally against
material in the input sources. Free variables occurring in the pattern
(denoted by the
.code @
symbol) are bound to the pieces of text occurring in the
corresponding positions. If the overall match is successful, then
\*(TX can do one of two things: it can report the list of variables which were
bound, in the form of a set of variable assignments which can be evaluated by
the
.B eval
command of the POSIX shell language, or generate a custom report according
to special directives in the query. Patterns can be arbitrarily complex,
and can be broken down into named pattern functions, which may be mutually
recursive. \*(TX patterns can work horizontally (characters within a line)
or vertically (spanning multiple lines). Multiple lines can be treated
as a single line.


In addition to embedded variables which implicitly match text, the
\*(TX query language supports a number of directives, for matching text using
regular expressions, for continuing a match in another file, for searching
through a file for the place where an entire sub-query matches, for collecting
lists, and for combining sub-queries using logical conjunction, disjunction and
negation, and numerous others.

Furthermore, embedded within \*(TX is a powerful Lisp dialect.  \*(TL supports
functional and imperative programming, and provides data types such as symbols,
strings, vectors, hash tables with weak reference support, lazy lists, and
arbitrary-precision (bignum integers).

.SH* ARGUMENTS AND OPTIONS

Options which don't take an argument may be combined together.
The
.code -v
and
.code -q
options are mutually exclusive. Of these two, the one which
occurs in the rightmost position in the argument list dominates.
The
.code -c
and
.code -f
options are also mutually exclusive; if both are specified,
it is a fatal error.

.meIP >> -D var=value
Bind the variable
.meta var
to the value
.meta value
prior to processing the query. The name is in scope over the entire
query, so that all occurrence of the variable are substituted and
match the equivalent text.  If the value contains commas, these
are interpreted as separators, which give rise to a list value.
For instance
.code -Da,b,c
creates a list of the strings
.strn "a" ,
.str "b"
and
.strn "c" .
(See Collect Directive bellow). List variables provide a multiple
match. That is to say, if a list variable occurs in a query, a successful
match occurs if any of its values matches the text. If more than one
value matches the text, the first one is taken.

.meIP >> -D var
Binds the variable
.meta var
to an empty string value prior to processing the query.

.coIP -q
Quiet operation during matching. Certain error messages are not reported on the
standard error device (but the if the situations occur, they still fail the
query). This option does not suppress error generation during the parsing
of the query, only during its execution.

.coIP -i
If this option is present, then \*(TX will enter into an interactive
interpretation mode after processing all options, and the input query
if one is present. See the INTERACTIVE LISTENER section for a
description of this mode.

.coIP -d
.coIP --debugger
Invoke the interactive \*(TX debugger. See the DEBUGGER section.

.coIP -n
.coIP --noninteractive
This option affects behavior related to \*(TX's
.code *std-input*
stream.  Normally, if this stream is connected to a terminal device, it is
automatically marked as having the real-time property when \*(TX starts up (see
the functions .code stream-set-prop and
.codn real-time-stream-p ).
The
.code -n
option suppresses this behavior; the
.code *std-input*
stream remains ordinary.

The \*(TX pattern language reads standard input via
a lazy list, created by applying the
.code lazy-stream-cons
function to the
.code *std-input*
stream. If that stream is marked real-time, then the lazy list which is
returned by that function has behaviors that are better suited for scanning
interactive input. A more detailed explanation is given under the description
of this function.

.coIP -v
Verbose operation. Detailed logging is enabled.

.coIP -b
This is a deprecated option, which is silently ignored. In \*(TX versions
prior to 90, the printing of variable bindings (see
.code -B
option) was
implicit behavior which was automatically suppressed in certain situations.
The -b option suppressed it unconditionally.

.coIP -B
If the query is successful, print the variable bindings as a sequence
of assignments in shell syntax that can be
.IR eval -ed
by a POSIX shell.
II the query fails, print the word "false". Evaluation of this word
by the shell has the effect of producing an unsuccessful termination
status from the shell's
.I eval
command.

.coIP "-l or --lisp-bindings"
This option implies
.codn -B .
Print the variable bindings in Lisp syntax instead of
shell syntax.

.meIP -a < num
This option implies
.codn -B .
The decimal integer argument
.meta num
specifies the maximum
number of array dimensions to use for list-valued variable bindings.
The default is 1. Additional dimensions are expressed using numeric suffixes
in the generated variable names.
For instance, consider the three-dimensional list arising out of a triply
nested collect:
.cblk
((("a" "b") ("c" "d")) (("e" "f") ("g" "h"))).
.cble
Suppose this is bound to a variable V.  With
.codn "-a 1" ,
this will be
reported as:

.cblk
  V_0_0[0]="a"
  V_0_1[0]="b"
  V_1_0[0]="c"
  V_1_1[0]="d"
  V_0_0[1]="e"
  V_0_1[1]="f"
  V_1_0[1]="g"
  V_1_1[1]="h"
.cble

With
.codn "-a 2" ,
it comes out as:

.cblk
  V_0[0][0]="a"
  V_1[0][0]="b"
  V_0[0][1]="c"
  V_1[0][1]="d"
  V_0[1][0]="e"
  V_1[1][0]="f"
  V_0[1][1]="g"
  V_1[1][1]="h"
.cble

The leftmost bracketed index is the most major index. That is to say,
the dimension order is:
.codn "NAME_m_m+1_..._n[1][2]...[m-1]" .

.meIP -c < query
Specifies the query in the form of a command line argument. If this option is
used, the query-file argument is omitted. The first non-option argument,
if there is one, now specifies the first input source rather than a query.
Unlike queries read from a file, (non-empty) queries specified as arguments
using -c do not have to properly end in a newline. Internally,
\*(TX adds the missing newline before parsing the query. Thus
.code -c
.str @a
is a valid query which matches a line.

Example:

Shell script which uses \*(TX to read two lines
.str 1
and
.str 2
from standard input,
binding them to variables
.code a
and
.codn b .
Standard
input is specified as
.code -
and the data
comes from shell "here document" redirection:
.RS
.IP code:
.cblk
\ #!/bin/sh

 txr -B -c "@a
 @b" - <<!
 1
 2
 !
.cble

.IP output:
.cblk
\ a=1
 b=2
.cble
.PP

The
.code @;
comment syntax can be used for better formatting:

.cblk
  txr -B -c "@;
  @a
  @b"
.cble
.RE

.meIP -f < query-file
Specifies the file from which the query is to be read, instead of the
.meta query-file
argument. This is useful in
.code #!
("hash bang") scripts. (See Hash Bang Support below).

.meIP -e < expression
Evaluates a \*(TL expression for its side effects, without printing
its value. Can be specified more than once. The
.meta query-file
argument becomes optional if
.code -e
is used at least once. If the evaluation of every
.meta expression
evaluated this way terminates normally, and there is no
.meta query-file
argument, then \*(TX terminates with a successful status.

.meIP -p < expression
Just like
.code -e
but prints the value of
.meta expression
using the
.code prinl
function.

.meIP -P < expression
Like
.code -p
but prints using the
.code pprinl
function.

.meIP -t < expression
Like
.code -p
but prints using the
.code tprint
function.

.meIP -C < number
.meIP >> --compat= number

Requests \*(TX to behave in a manner that is compatible with the specified
version of \*(TX. This makes a difference in situations when a release of
\*(TX breaks backward compatibility. If some version N+1 deliberately introduces
a change which is backward incompatible, then
.code "-C N"
can be used to request the old behavior.

The requested value of N can be too low, in which case \*(TX will
complain and exit with an unsuccessful termination status. This indicates
that \*(TX refuses to be compatible with such an old version. Users requiring
the behavior of that version will have to install an older version of \*(TX which
supports that behavior, or even that exact version.

If the option is specified more than once, the behavior is not specified.

Compatibility can also be requested via the
.code TXR_COMPAT
environment variable instead of the
.code -C
option.

For more information, see the COMPATIBILITY section.

.meIP >> --gc-delta= number

The
.meta number
argument to this option must be a decimal integer. It represents
a megabyte value, the "GC delta": one megabyte is 1048576 bytes.  The "GC
delta" controls an aspect of the garbage collector behavior.
See the
.code gc-set-delta
function for a description.

.meIP --debug-autoload
This option turns on debugging, like
.code --debugger
but also requests stepping into the auto-load processing of
\*(TL library code.  Normally, debugging through the evaluations
triggered by auto-loading is suppressed.

.meIP --debug-expansion
This option turns on debugging, like
.code --debugger
but also requests stepping into the parse-time macro-expansion
of \*(TL code embedded in \*(TX queries. Normally, this is suppressed.

.coIP --help
Prints usage summary on standard output, and terminates successfully.

.coIP --license
Prints the software license. This depends on the software being
installed such that the LICENSE file is in the data directory.
Use of \*(TX implies agreement with the liability disclaimer in the license.

.coIP --version
Prints program version standard output, and terminates successfully.

.coIP --args
The
.code --args
option provides a way to encode multiple arguments as a single
argument, which is useful on some systems which have limitations in
their implementation of the "hash bang" mechanism. For details about
its special syntax, See Hash Bang Support below. It is also very useful in
stand-alone application deployment. See the section
STAND-ALONE APPLICATION SUPPORT, in which example uses of
.code --args
are shown.

.coIP --eargs
The
.code --eargs
option (extended
.codn --args )
is like
.code --args
but must be followed by an argument. The argument is substituted
in place of occurrences of
.code {}
in the
.code --eargs
syntax.

.coIP --lisp
This option influences the treatment of query files which do not have
a suffix indicating their type: they are treated as \*(TL source.
Moreover, if
.code --lisp
is specified, and an unsuffixed file does not exist, then \*(TX
will add the
.str .tl
suffix and try the file again. In the same situation, if
.code --lisp
is not present, \*(TX will first try adding the
.str .txr
suffix. If that fails,
then
.str .tl
suffix will be tried. Note that
.code --lisp
influences how the argument of the
.code -f
option is treated, but only if it precedes that option.
It has no effect on the
.code -c
option. The argument of
.code -c
is always \*(TX pattern language code. Lisp code can be evaluated using
the
.codn -e ,
.codn -p ,
or
.code -P
options.

.coIP --reexec
On platforms which support the POSIX
.code exec
family of functions, this option causes \*(TX to re-execute itself.
The re-executed image receives the remaining arguments which follow
the
.code --reexec
argument. Note: this option is useful for supporting setuid operation in
"hash hang" scripts. On some platforms, the interpreter designated by
a "hash bang" script runs without altered privilege, even if that
interpreter is installed setuid. If the interpreter is executed directly,
then setuid applies to it, but not if it is executed via "hash bang".
If the
.code --reexec
option is used in the interpreter command line of such a script, the
interpreter will re-execute itself, thereby gaining the setuid privilege.
The re-executed image will then obtain the script name from the arguments
which are passed to it and determine whether that script will run setuid.
See the section SETUID/SETGID OPERATION.

.coIP --gc-debug
This option enables a behavior which stresses the garbage collector with
frequent garbage collection requests. The purpose is to make it more likely
to reproduce certain kinds of bugs. It makes \*(TX run very slowly.

.coIP --vg-debug
If \*(TX is enabled with Valgrind support, then this option is available.
It enables code which uses the Valgrind API to integrate with the Valgrind
debugger, for more accurate tracking of garbage collected objects. For
example, objects which have been reclaimed by the garbage collector
are marked as inaccessible, and marked as uninitialized when they are
allocated again.

.coIP --dv-regex
If this option is used, then regular expressions are all treated using the
derivative-based back-end.  The NFA-based regex implementation is disabled.
Normally, only regular expressions which require the intersection and
complement operators are handled using the derivative back-end.
This option makes it possible to test that back-end on test cases that it
wouldn't normally receive.

.coIP --
Signifies the end of the option list.

.coIP -
This argument is not interpreted as an option, but treated as a filename
argument. After the first such argument, no more options are recognized. Even
if another argument looks like an option, it is treated as a name.
This special argument
.code -
means "read from standard input" instead of a file.
The query file, or any of the data files, may be specified using this option.
If two or more files are specified as
.codn - ,
the behavior is system-dependent.
It may be possible to indicate EOF from the interactive terminal, and
then specify more input which is interpreted as the second file, and so forth.

.PP
After the options, the remaining arguments are files. The first file argument
specifies the query, and is mandatory if the
.code -f
option has not been specified.  A file argument consisting of a single
.code -
means to read the standard input instead of opening a file. A file argument
which begins with an exclamation symbol means that the rest of the argument is
a shell command which is to be run as a coprocess, and its output read like a
file.

.PP
\*(TX begins by reading the query. The entire query is scanned, internalized
and then begins executing, if it is free of syntax errors.  The reading of
data, on the other hand, is lazy.  A file isn't opened until the query demands
material from that file, and then the contents are read on demand, not all at
once.

The suffix of the query file is significant. If the query file name has no
suffix, or if it has a
.str .txr
suffix, then it is assumed to be in the \*(TX query language. If it has
the
.str .tl
suffix, then it is assumed to be \*(TL.  The
.code --lisp
option changes the treatment of unsuffixed query file names, causing them
to be interpreted as \*(TL .

If an unsuffixed query file name is specified, and cannot be opened, then
\*(TX will add the
.str .txr
suffix and try again. If that fails, it will be tried with the
.str .tl
suffix, and treated as \*(TL .
If the
.code --lisp
option has been specified, then \*(TX tries only the
.str .tl
suffix.

A \*(TL file is processed as if by the
.code load
macro: forms from the file are read and evaluated. If the forms do not terminate
the \*(TX process or throw an exception, and there are no syntax errors, then
\*(TX terminates successfully after evaluating the last form. If syntax errors
are encountered in a form, then \*(TX terminates unsuccessfully.
\*(TL is documented in the section TXR LISP.

If no files arguments are specified on the command line, it is up to the
query to open a file, pipe or standard input via the
.code @(next)
directive
prior to attempting to make a match. If a query attempts to match text,
but has run out of files to process, the match fails.

.SH* STATUS AND ERROR REPORTING
\*(TX sends errors and verbose logs to the standard error device. The following
paragraphs apply when \*(TX is run without enabling verbose mode with
.codn -v ,
or the printing of variable
bindings with
.code -B
or
.codn -a .

If the command line arguments are incorrect, or the query has a malformed
syntax, \*(TX issues an error diagnostic and terminates with a failed status.

If the query fails due to a mismatch, \*(TX terminates
with a failed status. No diagnostics are issued.

If the query is well-formed, and matches, then \*(TX issues
no diagnostics, and terminates with a successful status.

In verbose mode (option
.codn -v ),
\*(TX issues diagnostics on the standard error device even in situations which
are not erroneous.

In bindings-printing mode (options
.code -B
or
.codn -a) ,
\*(TX prints the word
.code false
if the query fails, and exits with a failed
termination status. If the query succeeds, the variable bindings, if any,
are output on standard output.

.SH* BASIC TXR SYNTAX
.SS* Comments
A query may contain comments which are delimited by the sequence
.code @;
and extend to the end of the line. Whitespace can occur between the
.code @
and
.codn ; .
A comment which begins on a line swallows that entire line, as well as the
newline which terminates it. In essence, the entire comment line disappears.
If the comment follows some material in a line, then it does not consume
the newline. Thus, the following two queries are equivalent:
.IP 1.
.cblk
\ @a@; comment: match whole line against variable @a
 @; this comment disappears entirely
 @b
.cble

.IP 2.
.cblk
\ @a
 @b
.cble

.PP

The comment after the
.code @a
does not consume the newline, but the
comment which follows does. Without this intuitive behavior,
line comment would give rise to empty lines that must match empty
lines in the data, leading to spurious mismatches.

Instead of the
.code ;
character, the
.code #
character can be used. This is an obsolescent feature.

.SS* Hash Bang Support
\*(TX has several features which support use of the "hash bang" convention
for creating apparently stand-alone executable programs.

If the first line of a query begins with the characters
.codn #! ,
that entire line is deleted from the query. This allows
for \*(TX queries to be turned into standalone executable programs in the POSIX
environment.

Shell example: create a simple executable program called
.str "twoline.txr"
and
run it. This assumes \*(TX is installed in
.codn /usr/bin .

.cblk
  $ cat > hello.txr
  #!/usr/bin/txr
  @(bind a "Hey")
  @(output)
  Hello, world!
  @(end)
  $ chmod a+x hello.txr
  $ ./hello.txr
  Hello, world!
.cble

When this plain hash bang line is used, \*(TX receives the name of the script
as an argument.  Therefore, it is not possible to pass additional options
to \*(TX.  For instance, if the above script is invoked like this

.cblk
  $ ./hello.txr -B
.cble

the -B option isn't processed by \*(TX, but treated as an additional argument,
just as if
.cblk
.meti txr < scriptname -B
.cble
had been executed directly.

This behavior is useful if the script author wants not to expose the
\*(TX options to the user of the script.

However, the hash bang line can use the
.code -f
option:

.cblk
  #!/usr/bin/txr -f
.cble

Now, the name of the script is passed as an argument to the
.code -f
option, and \*(TX will look for more options after that, so that the resulting
program appears to accept \*(TX options. Now we can run

.cblk
  $ ./hello.txr -B
  Hello, world!
  a="Hey"
.cble

The
.code -B
option is honored.

On some operating systems, it is not possible to pass more than one
argument through the hash bang mechanism. That is to say, this will
not work.

.cblk
  #!/usr/bin/txr -B -f
.cble

To support systems like this, \*(TX supports the special argument
.codn --args ,
as well as as an extended version,
.codn --eargs .
With
.codn --args ,
it is possible to encode multiple arguments
into one argument.  The
.code --args
option must be followed by a separator
character, chosen by the programmer. The characters after that are
split into multiple arguments on the separator character. The
.code --args
option is then removed from the argument list and replaced with these
arguments, which are processed in its place.

Example:

.cblk
  #!/usr/bin/txr --args:-B:-f
.cble

The above has the same behavior as

.cblk
  #!/usr/bin/txr -B -f
.cble

on a system which supports multiple arguments in hash bang.
The separator character is the colon, and so the remainder
of that argument,
.codn -B:-f ,
is split into the two arguments
.codn "-B -f" .

The
.code --eargs
mechanism allows an additional flexibility. An
.code --eargs
argument must be followed by one more argument.
Occurrences of the two-character sequence
.code {}
in the encoded argument string are replaced with that
following argument. This replacement occurs after
the argument splitting.

Example:

.cblk
  #!/usr/bin/txr --eargs:-B:{}:--foo:42
.cble

This has an effect which cannot be replicated in any known
implementation of the hash bang mechanism. Suppose
that this hash bang line is placed in a script called
.codn script.txr .
When this script is invoked with arguments, as in:

.cblk
  script.txr a b c
.cble

then \*(TX is invoked similarly to:

.cblk
  /usr/bin/txr --eargs:-B:{}:--foo:42 script.txr a b c
.cble

Then, when
.code --eargs
processing takes place, firstly the argument sequence

.code
  -B {} --foo 42
.code

is produced. Then, all occurrences of
.code {}
are replaced with
.codn script.txr ,
resulting in:

.code
  -B script.txr --foo 42
.code

The resulting \*(TX invocation is

.code
  /usr/bin/txr -B script.txr --foo 42 a b c
.code

Thus,
.code --eargs
allows some arguments to be encoded into the interpreter script, such that
script name is inserted anywhere among them, possibly multiple times. Arguments
for the interpreter can be encoded, as well as arguments to be processed by the
script.

\*(TX supports setuid hash bang scripting, even on platforms that do not
support setuid and setgid attributes on hash bang scripts. On such
platforms, \*(TX has to be installed setuid/setgid. See the section
SETUID/SETGID OPERATION. On some platforms, it may also be necessary to
to use the
.code --reexec
option.

.SS* Whitespace
Outside of directives, whitespace is significant in \*(TX queries, and represents
a pattern match for whitespace in the input.  An extent of text consisting of
an undivided mixture of tabs and spaces is a whitespace token.  

Whitespace tokens match a precisely identical piece of whitespace in the input,
with one exception: a whitespace token consisting of precisely one space has a
special meaning. It is equivalent to the regular expression
.codn "@/[ ]+/" :
match an extent of one or more spaces (but not tabs!). Multiple consecutive
spaces do not have this meaning.

Thus, the query line
.str "a b"
(one space between
.code a
and
.codn b )
matches
.str "a b"
with any number of spaces between the two letters.

For matching a single space, the syntax
.code "@\e "
can be used (backslash-escaped space).

It is more often necessary to match multiple spaces than to exactly
match one space, so this rule simplifies many queries and adds inconvenience
to only few.

In output clauses, string and character literals and quasiliterals, a space
token denotes a space.

.SS* Text
Query material which is not escaped by the special character
.code @
is literal text, which matches input character for character. Text which occurs at
the beginning of a line matches the beginning of a line.  Text which starts in
the middle of a line, other than following a variable, must match exactly at
the current position, where the previous match left off. Moreover, if the text
is the last element in the line, its match is anchored to the end of the line.

An empty query line matches an empty line in the input. Note that an
empty input stream does not contain any lines, and therefore is not matched
by an empty line. An empty line in the input is represented by a newline
character which is either the first character of the file, or follows
a previous newline-terminated line.  

Input streams which end without terminating their last line with a newline are
tolerated, and are treated as if they had the terminator.

Text which follows a variable has special semantics, described in the
section Variables below.

A query may not leave a line of input partially matched. If any portion of a
line of input is matched, it must be entirely matched, otherwise a matching
failure results. However, a query may leave unmatched lines. Matching only
four lines of a ten line file is not a matching failure. The
.code eof
directive can be used to explicitly match the end of a file.

In the following example, the query matches the text, even though
the text has an extra line.
.IP code:
.cblk
\ Four score and seven
 years ago our
.cble

.IP data:
.cblk
\ Four score and seven
 years ago our
 forefathers
.cble
.PP

In the following example, the query
.B fails
to match the text, because the text has extra material on one
line that is not matched:
.IP code:
.cblk
\ I can carry nearly eighty gigs
 in my head
.cble

.IP data:
.cblk
\ I can carry nearly eighty gigs of data
 in my head
.cble
.PP

Needless to say, if the text has insufficient material relative
to the query, that is a failure also.

To match arbitrary material from the current position to the end
of a line, the "match any sequence of characters, including empty"
regular expression
.code @/.*/
can be used. Example:
.IP code:
.cblk
\ I can carry nearly eighty gigs@/.*/
.cble

.IP data:
.cblk
\ I can carry nearly eighty gigs of data
.cble
.PP

In this example, the query matches, since the regular expression
matches the string "of data". (See Regular Expressions section below).

Another way to do this is:
.IP code:
.cblk
\ I can carry nearly eighty gigs@(skip)
.cble

.SS* Special Characters in Text
Control characters may be embedded directly in a query (with the exception of
newline characters). An alternative to embedding is to use escape syntax.
The following escapes are supported:

.meIP >> @\e  newline
A backslash immediately followed by a newline introduces a physical line
break without breaking up the logical line. Material following this sequence
continues to be interpreted as a continuation of the previous line, so
that indentation can be introduced to show the continuation without appearing
in the data.
.meIP >> @\e  space
A backslash followed by a space encodes a space. This is useful in line
continuations when it is necessary for some or all of the leading spaces to be
preserved.  For instance the two line sequence

.cblk
  abcd@\e
    @\e  efg
.cble

is equivalent to the line

.cblk
  abcd  efg
.cble

The two spaces before the
.code @\e
in the second line are consumed. The spaces after are preserved.

.coIP @\ea
Alert character (ASCII 7, BEL).
.coIP @\eb
Backspace (ASCII 8, BS).
.coIP @\et
Horizontal tab (ASCII 9, HT).
.coIP @\en
Line feed (ASCII 10, LF). Serves as abstract newline on POSIX systems.
.coIP @\ev
Vertical tab (ASCII 11, VT).
.coIP @\ef
Form feed (ASCII 12, FF). This character clears the screen on many
kinds of terminals, or ejects a page of text from a line printer.
.coIP @\er
Carriage return (ASCII 13, CR).
.coIP @\ee
Escape (ASCII 27, ESC)
.meIP @\ex < hex-digits
A
.code @\ex
immediately followed by a sequence of hex digits is interpreted as a hexadecimal
numeric character code. For instance
.code @\ex41
is the ASCII character A.  If a semicolon character immediately follows the
hex digits, it is consumed, and characters which follow are not considered
part of the hex escape even if they are hex digits.
.meIP @\e < octal-digits

A
.code @\e
immediately followed by a sequence of octal digits (0 through 7) is interpreted
as an octal character code. For instance
.code @\e010
is character 8, same as
.codn @\eb .
If a semicolon character immediately follows the octal digits, it is consumed,
and subsequent characters are not treated as part of the octal escape,
even if they are octal digits.
.PP

Note that if a newline is embedded into a query line with
.code @\en,
this does not split the line into two; it's embedded into the line and thus
cannot match anything. However,
.code @\en
may be useful in the
.code @(cat)
directive and
in
.codn @(output) .

.SS* Character Handling and International Characters

\*(TX represents text internally using wide characters, which are used to
represent Unicode code points. The query language, as well as all data sources,
are assumed to be in the UTF-8 encoding.  In the query language, extended
characters can be used directly in comments, literal text, string literals,
quasiliterals and regular expressions.  Extended characters can also be
expressed indirectly using hexadecimal or octal escapes.
On some platforms, wide characters may be restricted to 16 bits, so that
\*(TX can only work with characters in the BMP (Basic Multilingual Plane)
subset of Unicode.

\*(TX does not use the localization features of the system library;
its handling of extended characters is not affected by environment variables
like
.code LANG
and
.codn L_CTYPE .
The program reads and writes only the UTF-8 encoding.

If
\*(TX encounters an invalid bytes in the UTF-8 input, what happens depends on
the context in which this occurs. In a query, comments are read without regard
for encoding, so invalid encoding bytes in comments are not detected. A comment
is simply a sequence of bytes terminated by a newline.  In lexical elements
which represent text, such as string literals, invalid or unexpected encoding
bytes are treated as syntax errors. The scanner issues an error message,
then discards a byte and resumes scanning.  Certain sequences pass through the
scanner without triggering an error, namely some UTF-8 overlong sequences.
These are caught when when the lexeme is subject to UTF-8 decoding, and treated
in the same manner as other UTF-8 data, described in the following paragraph.

Invalid bytes in data are treated as follows. When an invalid byte is
encountered in the middle of a multibyte character, or if the input
ends in the middle of a multibyte character, or if a character is extracted
which is encoded as an overlong form, the UTF-8 decoder returns to the starting
byte of the ill-formed multibyte character, and extracts just that byte,
mapping it to the Unicode character range U+DC00 through U+DCFF.  The decoding
resumes afresh at the following byte, expecting that byte to be the start
of a UTF-8 code.

Furthermore, because \*(TX internally uses a null-terminated character
representation of strings which easily interoperates with C language
interfaces, when a null character is read from a stream, \*(TX converts it to
the code U+DC00. On output, this code converts back to a null byte,
as explained in the previous paragraph. By means of this representational
trick, \*(TX can handle textual data containing null bytes.

.SS* Regular Expression Directives

In place of a piece of text (see section Text above), a regular expression
directive may be used, which has the following syntax:

.cblk
  @/RE/
.cble

where the RE part enclosed in slashes represents regular expression
syntax (described in the section Regular Expressions below).

Long regular expressions can be broken into multiple lines using a
backslash-newline sequence.  Whitespace before the sequence or after the
sequence is not significant, so the following two are equivalent:

.cblk
  @/reg \e
    ular/

  @/regular/
.cble

There may not be whitespace between the backslash and newline.

Whereas literal text simply represents itself, regular expression denotes a
(potentially infinite) set of texts.  The regular expression directive
matches the longest piece of text (possibly empty) which belongs to the set
denoted by the regular expression. The match is anchored to the current
position; thus if the directive is the first element of a line, the match is
anchored to the start of a line. If the regular expression directive is the
last element of a line, it is anchored to the end of the line also: the regular
expression must match the text from the current position to the end of the
line.

Even if the regular expression matches the empty string, the match will fail if
the input is empty, or has run out of data. For instance suppose the third line
of the query is the regular expression
.codn @/.*/ ,
but the input is a file which has
only two lines. This will fail: the data has no line for the regular expression to
match. A line containing no characters is not the same thing as the absence of
a line, even though both abstractions imply an absence of characters.

Like text which follows a variable, a regular expression directive which
follows a variable has special semantics, described in the section Variables
below.

.SS* Variables

Much of the query syntax consists of arbitrary text, which matches file data
character for character. Embedded within the query may be variables and
directives which are introduced by a
.code @
character.  Two consecutive
.code @@
characters encode a literal
.codn @ .

A variable matching or substitution directive is written in one of several
ways:

.cblk
.mets >> @ sident
.mets <> @{ bident }
.mets >> @* sident
.mets <> @*{ bident }
.mets >> @{ bident <> / regex /}
.mets >> @{ bident >> ( fun >> [ arg ... ])}
.mets >> @{ bident << number }
.cble

The forms with an
.code *
indicate a long match, see Longest Match below.
The last two three forms with the embedded regexp
.cblk
.meti <> / regex /
.cble
or
.meta number
or function
have special semantics; see Positive Match below.

The identifier
.code t
cannot be used as a name; it is a reserved symbol which
denotes the value true. An attempt to use the variable
.code @t
will result in an exception.  The symbol
.code nil
can be used where a variable name is required syntactically,
but it has special semantics, described in a section below.

A
.meta sident
is a "simple identifier" form which is not delimited by
braces.

A
.meta sident
consists of any combination of
one or more letters, numbers, and underscores. It may not look like a number,
so that for instance
.code 123
is not a valid
.metn sident ,
but
.code 12A
is valid.  Case is
sensitive, so that
.code FOO
is different from
.codn foo ,
which is different from
.codn Foo .

The braces around an identifier can be used when material which follows would
otherwise be interpreted as being part of the identifier. When a name is
enclosed in braces it is a
.metn bident .

The following additional characters may be used as part of
.meta bident
which are not allowed in a
.metn sident :

.cblk
 ! $ % & * + - < = > ? \e _ ~
.cble

The rule still holds that a name cannot look like a number so
.code +123
is not a valid
.meta bident
but these are valid:
.codn a->b ,
.codn *xyz* ,
.codn foo-bar .

The syntax
.code @FOO_bar
introduces the name
.codn FOO_bar ,
whereas
.code @{FOO}_bar
means the
variable named
.str FOO
followed by the text
.strn _bar .
There may be whitespace
between the
.code @
and the name, or opening brace. Whitespace is also allowed in the
interior of the braces. It is not significant.

If a variable has no prior binding, then it specifies a match. The
match is determined from some current position in the data: the
character which immediately follows all that has been matched previously.
If a variable occurs at the start of a line, it matches some text
at the start of the line. If it occurs at the end of a line, it matches
everything from the current position to the end of the line.

.SS* Negative Match

If a variable is one of the plain forms

.cblk
.mets >> @ sident
.mets <> @{ bident }
.mets >> @* sident
.mets <> @*{ bident }
.cble

then this is a "negative match".  The extent of the matched text (the text
bound to the variable) is determined by looking at what follows the variable,
and ranges from the current position to some position where the following
material finds a match. This is why this is called a "negative match": the
spanned text which ends up bound to the variable is that in which the match for
the trailing material did not occur.

A variable may be followed by a piece of text, a regular expression directive,
a function call, a directive, another variable, or nothing (i.e.  occurs at the
end of a line). These cases are described in detail below.

.NP* Variable Followed by Nothing
If the variable is followed by nothing, the negative match extends from the
current position in the data, to the end of the line.  Example:
.IP code:
.cblk
\ a b c @FOO
.cble
.IP data:
.cblk
\ a b c defghijk
.cble
.IP result:
.cblk
\ FOO="defghijk"
.cble

.NP* Variable Followed by Text
For the purposes of determining the negative match, text is defined as a
sequence of literal text and regular expressions, not divided by a directive.
So for instance in this example:

.cblk
  @a:@/foo/bcd e@(maybe)f@(end)
.cble
.PP

the variable @a is considered to be followed by
.strn ":@/foo/bcd e" .

If a variable is followed by text, then the extent of the negative match is
determined by searching for the first occurrence of that text within the line,
starting at the current position.

The variable matches everything between the current position and the matching
position (not including the matching position). Any whitespace which follows
the variable (and is not enclosed inside braces that surround the variable
name) is part of the text. For example:
.IP code:
.cblk
\ a b @FOO e f
.cble
.IP data:
.cblk
\ a b c d e f
.cble
.IP result:
.cblk
\ FOO="c d"
.cble
.PP

In the above example, the pattern text
.str "a b "
matches the
data
.strn "a b " .
So when the
.code @FOO
variable is processed, the data being
matched is the remaining
.strn "c d e f" .
The text which follows
.code @FOO
is
.strn " e f" .
This is found within the data
.str "c d e f"
at position 3 (counting from 0).  So positions 0-2
.cblk
("c d")
.cble
constitute the matching text which is bound to FOO.

.NP* Variable Followed by a Function Call or Directive

If the variable is followed by a function call, or a directive, the extent is
determined by scanning the text for the first position where a match occurs
for the entire remainder of the line. (For a description of functions,
see Functions.)

For example:

.cblk
  @foo@(bind a "abc")xyz
.cble

Here,
.code foo
will match the text from the current position to where
.str "xyz"
occurs, even though there is a
.code @(bind)
directive. Furthermore, if
more material is added after the xyz, it is part of the search.
Note the difference between the following two:

.cblk
  @foo@/abc/@(func)
  @foo@(func)@/abc/
.cble

In the first example, the variable foo matches the text from the current
position until the match for the regular expression abc.
.code @(func)
is not
considered when processing
.codn @foo .
In the second example, the variable foo
matches the text from the current position until the position which matches
the function call, followed by a match for the regular expression.
The entire sequence
.code @(func)@/abc/
is considered.

.NP* Consecutive Variables
If an unbound variable specifies a fixed-width match or a regular expression,
then the issue of consecutive variables does not arise. Such a variable
consumes text regardless of any context which follows it.

However, what if an unbound variable with no modifier is followed by another
variable? The behavior depends on the nature of the other variable.

If the other variable is also unbound, and also has no modifier, this is a
semantic error which will cause the query to fail.  A diagnostic message will
be issued, unless operating in quiet mode via
.codn -q .
The reason is that there is no way to bind two
consecutive variables to an extent of text; this is an ambiguous situation,
since there is no matching criterion for dividing the text between two
variables.  (In theory, a repetition of the same variable, like
.codn @FOO@FOO ,
could find a solution by dividing the match extent in half, which would work
only in the case when it contains an even number of characters.  This behavior
seems to have dubious value).

An unbound variable may be followed by one which is bound. The bound
variable is effectively replaced by the text which it denotes, and the logic
proceeds accordingly.

It is possible for a variable to be bound to a regular expression.
If
.code x
is an unbound variable and
.code y
is bound to a regular expression
.codn RE ,
then
.code @x@y
means
.codn @x@/RE/ .
A variable
.code v
can be bound to a regular expression using, for example,
.codn "@(bind v #/RE/)" .

The
.code @*
syntax for longest match is available. Example:
.IP code:
.cblk
\ @FOO:@BAR@FOO
.cble
.IP data:
.cblk
\ xyz:defxyz
.cble
.IP result:
.cblk
\ FOO=xyz, BAR=def
.cble
.PP

Here,
.code FOO
is matched with
.strn "xyz" ,
based on the delimiting around the
colon. The colon in the pattern then matches the colon in the data,
so that
.code BAR
is considered for matching against
.strn "defxyz" .
.code BAR
is followed by
.codn FOO ,
which is already bound to
.strn "xyz" .
Thus
.str "xyz"
is located in the
.str "defxyz"
data following
.strn "def" ,
and so BAR is bound to
.strn "def" .

If an unbound variable is followed by a variable which is bound to a list, or
nested list, then each character string in the list is tried in turn to produce
a match. The first match is taken.

An unbound variable may be followed by another unbound variable which specifies
a regular expression or function call match. This is a special case called a
"double variable match".  What happens is that the text is searched using the
regular expression or function.  If the search fails, than neither variable is
bound: it is a matching failure.  If the search succeeds, than the first
variable is bound to the text which is skipped by the search.  The second
variable is bound to the text matched by the regular expression or function.
Examples:
.IP code:
.cblk
\ @foo@{bar /abc/}
.cble
.IP data:
.cblk
\ xyz@#abc
.cble
.IP result:
.cblk
\ foo="xyz@#", BAR="abc"
.cble
.PP

.NP* Consecutive Variables Via Directive
Two variables can be
.I de facto
consecutive in a manner shown in the
following example:

.cblk
  @var1@(all)@var2@(end)
.cble

This is treated just like the variable followed by directive. No semantic
error is identified, even if both variables are unbound. Here,
.code @var2
matches everything at the current position, and so
.code @var1
ends up bound to the empty string.

Example 1:
.code b
matches at position 0 and
.code a
binds the empty string:
.IP code:
.cblk
\ @a@(all)@b@(end)
.cble
.IP data:
.cblk
\ abc
.cble
.IP result:
.cblk
\ a=""
 b="abc"
.cble
.PP

Example 2:
.code *a
specifies longest match (see Longest Match below), and so it takes
everything:
.IP code:
.cblk
\ @*a@(all)@b@(end)
.cble
.IP data:
.cblk
\ abc
.cble
.IP result:
.cblk
\ a="abc"
 b=""
.cble
.PP

.NP* Longest Match
The closest-match behavior for the negative match can be overridden to longest
match behavior. A special syntax is provided for this: an asterisk between the
.code @
and the variable, e.g:
.IP code:
.cblk
\ a @*{FOO}cd
.cble
.IP data:
.cblk
\ a b cdcdcdcd
.cble
.IP result:
.cblk
\ FOO="b cdcdcd"
.cble
.PP
.IP code:
.cblk
\ a @{FOO}cd
.cble
.IP data:
.cblk
\ a b cdcdcd
.cble
.IP result:
.cblk
\ FOO="b "
 b=""
.cble
.PP

In the former example, the match extends to the rightmost occurrence of
.strn "cd" ,
and so
.code FOO
receives
.strn "b cdcdcd" .
In the latter example, the
.code *
syntax isn't used, and so a leftmost match takes place. The extent
covers only the
.strn "b " ,
stopping at the first
.str "cd"
occurrence.

.SS* Positive Match

There are syntactic variants of variable syntax which have an embedded expression
enclosed with the variable in braces:

.cblk
.mets >> @{ bident <> / regex /}
.mets >> @{ bident >> ( fun >> [args ...])}
.mets >> @{ bident << number }
.cble

These specify a variable binding that is driven by a positive match derived
from a regular expression, function or character count, rather than from
trailing material (which is regarded as a "negative" match, since the
variable is bound to material which is
.B skipped
in order to match the trailing material). In the
.cblk
.meti <> / regex /
.cble
form, the match
extends over all characters from the current position which match
the regular expression
.metn regex .
(see Regular Expressions section below).
In the
.cblk
.meti >> ( fun >> [ args ...])
.cble
form, the match extends over characters which
are matched by the call to the function, if the call
succeeds. Thus
.code "@{x (y z w)}"
is just like
.codn "@(y z w)" ,
except that the region of
text skipped over by
.code "@(y z w)"
is also bound to the variable
.codn x .
See Functions below.

In the
.meta number
form, the match processes a field of text which
consists of the specified number of characters, which must be non-negative
number.  If the data line doesn't have that many characters starting at the
current position, the match fails. A match for zero characters produces an
empty string.  The text which is actually bound to the variable
is all text within the specified field, but excluding leading and
trailing whitespace. If the field contains only spaces, then an empty
string is extracted.

This syntax is processed without consideration of what other
syntax follows.  A positive match may be directly followed by an unbound
variable.

.coSS Special Symbols @ nil and @ t

Just like in the Common Lisp language, the names
.code nil
and
.code t
are special.

.code nil
symbol stands for the empty
list object, an object which marks the end of a list, and Boolean false. It is
synonymous with the syntax
.code ()
which may be used interchangeably with
.code nil
in most constructs.

In \*(TL,
.code nil
and
.code t
cannot be used as variables. When evaluated, they evaluate to themselves.

In the \*(TX pattern language,
.code nil
can be used in the variable binding syntax, but does not create a binding;
it has a special meaning.  It allows the variable matching syntax to be used to
skip material, in ways similar to the
.code skip
directive.

The
.code nil
symbol is also used as a
.code block
name, both in the \*(TX pattern language and in \*(TL.
A block named
.code nil
is considered to be anonymous.

.SS* Keyword Symbols

Names whose names begin with the
.code :
character are keyword symbols.  These also
may not be used as variables either and stand for themselves. Keywords are
useful for labeling information and situations.

.SS* Regular Expressions
Regular expressions are a language for specifying sets of character strings.
Through the use of pattern matching elements, regular expression is
able to denote an infinite set of texts.
\*(TX contains an original implementation of regular expressions, which
supports the following syntax:
.coIP .
The period is a "wildcard" that matches any character.
.coIP []
Character class: matches a single character, from the set specified by
special syntax written between the square brackets.
This supports basic regexp character class syntax. POSIX
notation like
.code [:digit:]
is not supported.
The regex tokens
.codn \es ,
.code \ed
and
.code \ew
are permitted in character classes, but not their complementing counterparts.
These tokens simply contribute their characters to the class.
The class
.code [a-zA-Z]
means match an uppercase
or lowercase letter; the class
.code [0-9a-f]
means match a digit or
a lowercase letter; the class
.code [^0-9]
means match a non-digit, and so forth.
There are no locale-specific behaviors in \*(TX regular expressions;
.code [A-Z]
denotes an ASCII/Unicode range of characters.
The class
.code [\ed.]
means match a digit or the period character.
A
.code ]
or
.code -
can be used within a character class, but must be escaped
with a backslash. A
.code ^
in the first position denotes a complemented
class, unless it is escaped by backslash. In any other position, it denotes
itself.  Two backslashes code for one backslash. So for instance
.code [\e[\e-]
means match a
.code [
or
.code -
character,
.code [^^]
means match any character other
than
.codn ^ ,
and
.code [\e^\e\e]
means match either a
.code ^
or a backslash. Regex operators
such as
.codn * ,
.code +
and
.code &
appearing in a character class represent ordinary
characters. The characters
.codn - ,
.code ]
and
.code ^
occurring outside of a character class
are ordinary. Unescaped
.code /
characters can appear within a character class. The
empty character class
.code []
matches no character at all, and its complement
.code [^]
matches any character, and is treated as a synonym for the 
.code .
(period) wildcard operator.
.ccIP @, \es @ \ew and @ \ed
These regex tokens each match a single character. 
The
.code \es
regex token matches a wide variety of ASCII whitespace characters
and Unicode spaces. The
.code \ew
token matches alphabetic word characters; it
is equivalent to the character class
.codn [A-Za-z_] .
The
.code \ed
token matches a digit, and is equivalent to
.codn [0-9] .
.ccIP @, \eS @ \eW and @ \eD
These regex tokens are the complemented counterparts of
.codn \es ,
.code \ew
and
.codn \ed .
The
.code \eS
token matches all those characters which
.code \es
does not match,
.code \eW
matches all characters that
.code \ew
does not match and
.code \eD
matches nondigits.
.coIP empty
An empty expression is a regular expression. It represents the set of strings
consisting of the empty string; i.e. it matches just the empty string. The
empty regex can appear alone as a full regular expression (for instance the
\*(TX syntax
.code @//
with nothing between the slashes)
and can also be passed as a subexpression to operators, though this
may require the use of parentheses to make the empty regex explicit.  For
example, the expression
.code a|
means: match either
.codn a ,
or nothing.  The forms
.code *
and
.code (*)
are syntax errors; though not useful, the correct way to match the
empty expression zero or more times is the syntax
.codn ()* .
.coIP nomatch
The nomatch regular expression represents the
empty set: it matches no strings at all, not even the empty string.
There is no dedicated syntax to directly express nomatch in the regex language.
However, the empty character class
.code []
is equivalent to nomatch, and may be
considered to be a notation for it. Other representations of nomatch are
possible: for instance, the regex
.code ~.*
which is the complement of the regex that
denotes the set of all possible strings, and thus denotes the empty set. A
nomatch has uses; for instance, it can be used to temporarily "comment out"
regular expressions. The regex
.code ([]abc|xyz)
is equivalent to
.codn (xyz) ,
since the
.code []abc
branch cannot match anything. Using
.code []
to "block" a subexpression allows
you to leave it in place, then enable it later by removing the "block".
.coIP (R)
If
.code R
is a regular expression, then so is
.code (R).
The contents of parentheses denote one regular expression unit, so that for
instance in
.codn (RE)* ,
the
.code *
operator applies to the entire parenthesized group.
The syntax
.code ()
is valid and equivalent to the empty regular expression.
.coIP R?
Optionally match the preceding regular expression
.codn R .
.coIP R*
Match the expression
.code R
zero or more times. This
operator is sometimes called the "Kleene star", or "Kleene closure".
The Kleene closure favors the longest match. Roughly speaking, if there are two
or more ways in which
.code R1*R2
can match, than that match occurs in which
.code R1*
matches the longest possible text.
.coIP R+
Match the preceding expression
.code R
one or more times.  Like
.codn R* ,
this favors the longest possible match:
.code R+
is equivalent to
.codn RR* .
.coIP R1%R2
Match
.code R1
zero or more times, then match
.codn R2 .
If this match can occur in
more than one way, then it occurs such that
.code R1
is matched the fewest
number of times, which is opposite from the behavior of
.codn R1*R2 .
Repetitions of
.code R1
terminate at the earliest
point in the text where a non-empty match for
.code R2
occurs. Because
it favors shorter matches,
.code %
is termed a non-greedy operator.  If
.code R2
is the empty expression, or equivalent to it, then
.code R1%R2
reduces to
. codn R1* .
So for
instance
.code (R%)
is equivalent to
.codn (R*) ,
since the missing right operand is
interpreted as the empty regex. Note that whereas the expression
.code (R1*R2)
is equivalent to
.codn (R1*)R2 ,
the expression
.code (R1%R2)
is
.B not
equivalent to
.codn (R1%)R2 .
.coIP ~R
Match the opposite of the following expression
.codn R ;
that is, match exactly
those texts that
.code R
does not match. This operator is called complement,
or logical not.
.coIP R1R2
Two consecutive regular expressions denote catenation:
the left expression must match, and then the right.
.coIP R1|R2
match either the expression
.code R1
or
.codn R2 .
This operator is known by
a number of names: union, logical or, disjunction, branch, or alternative.
.coIP R1&R2
Match both the expression
.code R1
and
.code R2
simultaneously; i.e. the
matching text must be one of the texts which are in the intersection of the set
of texts matched by
.code R1
and the set matched by
.codn R2 .
This operator is called intersection, logical and, or conjunction.

.PP
Any character which is not a regular expression operator, a backslash escape,
or the slash delimiter, denotes one-position match of that character itself.

Any of the special characters, including the delimiting
.codn / ,
and the backslash, can be escaped with a backslash to suppress its
meaning and denote the character itself.

Furthermore, all of the same escapes as are described in the section Special
Characters in Text above are supported - the difference is that in regular
expressions, the
.code @
character is not required, so for example a tab is coded as
.code \et
rather than
.codn @\et .
Octal and hex character escapes can be optionally
terminated by a semicolon, which is useful if the following characters are
octal or hex digits not intended to be part of the escape.

Only the above escapes are supported. Unlike in some other regular expression
implementations, if a backlash appears before a character which isn't a regex
special character or one of the supported escape sequences, it is an error.
This wasn't true of historic versions of \*(TX. See the COMPATIBILITY section.

.IP "Precedence table, highest to lowest:"
.TS
tab(!);
l l l.
Operators!Class!Associativity
\f[4](R) []\f[]!primary!
\f[4]R? R+ R* R%...\f[]!postfix!left-to-right
\f[4]R1R2\f[]!catenation!left-to-right
\f[4]~R ...%R\f[]\f[]\f[]!unary!right-to-left
\f[4]R1&R2\f[]!intersection!left-to-right
\f[4]R1|R2\f[]!union!left-to-right
.TE
.PP

The
.code %
operator is like a postfix operator with respect to its left
operand, but like a unary operator with respect to its right operand.
Thus
.code a~b%c~d
is
.cblk
a(~(b%(c(~d))))
.cble
, demonstrating right-to-left associativity,
where all of
.code b%
may be regarded as a unary operator being applied to
.codn c~d .
Similarly,
.code a?*+%b
means
.codn (((a?)*)+)%b ,
where the trailing
.code %b
behaves like a postfix operator.

In
\*(TX, regular expression matches do not span multiple lines. The regex
language has no feature for multi-line matching. However, the
.code @(freeform)
directive
allows the remaining portion of the input to be treated as one string
in which line terminators appear as explicit characters. Regular expressions
may freely match through this sequence.

It's possible for a regular expression to match an empty string.
For instance, if the next input character is
.codn z ,
facing a
the regular expression
.codn /a?/ ,
there is a zero-character match:
the regular expression's state machine can reach an acceptance
state without consuming any characters. Examples:
.IP code:
.cblk
\ @A@/a?/@/.*/
.cble
.IP data:
.cblk
\ zzzzz
.cble
.IP result:
.cblk
\ A=""
.cble
.PP

.IP code:
.cblk
\ @{A /a?/}@B
.cble
.IP data:
.cblk
\ zzzzz
.cble
.IP result:
.cblk
\ A="", B="zzzz"
.cble
.PP

.IP code:
.cblk
\ @*A@/a?/
.cble
.IP data:
.cblk
\ zzzzz
.cble
.IP result:
.cblk
\ A="zzzzz"
.cble
.PP

In the first example, variable
.code @A
is followed by a regular expression
which can match an empty string. The expression faces the letter
.code "z"
at position 0 in the data line. A zero-character match occurs there,
therefore the variable
.code A
takes on the empty string. The
.code @/.*/
regular expression then consumes the line.

Similarly, in the second example, the
.code /a?/
regular expression faces a
.codn "z" ,
and thus yields an empty string which is bound to
.codn A .
Variable
.code @B
consumes the entire line.

The third example requests the longest match for the variable binding.
Thus, a search takes place for the rightmost position where the
regular expression matches. The regular expression matches anywhere,
including the empty string after the last character, which is
the rightmost place. Thus variable
.code A
fetches the entire line.

For additional information about the advanced regular expression
operators, NOTES ON EXOTIC REGULAR EXPRESSIONS below.

.SS* Directives
The general syntax of a directive is:

.cblk
.mets >> @ expr
.cble

where
.meta expr
stands for a parenthesized list of subexpressions. A subexpression
is a symbol, number, string literal, character literal, quasiliteral, regular
expression, or a parenthesized expression.  So, examples of syntactically valid
directives are:

.cblk
  @(banana)

  @(a b c (d e f))

  @(  a (b (c d) (e  ) ))

  @("apple" #\eb #\espace 3)

  @(a #/[a-z]*/ b)

  @(_ `@file.txt`)
.cble

A symbol has a slight more permissive lexical syntax than the
.meta bident
in the syntax
.cblk
.meti <> @{ bident }
.cble
introduced earlier. The
.code /
(slash) character may be part of an identifier, or even
constitute an entire identifier. In fact a symbol inside a
directive is a
.metn lident .
This is described in the Symbol Tokens section under TXR LISP.
A symbol must not be a number; tokens that look like numbers are treated as
numbers and not symbols.

.SS* Character Literals

Character literals are introduced by the
.code #\e
syntax, which is either
followed by a character name, the letter
.code x
followed by hex digits,
the letter
.code o
followed by octal digits, or a single character. Valid character
names are:

.cblk
  nul                 linefeed            return
  alarm               newline             esc
  backspace           vtab                space
  tab                 page                pnul
.cble

For instance
.code #\eesc
denotes the escape character.

This convention for character literals is similar to that
of the Scheme language.  Note that
.code #\elinefeed
and
.code #\enewline
are the same
character. The
.code #\epnul
character is specific to \*(TX and denotes the
.code U+DC00
code in Unicode; the name stands for "pseudo-null", which is related to
its special function. For more information about this, see the section
"Character Handling and International Characters".

.SS* String Literals

String literals are delimited by double quotes.
A double quote within a string literal is encoded using
.cblk
\e"
.cble
and a backslash is encoded as
.codn \e\e .
Backslash escapes like
.code \en
and
.code \et
are recognized, as are hexadecimal escapes like
.code \exFF
or
.code \exxabc
and octal
escapes like
.codn \e123 .
Ambiguity between an escape and subsequent
text can be resolved by using trailing semicolon delimiter:
.str "\exabc;d"
is a string consisting of the character
.code "U+0ABC"
followed by
.strn "d" .
The semicolon
delimiter disappears. To write a literal semicolon immediately after a hex
or octal escape, write two semicolons, the first of which will be interpreted
as a delimiter. Thus,
.str "\ex21;;"
represents
.strn "!;" .

If the line ends in the middle of a literal, it is an error, unless the
last character is a backslash. This backslash is a special escape which does
not denote a character; rather, it indicates that the string literal continues
on the next line.  The backslash is deleted, along with whitespace which
immediately precedes it, as well as leading whitespace in the following line.
The escape sequence
.str "\e "
(backslash space) can be used to encode a significant space.

Example:

.cblk
  "foo   \e
   bar"

  "foo   \e
  \e bar"

  "foo\e  \e
   bar"
.cble

The first string literal is the string
.strn "foobar" .
The second two are
.strn "foo bar" .

.SS* Word List Literals

A word list literal (WLL) provides a convenient way to write a list of strings
when such a list can be given as whitespace-delimited words.

There are two flavors of the WLL: the regular WLL which begins with
.cblk
#"
.cble
(hash, double-quote) and the splicing list literal which begins with
.cblk
#*"
.cble
(hash, star, double-quote).

Both types are terminated by a double quote, which may be escaped
as
.cblk
\e"
.cble
in order to include it as a character. All the escaping conventions
used in string literals can be used in word literals.

Unlike in string literals, whitespace (tabs and spaces) is not
significant in word literals: it separates words.  Whitespace may be
escaped with a backslash in order to include it as a literal character.

Just like in string literals, an unescaped newline character is not allowed.
A newline preceded by a backslash is permitted. Such an escaped backslash,
together with any leading and trailing unescaped whitespace, is removed
and replaced with a single space.

Example:

.cblk
  #"abc def ghi"   --> notates ("abc" "def" "ghi")

  #"abc   def \e
      ghi"         --> notates ("abc" "def" "ghi")

  #"abc\e def ghi" --> notates ("abc def" "ghi")

  #"abc\e def\e \e
   \e ghi"         --> notates ("abc def " " ghi")
.cble

A splicing word literal differs from a word literal in that it does not
produce a list of string literals, but rather it produces a sequence of string
literals that is merged into the surrounding syntax.  Thus, the following two
notations are equivalent:

.cblk
  (1 2 3 #*"abc def" 4 5 #"abc def")

  (1 2 3 "abc" "def" 4 5 ("abc" "def"))
.cble

The regular WLL produced a single list object, but the splicing
WLL expanded into multiple string literal objects.

.SS* String Quasiliterals

Quasiliterals are similar to string literals, except that they may
contain variable references denoted by the usual
.code @
syntax. The quasiliteral
represents a string formed by substituting the values of those variables
into the literal template. If
.code a
is bound to
.str "apple"
and
.code b
to
.strn "banana" ,
the quasiliteral
.code "`one @a and two @{b}s`"
represents the string
.strn "one apple and two bananas" .
A backquote escaped by a backslash represents
itself. Unlike in directive syntax, two consecutive
.code @
characters do not code for a literal
.codn @ ,
but cause a syntax error. The reason for this is that compounding of the
.code @
syntax is meaningful.
Instead, there is a
.code \e@
escape for encoding a literal
.code @
character.  Quasiliterals support the full output variable
syntax. Expressions within variable substitutions follow the evaluation rules
of \*(TL.  This hasn't always been the case: see the COMPATIBILITY section.

Quasiliterals can be split into multiple lines in the same way as ordinary
string literals.

.SS* Quasiword List Literals

The quasiword list literals (QLL-s) are to quasiliterals what WLL-s are to
ordinary literals. (See the above section Word List Literals.)

A QLL combines the convenience of the WLL
with the power of quasistrings.

Just as in the case of WLL-s, there are two flavors of the
QLL: the regular QLL which begins with
.code #`
\ (hash, backquote) and the splicing QLL which begins with
.code #*`
\ (hash, star, backquote).

Both types are terminated by a backquote, which may be escaped
as
.code \e`
\ in order to include it as a character. All the escaping conventions
used in quasiliterals can be used in QLL.

Unlike in quasiliterals, whitespace (tabs and spaces) is not
significant in QLL: it separates words.  Whitespace may be
escaped with a backslash in order to include it as a literal character.

A newline is not permitted unless escaped. An escaped newline works exactly the
same way as it does in word list literals (WLL-s).

Note that the delimiting into words is done before the variable
substitution. If the variable a contains spaces, then
.code #`@a`
nevertheless
expands into a list of one item: the string derived from
.codn a .

Examples:

.cblk
  #`abc @a ghi`  --> notates (`abc` `@a` `ghi`)

  #`abc   @d@e@f \e
  ghi`            --> notates (`abc` `@d@e@f` `ghi`)

  #`@a\e @b @c` --> notates (`@a @b` `@c`)
.cble

A splicing QLL differs from an ordinary QLL in that it does not produce a list
of quasiliterals, but rather it produces a sequence of quasiliterals that is
merged into the surrounding syntax.

.SS* Numbers

\*(TX supports integers and floating-point numbers. 

An integer constant is made up of digits
.code 0
through
.codn 9 ,
optionally preceded by a
.code +
or
.code -
sign.

Examples:

.cblk
  123
  -34
  +0
  -0
  +234483527304983792384729384723234
.cble

An integer constant can also be specified in hexadecimal using the prefix
.code #x
followed by an optional sign, followed by hexadecimal digits:
.code 0
through
.code 9
and the upper or lower case letters
.code A
through
.codn F :

.cblk
  #xFF    ;; 255
  #x-ABC  ;; -2748
.cble

Similarly, octal numbers are supported with the prefix
.code #o
followed by octal digits:

.cblk
  #o777   ;; 511
.cble

and binary numbers can be written with a
.code #b
prefix:

.cblk
  #b1110  ;; 14
.cble

A floating-point constant is marked by the inclusion of a decimal point, the
exponential "e notation", or both. It is an optional sign, followed
by a mantissa consisting of digits, a decimal point, more digits, and then an
optional exponential notation consisting of the letter
.code "e"
or
.codn "E" ,
an optional
.code +
or
.code -
sign, and then digits indicating the exponent value.
In the mantissa, the digits are not optional. At least one digit must either
precede the decimal point or follow. That is to say, a decimal point by itself
is not a floating-point constant.

Examples:

.cblk
  .123
  123.
  1E-3
  20E40
  .9E1
  9.E19
  -.5
  +3E+3
  1.E5
.cble

Examples which are not floating-point constant tokens:

.cblk
  .      ;; dot token, not a number
  123E   ;; the symbol 123E
  1.0E-  ;; syntax error: invalid floating point constant
  1.0E   ;; syntax error: invalid floating point constant
  1.E    ;; syntax error: invalid floating point literal
  .e     ;; syntax error: dot token followed by symbol
.cble

In \*(TX there is a special "dotdot" token consisting of two consecutive periods.
An integer constant followed immediately by dotdot is recognized as such; it is
not treated as a floating constant followed by a dot. That is to say,
.code 123..
does not mean
.code "123. ."
(floating point
.code 123.0
value followed by dot token).  It means
.code "123 .."
(integer
.code 123
followed by
.code ..
token).

Dialect note: unlike in Common Lisp,
.code 123.
is not an integer, but the floating-point number
.codn 123.0 .

.SS* Comments

Comments of the form
.code @;
were already covered. Inside directives,
comments are introduced just by a
.code ;
character.

Example:

.cblk
  @(foo  ; this is a comment
    bar  ; this is another comment 
    )
.cble

This is equivalent to
.codn "@(foo bar)" .

.SS* Directives-driven Syntax

Some directives not only denote an expression, but are also involved in
surrounding syntax. For instance, the directive

.cblk
  @(collect)
.cble

not only denotes an expression, but it also introduces a syntactic phrase which
requires a matching
.code @(end)
directive. In other words,
.code @(collect)
is not only
an expression, but serves as a kind of token in a higher level phrase structure
grammar.

Usually if this type of "syntactic directive" occurs alone in a line, not
preceded or followed by other material, it is involved in a "vertical" (or line
oriented) syntax.

If such a directive is embedded in a line (has preceding or trailing material)
then it is in a horizontal syntactic and semantic context (character-oriented).

There is an exception: the definition of a horizontal function looks like this:

.cblk
  @(define name (arg))body material@(end)
.cble

Yet, this is considered one vertical item, which means that it does not match
a line of data. (This is necessary because all horizontal syntax matches
something within a line of data, which is undesirable for definitions.)

Many directives exhibit both horizontal and vertical syntax, with different but
closely related semantics. A few are vertical only, and some are
horizontal only.

A summary of the available directives follows:

.coIP @(eof)
Explicitly match the end of file. Fails if unmatched data remains in
the input stream.

.coIP @(eol)
Explicitly match the end of line. Fails if the current position is not the
end of a line. Also fails if no data remains (there is no current line).

.coIP @(next)
Continue matching in another file or other data source.

.coIP @(block)
Groups together a sequence of directives into a logical name block,
which can be explicitly terminated from within using
the
.code @(accept)
and
.code @(fail)
directives.
Blocks are described in the section BLOCKS below.

.coIP @(skip)
Treat the remaining query as a subquery unit, and search the lines (or
characters) of the input file until that subquery matches somewhere.  A skip is
also an anonymous block.

.coIP @(trailer)
Treat the remaining query or subquery as a match for a trailing context. That
is to say, if the remainder matches, the data position is not advanced.

.coIP @(freeform)
Treat the remainder of the input as one big string, and apply the following
query line to that string. The newline characters (or custom separators) appear
explicitly in that string.

.coIP @(fuzz)
The fuzz directive, inspired by the patch utility, specifies a partial
match for some lines.

.ccIP @ @(line) and @ @(chr)
These directives match a variable or expression against the current line
number or character position.

.coIP @(name)
Match a variable against the name of the current data source.

.coIP @(data)
Match a variable against the remaining data (lazy list of strings).

.coIP @(some)
Multiple clauses are each applied to the same input. Succeeds if at least one
of the clauses matches the input. The bindings established by earlier
successful clauses are visible to the later clauses.

.coIP @(all)
Multiple clauses are applied to the same input. Succeeds if and only if each
one of the clauses matches. The clauses are applied in sequence, and evaluation
stops on the first failure. The bindings established by earlier successful
clauses are visible to the later clauses.

.coIP @(none)
Multiple clauses are applied to the same input. Succeeds if and only if none of
them match. The clauses are applied in sequence, and evaluation stops on the
first success. No bindings are ever produced by this construct.

.coIP @(maybe)
Multiple clauses are applied to the same input. No failure occurs if none of
them match.  The bindings established by earlier successful clauses are visible
to the later clauses.

.coIP @(cases)
Multiple clauses are applied to the same input. Evaluation stops on the
first successful clause.

.coIP @(require)
The require directive is similar to the do directive: it evaluates one or more
\*(TL expressions.  If the result of the rightmost expression is nil,
then require triggers a match failure.  See the TXR LISP section far below.

.ccIP @, @(if) @, @(elif) and @ @(else)
The
.code if
directive with optional
.code elif
and
.code else
clauses allows one of multiple bodies of pattern matching directives to be
conditionally selected by testing the values of Lisp expressions.

.coIP @(choose)
Multiple clauses are applied to the same input. The one whose effect persists
is the one which maximizes or minimizes the length of a particular variable.

.coIP @(empty)
The
.code @(empty)
directive matches the empty string. It is useful in certain
situations, such as expressing an empty match in a directive that doesn't
accept an empty clause. The
.code @(empty)
syntax has another meaning in
.code @(output)
clauses, in conjunction with
.codn @(repeat) .

.meIP @(define < name >> ( args ...))
Introduces a function. Functions are described in the Functions section below.

.meIP @(call < expr << args *)
Performs function indirection.  Evaluates
.metn expr ,
which must produce a symbol that names a pattern function. Then that
pattern function is invoked.

.coIP @(gather)
Searches text for matches for multiple clauses which may occur in arbitrary
order. For convenience, lines of the first clause are treated as separate
clauses.

.coIP @(collect)
Search the data for multiple matches of a clause. Collect the
bindings in the clause into lists, which are output as array variables.
The
.code @(collect)
directive is line oriented. It works with a multi-line
pattern and scans line by line. A similar directive called
.code @(coll)
works within one line.

A collect is an anonymous block.

.coIP @(and)
Separator of clauses for
.codn @(some) ,
.codn @(all) ,
.codn @(none) ,
.code @(maybe)
and
.codn @(cases) .
Equivalent to
.codn @(or) .
The choice is stylistic.

.coIP @(or)
Separator of clauses for
.codn @(some) ,
.codn @(all) ,
.codn @(none) ,
.code @(maybe)
and
.codn @(cases) .
Equivalent to
.codn @(and) .
The choice is stylistic.

.coIP @(end)
Required terminator for
.codn @(some) ,
.codn @(all) ,
.codn @(none) ,
.codn @(maybe) ,
.codn @(cases) ,
.codn @(if) ,
.codn @(collect) ,
.codn @(coll) ,
.codn @(output) ,
.codn @(repeat) ,
.codn @(rep) ,
.codn @(try) ,
.code @(block)
and
.codn @(define) .

.coIP @(fail)
Terminate the processing of a block, as if it were a failed match.
Blocks are described in the section BLOCKS below.

.coIP @(accept)
Terminate the processing of a block, as if it were a successful match.
What bindings emerge may depend on the kind of block: collect
has special semantics.  Blocks are described in the section BLOCKS below.

.coIP @(try)
Indicates the start of a try block, which is related to exception
handling, described in the EXCEPTIONS section below.

.ccIP @ @(catch) and @ @(finally)
Special clauses within
.codn @(try) .
See EXCEPTIONS below.

.ccIP @ @(defex) and @ @(throw)
Define custom exception types; throw an exception.  See EXCEPTIONS below.

.coIP @(assert)
The assert directive requires the following material to match, otherwise
it throws an exception. It is useful for catching mistakes or omissions
in parts of a query that are sure-fire matches.

.coIP @(flatten)
Normalizes a set of specified variables to one-dimensional lists. Those
variables which have scalar value are reduced to lists of that value.
Those which are lists of lists (to an arbitrary level of nesting) are converted
to flat lists of their leaf values.

.coIP @(merge)
Binds a new variable which is the result of merging two or more
other variables. Merging has somewhat complicated semantics.

.coIP @(cat)
Decimates a list (any number of dimensions) to a string, by catenating its
constituent strings, with an optional separator string between all of the
values.

.coIP @(bind)
Binds one or more variables against a value using a structural
pattern match. A limited form of unification takes place which can cause a
match to fail.

.coIP @(set)
Destructively assigns one or more existing variables using a structural
pattern, using syntax similar to bind. Assignment to unbound
variables triggers an error.

.coIP @(rebind)
Evaluates an expression in the current binding environment, and
then creates new bindings for the variables in the structural pattern.
Useful for temporarily overriding variable values in a scope.

.coIP @(forget)
Removes variable bindings.

.coIP @(local)
Synonym of
.codn @(forget) .

.coIP @(output)
A directive which encloses an output clause in the query. An output section
does not match text, but produces text. The directives above are not
understood in an output clause.

.coIP @(repeat)
A directive understood within an @(output) section, for repeating multi-line
text, with successive substitutions pulled from lists. The directive
.code @(rep)
produces iteration over lists horizontally within one line. These directives
have a different meaning in matching clauses, providing a shorthand
notation for
.code "@(repeat :vars nil)"
and
.codn "@(rep :vars nil)" ,
respectively.

.coIP @(deffilter)
This directive is used for defining named filters, which are useful
for filtering variable substitutions in output blocks. Filters are useful
when data must be translated between different representations that
have different special characters or other syntax, requiring escaping
or similar treatment. Note that it is also possible to use a function
as a filter. See Function Filters below.

.coIP @(filter)
The filter directive passes one or more variables through a given
filter or chain or filters, updating them with the filtered values.

.ccIP @ @(load) and @ @(include)
These directives allow \*(TX programs to be modularized. They bring in
code from a file, in two different ways.

.coIP @(do)
The do directive is used to evaluate \*(TL expressions, discarding their
result values. See the TXR LISP section far below.

.PP

.SH* DIRECTIVES

.SS* Input Scanning and Data Manipulation

.dir next

The
.code next
directive indicates that the remaining directives in the current block
are to be applied against a new input source.

It can only occur by itself as the only element in a query line,
and takes various arguments, according to these possibilities:

.cblk
.mets @(next)
.mets @(next << source )
.mets @(next < source :nothrow)
.mets @(next :args)
.mets @(next :env)
.mets @(next :list << expr )
.mets @(next :string << expr )
.mets @(next nil)
.cble

The lone
.code @(next)
without arguments specifies that subsequent directives
will match inside the next file in the argument list which was passed
to \*(TX on the command line.

If
.meta source
is given, it must be a \*(TL expression which denotes an
input source. Its value may be a string or an input stream.
For instance, if variable
.code A
contains the text
.strn "data" ,
then
.code "@(next A)"
means switch to the file called
.strn "data" ,
and
.code "@(next `@A.txt`)"
means to switch to the file
.strn "data.txt" .
The directive
.code "@(next (open-command `git log`))"
switches to the input stream connected to the output of the
.code "git log"
command.

If the input source cannot be opened for whatever reason,
\*(TX throws an exception (see EXCEPTIONS below). An unhandled exception will
terminate the program.  Often, such a drastic measure is inconvenient;
if
.code @(next)
is invoked with the
.code :nothrow
keyword, then if the input
source cannot be opened, the situation is treated as a simple
match failure.

The variant
.code "@(next :args)"
means that the remaining command line arguments are to
be treated as a data source. For this purpose, each argument is considered to
be a line of text. The argument list does include that argument which specifies
the file that is currently being processed or was most recently processed.
As the arguments are matched, they are consumed. This means that if a
.code @(next)
directive without
arguments is executed in the scope of
.codn "@(next :args)" ,
it opens the file named
by the first unconsumed argument.

To process arguments, and then continue with the original file and argument
list, wrap the argument processing in a
.codn @(block) .
When the block terminates, the input source and argument list are restored
to what they were before the block.

The variant
.code "@(next :env)"
means that the list of process environment variables
is treated as a source of data. It looks like a text file stream
consisting of lines of the form
.strn "name=value" .
If this feature is not available
on a given platform, an exception is thrown.

The syntax
.cblk
.meti @(next :list << expr )
.cble
treats expression
.meta expr
as a source of
text. The value of
.meta expr
is flattened to a simple list in a way similar to the
.code @(flatten)
directive.  The resulting list is treated as if it were the
lines of a text file: each element of the list must be a string,
which represents a line.  If the strings happen contain embedded newline
characters, they are a visible constituent of the line, and do not act as line
separators.

The syntax
.cblk
.meti @(next :string << expr )
.cble
treats expression
.meta expr
as a source of text. The value of the expression must be a string. Newlines in
the string are interpreted as line terminators.

A string which is not terminated by a newline is tolerated, so that:

.cblk
  @(next :string "abc")
  @a
.cble

binds
.code a
to
.strn "abc" .
Likewise, this is also the case with input files and other
streams whose last line is not terminated by a newline.

However, watch out for empty strings, which are analogous to a correctly formed
empty file which contains no lines:

.cblk
  @(next :string "")
  @a
.cble

This will not bind
.code a
to
.strn "" ;
it is a matching failure.  The behavior of
.code :list
is
different. The query

.cblk
  @(next :list "")
  @a
.cble

binds
.code a
to
.strn "" .
The reason is that under
.code :list
the string
.str ""
is flattened to
the list
.cblk
("")
.cble
which is not an empty input stream, but a stream consisting of
one empty line.

The
.code "@(next nil)"
variant indicates that the following subquery is applied to empty data,
and the list of data sources from the command line is considered empty.
This directive is useful in front of \*(TX code which doesn't process data
sources from the command line, but takes command line arguments.
The
.code "@(next nil)"
incantation absolutely prevents \*(TX from trying to open the
first command line argument as a data source.

Note that the
.code @(next)
directive only redirect the source of input over the scope of subquery in which
the next directive appears, not necessarily all remaining directives.  For
example, the following query looks for the line starting with
.str "xyz"
at the top of the file
.strn "foo.txt" ,
within a some
directive.  After the
.code @(end)
which terminates the
.codn @(some) ,
the
.str "abc"
is matched in the previous input stream which was in effect before
the
.code
@(next)
directive:

.cblk
  @(some)
  @(next "foo.txt")
  xyz@suffix
  @(end)
  abc
.cble

However, if the
.code @(some)
subquery successfully matched
.str "xyz@suffix"
within the
file
.codn foo.text ,
there is now a binding for the
.code suffix
variable, which
is visible to the remainder of the entire query. The variable bindings
survive beyond the clause, but the data stream does not.

The
.code @(next)
directive supports the file name conventions as the command
line. The name
.code -
means standard input. Text which starts with a
.code !
is
interpreted as a shell command whose output is read like a file.  These
interpretations are applied after variable substitution. If the file is
specified as
.codn @a ,
but the variable a expands to
.strn "!echo foo" ,
then the output of
the
.str "echo foo"
command will be processed.

.dir skip

The
.code skip
directive considers the remainder of the query as a search
pattern. The remainder is no longer required to strictly match at the
current line in the current input stream. Rather, the current stream is searched,
starting with the current line, for the first line where the entire remainder
of the query will successfully match. If no such line is found, the
.code skip
directive fails. If a matching position is found, the remainder of
the query is processed from that point.

Of course, the remainder of the query can itself contain skip directives.
Each such directive performs a recursive subsearch.

Skip comes in vertical and horizontal flavors. For instance, skip and match the
last line:

.cblk
  @(skip)
  @last
  @(eof)
.cble

Skip and match the last character of the line:

.cblk
  @(skip)@{last 1}@(eol)
.cble

The skip directive has two optional arguments. If the first argument is a
number, its value limits the range of lines scanned for a match. Judicious use
of this feature can improve the performance of queries.

Example: scan until
.str "size: @SIZE"
matches, which must happen within
the next 15 lines:

.cblk
  @(skip 15)
  size: @SIZE
.cble

Without the range limitation skip will keep searching until it consumes
the entire input source.  In a horizontal
.codn skip ,
the range-limiting numeric argument is expressed in characters, so that

.cblk
  abc@(skip 5)def
.cble

means: there must be a match for
.str "abc"
at the start of the line, and then within the next five characters,
there must be a match for
.strn "def" .

Sometimes a skip is nested within a
.codn collect ,
or
following another skip. For instance, consider:

.cblk
  @(collect)
  begin @BEG_SYMBOL
  @(skip)
  end @BEG_SYMBOL
  @(end)
.cble

The above
.code collect
iterates over the entire input. But, potentially, so does
the embedded
.codn skip .
Suppose that
.str "begin x"
is matched, but the data has no
matching
.strn "end x" .
The skip will search in vain all the way to the end of the
data, and then the collect will try another iteration back at the
beginning, just one line down from the original starting point.  If it is a
reasonable expectation that an
.code "end x"
occurs 15 lines of a
.strn "begin x" ,
this can be specified instead:

.cblk
  @(collect)
  begin @BEG_SYMBOL
  @(skip 15)
  end @BEG_SYMBOL
  @(end)
.cble

If the symbol
.code nil
is used in place of a number, it means to scan
an unlimited range of lines; thus,
.code "@(skip nil)"
is equivalent to
.codn @(skip) .

If the symbol
.code :greedy
is used, it changes the semantics of the skip
to longest match semantics.  For instance, match the last three space-separated
tokens of the line:

.cblk
  @(skip :greedy) @a @b @c
.cble

Without
.codn :greedy ,
the variable
.code @c
will can match multiple tokens,
and end up with spaces in it, because nothing follows
.code @c
and so it matches from any position which follows a space to the
end of the line.  Also note the space in front of
.codn @a .
Without this
space,
.code @a
will get an empty string.

A line oriented example of greedy skip: match the last line without
using
.codn @eof :

.cblk
  @(skip :greedy)
  @last_line
.cble

There may be a second numeric argument. This specifies a minimum
number of lines to skip before looking for a match. For instance,
skip 15 lines and then search indefinitely for
.codn "begin ..." :

.cblk
  @(skip nil 15)
  begin @BEG_SYMBOL
.cble

The two arguments may be used together. For instance, the following
matches if, and only if, the 15th line of input starts with
.codn "begin " :

.cblk
  @(skip 1 15)
  begin @BEG_SYMBOL
.cble

Essentially,
.cblk
.meti @(skip 1 << n )
.cble
means "hard skip by
.meta n
lines".
.code "@(skip 1 0)"
is the same as
.codn "@(skip 1)" ,
which is a noop, because it means: "the remainder of the query must match
starting on the very next line", or, more briefly, "skip exactly zero lines",
which is the behavior if the skip directive is omitted altogether.

Here is one trick for grabbing the fourth line from the bottom of the input:

.cblk
  @(skip)
  @fourth_from_bottom
  @(skip 1 3)
  @(eof)
.cble

Or using greedy skip:

.cblk
  @(skip :greedy)
  @fourth_from_bottom
  @(skip 1 3)
.cble

Nongreedy skip with the
.code @(eof)
has a slight advantage because the greedy skip
will keep scanning even though it has found the correct match, then backtrack
to the last good match once it runs out of data. The regular skip with explicit
.code @(eof)
will stop when the
.code @(eof)
matches.

.NP* Reducing Backtracking with Blocks

.code skip
can consume considerable CPU time when multiple skips are nested.  Consider:

.cblk
  @(skip)
  A
  @(skip)
  B
  @(skip)
  C
.cble

This is actually nesting: the second a third skips occur within the body of the
first one, and thus this creates nested iteration. \*(TX is searching for the
combination of skips which find match the pattern of lines
.codn A ,
.code B
and
.codn C ,
with
backtracking behavior. The outermost skip marches through the data until it
finds
.codn A ,
followed by a pattern match for the second skip. The second skip
iterates within to find
.codn B ,
followed by the third skip, and the third skip
iterates to find
.codn C .
If there is only one line
.codn A ,
and one
.codn B ,
then this is reasonably fast. But suppose there are many lines matching
.code A
and
.codn B ,
giving rise to a large number combinations of skips which match
.code A
and
.codn B ,
and yet do not find a match for
.codn C ,
triggering backtracking. The nested stepping which tries
the combinations of
.code A
and
.code B
can give rise to a considerable running time.

One way to deal with the problem is to unravel the nesting with the help of
blocks. For example:

.cblk
  @(block)
  @  (skip)
  A
  @(end)
  @(block)
  @  (skip)
  B
  @(end)
  @(skip)
  C
.cble

Now the scope of each skip is just the remainder of the block in which it
occurs. The first skip finds
.codn A ,
and then the block ends. Control passes to the
next block, and backtracking will not take place to a block which completed
(unless all these blocks are enclosed in some larger construct which
backtracks, causing the blocks to be re-executed.

Of course, this rewrite is not equivalent, and cannot be used for instance
in backreferencing situations such as:

.cblk
  @;
  @; Find three lines anywhere in the input which are identical.
  @;
  @(skip)
  @line
  @(skip)
  @line
  @(skip)
  @line
.cble

This example depends on the nested search-within-search semantics.

.dir trailer

The
.code trailer
directive introduces a trailing portion of a query or subquery
which matches input material normally, but in the event of a successful match,
does not advance the current position. This can be used, for instance, to
cause
.code @(collect)
to match partially overlapping regions.

Example:

.cblk
  @(collect)
  @line
  @(trailer)
  @(skip)
  @line
  @(end)
.cble

This script collects each line which has a duplicate somewhere later
in the input. Without the
.code @(trailer)
directive, this does not work properly
for inputs like:

.cblk
  111
  222
  111
  222
.cble

Without
.codn @(trailer) ,
the first duplicate pair constitutes a match which
spans over the
.codn 222 .
After that pair is found, the matching continues
after the second
.codn 111 .

With the
.code @(trailer)
directive in place, the collect body, on each
iteration, only consumes the lines matched prior to
.codn @(trailer) .

.dir freeform

The
.code freeform
directive provides a useful alternative to
\*(TX's line-oriented matching discipline. The freeform directive treats all
remaining input from the current input source as one big line. The query line
which immediately follows freeform is applied to that line.

The syntax variations are:

.cblk
  @(freeform)
  ... query line ..

.mets @(freeform << number )
  ... query line ..

.mets @(freeform << string )
  ... query line ..

.mets @(freeform < number << string )
  ... query line ..
.cble

If
.meta number
and
.meta string
are both present, they may be given in either order.

If a numeric argument is given, it limits the range of lines which are combined
together. For instance
.code "@(freeform 5)"
means to only consider the next five lines
to to be one big line. Without a numeric argument, freeform is "bottomless". It
can match the entire file, which creates the risk of allocating a large amount
of memory.

If a string argument is given, it specifies a custom line terminator. The
default terminator is
.strn "\en" .
The terminator does not have to be one character long.

Freeform does not convert the entire remainder of the input into one big line
all at once, but does so in a dynamic, lazy fashion, which takes place as the
data is accessed. So at any time, only some prefix of the data exists as a flat
line in which newlines are replaced by the terminator string, and the remainder
of the data still remains as a list of lines.

After the subquery is applied to the virtual line, the unmatched remainder
of that line is broken up into multiple lines again, by looking for and
removing all occurrences of the terminator string within the flattened portion.

Care must be taken if the terminator is other than the default
.strn "\en" .
All occurrences of the terminator string are treated as line terminators in
the flattened portion of the data, so extra line breaks may be introduced.
Likewise, in the yet unflattened portion, no breaking takes place, even if
the text contains occurrences of the terminator string. The extent of data which
is flattened, and the amount of it which remains, depends entirely on the
query line underneath
.codn @(flatten) .

In the following example, lines of data are flattened using $ as the line
terminator.
.IP code:
.cblk
\ @(freeform "$")
 @a$@b:
 @c
 @d
.cble

.IP data:
.cblk
\ 1
 2:3
 4
.cble

.IP "output (\f[4]-B\f[]):"
.cblk
\ a="1"
 b="2"
 c="3"
 d="4"
.cble
.PP

The data is turned into the virtual line
.codn 1$2:3$4$ .
The
.code @a$@b:
subquery matches
the
.code 1$2:
portion, binding
.code a
to
.strn 1 ,
and
.code b
to
.strn 2 .
The remaining portion
.code 3$4$
is then split into separate lines again according to the line terminator
.codn $i :

.cblk
  3
  4
.cble

Thus the remainder of the query

.cblk
  @c
  @d
.cble

faces these lines, binding
.code c
to
.code 3
and
.code d
to
.codn 4 .
Note that since the data
does not contain dollar signs, there is no ambiguity; the meaning may be
understood in terms of the entire data being flattened and split again.

In the following example,
.code freeform
is used to solve a tokenizing problem.  The
Unix password file has fields separated by colons. Some fields may be empty.
Using freeform, we can join the password file using
.str ":"
as a terminator.
By restricting freeform to one line, we can obtain each line of the password
file with a terminating
.strn ":" ,
allowing for a simple tokenization, because
now the fields are colon-terminated rather than colon-separated.

Example:

.cblk
  @(next "/etc/passwd")
  @(collect)
  @(freeform 1 ":")
  @(coll)@{token /[^:]*/}:@(end)
  @(end)
.cble

.dir fuzz

The
.code fuzz
directive allows for an imperfect match spanning a set number of
lines. It takes two arguments, both expressions that should evaluate
to integers:

.cblk
  @(fuzz m n)
  ...
.cble

This expresses that over the next n query lines, the matching strictness
is relaxed a little bit. Only m out of those n lines have to match.
Afterward, the rest of the query follows normal, strict processing.

In the degenerate situation that there are fewer than n query lines following
the
.code fuzz
directive, then m of them must succeed nevertheless. (If there
are fewer than m, then this is impossible.)

.dirs line chr

The
.code line
and
.code chr
directives perform binding between the current input line number or character
position within a line, against an expression or variable:

.cblk
  @(line 42)
  @(line x)
  abc@(chr 3)def@(chr y)
.cble

The directive
.code "@(line 42)"
means "match the current input line number against the integer 42". If
the current line is 42, then the directive matches, otherwise it fails.
.code line
is a vertical directive which doesn't consume a line of input. Thus,
the following matches at the beginning of an input stream, and
.code x
ends up bound to the first line of input:

.cblk
  @(line 1)
  @(line 1)
  @(line 1)
  @x
.cble

The directive
.code "@(line x)"
binds variable
.code x
to the current input line number, if
.code x
is an unbound variable. If
.code x
is already bound, then the value of
.code x
must match the current line number, otherwise the directive fails.

The
.code chr
directive is similar to
.code line
except that it's a horizontal directive, and matches the character position
rather than the line position. Character positions are measured from zero,
rather than one.
.code chr
does not consume a character. Hence the two occurrences of
.code chr
in the following example both match, and
.code x
takes the entire line of input:

.cblk
  @(chr 0)@(chr 0)@x
.cble

The argument of
.code line
or
.code chr
may be a
.codn @ -delimited
Lisp expression. This is useful for matching computed lines or
character positions:

.cblk
  @(line @(+ a (* b c)))
.cble

.dir name

The
.code name
directive performs a binding between the name of the current
data source and a variable or expression:

.cblk
  @(name na)
  @(name "data.txt")
.cble

If
.code na
is an unbound variable, it is bound and takes on the name
of the data source, such as a file name. If
.code na
is bound, then it has to match the name of the data source,
otherwise the directive fails.

The directive
.cblk
@(name "data.txt")
.cble
fails unless the current data source has that name.

.dir data

The
.code data
directive performs a binding between the unmatched data
at the current position, and and a variable or expression.
The unmatched data takes the form of a list of strings:

.cblk
  @(data d)
.cble

The binding is performed on object equality. If
.code d
is already bound, a matching failure occurs unless
.code d
contains the current unmatched data.

Matching the current data has various uses.

For instance, two branches of pattern matching can, at some point, bind the
current data into different variables. When those paths join, the variables can
be bound together to create the assertion that the current data had been the
same at those points:

.cblk
  @(all)
  @  (skip)
  foo
  @  (skip)
  bar
  @  (data x)
  @(or)
  @  (skip)
  xyzzy
  @  (skip)
  bar
  @  (data y)
  @(end)
  @(require (eq x y))
.cble

Here, two branches of the
.code @(all)
match some material which ends in the line
.codn "bar" .
However, it is possible that this is a different line. The
.code data
directives are used to create an assertion that the data regions matched
by the two branches are identical. That is to say, the unmatched data
.code x
captured after the first
.code "bar"
and the unmatched data
.code y
captured after the second
.code "bar"
must be the same object in order for
.code "@(require (eq x y))"
to succeed, which implies that the same
.code "bar"
was matched in both branches of the
.codn @(all) .

Another use of
.code data
is simply to gain access to the trailing remainder of the unmatched
input in order to print it, or do some special processing on it.

The
.code tprint
Lisp function is useful for printing the unmatched data as newline-terminated
lines:

.cblk
  @(data remainder)
  @(do (tprint remainder))
.cble

.dirs some all none maybe cases choose

These directives, called the parallel directives, combine multiple subqueries,
which are applied at the same input position, rather than to consecutive input.

They come in vertical (line mode) and horizontal (character mode) flavors.

In horizontal mode, the current position is understood to be a character
position in the line being processed. The clauses advance this character
position by moving it to the right.  In vertical mode, the current position is
understood to be a line of text within the stream. A clause advances the
position by some whole number of lines.

The syntax of these parallel directives follows this example:

.cblk
  @(some)
  subquery1
  .
  .
  .
  @(and)
  subquery2
  .
  .
  .
  @(and)
  subquery3
  .
  .
  .
  @(end)
.cble

And in horizontal mode:

.cblk
  @(some)subquery1...@(and)subquery2...@(and)subquery3...@(end)
.cble

Long horizontal lines can be broken up with line continuations, allowing the
above example to be written like this, which is considered a single logical
line:

.cblk
  @(some)@\e
     subquery1...@\e
  @(and)@\e
     subquery2...@\e
  @(and)@\e
     subquery3...@\e
  @(end)
.cble

The
.codn @(some) ,
.codn @(all) ,
.codn @(none) ,
.codn @(maybe) ,
.code @(cases)
or
.code @(choose)
must be followed
by at least one subquery clause, and be terminated by
.codn @(end) .
If there are two
or more subqueries, these additional clauses are indicated by
.code @(and)
or
.codn @(or) ,
which are interchangeable.  The separator and terminator directives also must
appear as the only element in a query line.

The
.code choose
directive requires keyword arguments. See below.

The syntax supports arbitrary nesting. For example:

.cblk
  QUERY:            SYNTAX TREE:

  @(all)            all -+
  @  (skip)              +- skip -+
  @  (some)              |        +- some -+
  it                     |        |        +- TEXT
  @  (and)               |        |        +- and
  @    (none)            |        |        +- none -+
  was                    |        |        |        +- TEXT
  @    (end)             |        |        |        +- end
  @  (end)               |        |        +- end
  a dark                 |        +- TEXT
  @(end)                 *- end
.cble

nesting can be indicated using whitespace between
.code @
and the
directive expression. Thus, the above is an
.code @(all)
query containing a
.code @(skip)
clause which applies to a
.code @(some)
that is followed by the text line
.strn "a dark" .
The
.code @(some)
clause combines the text line
.strn it ,
and a
.code @(none)
clause which contains just one clause consisting of the line
.strn was .

The semantics of the parallel directives is:

.coIP @(all)
Each of the clauses is matched at the current position. If any of the
clauses fails to match, the directive fails (and thus does not produce
any variable bindings). Clauses following the failed directive are not
evaluated. Bindings extracted by a successful clause are visible to the clauses
which follow, and if the directive succeeds, all of the combined bindings
emerge.

.meIP @(some [ :resolve >> ( var ...) ])
Each of the clauses is matched at the current position. If any of the clauses
succeed, the directive succeeds, retaining the bindings accumulated by the
successfully matching clauses.  Evaluation does not stop on the first successful
clause. Bindings extracted by a successful clause are visible to the clauses
which follow.

The
.code :resolve
parameter is for situations when the
.code @(some)
directive has
multiple clauses that need to bind some common variables to different
values: for instance, output parameters in functions. Resolve takes
a list of variable name symbols as an argument.  This is called the
resolve set. If the clauses of
.code @(some)
bind variables in the resolve
set, those bindings are not visible to later clauses.  However, those
bindings do emerge out of the
.code @(some)
directive as a whole.
This creates a conflict: what if two or more clauses introduce
different bindings for a variable in the resolve set?
This is why it is called the resolve set: conflicts for variables in the
resolve set are automatically resolved in favor of later directives.

Example:

.cblk
  @(some :resolve (x))
  @  (bind a "a")
  @  (bind x "x1")
  @(or)
  @  (bind b "b")
  @  (bind x "x2")
  @(end)
.cble

Here, the two clauses both introduce a binding for
.codn x .
Without the
.code :resolve
parameter, this would mean that the second clause fails, because
.code x
comes in
with the value
.strn x1 ,
which does not bind with
.strn x2 .
But because
.code x
is placed
into the resolve set, the second clause does not see the 
.str x1
binding. Both
clauses establish their bindings independently creating a conflict over
.codn x .
The conflict is resolved in favor of the second clause, and so the bindings
which emerge from the directive are:

.cblk
  a="a"
  b="b"
  x="x2"
.cble

.coIP @(none)
Each of the clauses is matched at the current position. The
directive succeeds only if all of the clauses fail. If
any clause succeeds, the directive fails, and subsequent clauses are not
evaluated. Thus, this directive never produces variable bindings, only matching
success or failure.

.coIP @(maybe)
Each of the clauses is matched at the current position.  The directive always
succeeds, even if all of the clauses fail.  Whatever bindings are found in any
of the clauses are retained. Bindings extracted by any successful clause are
visible to the clauses which follow.

.coIP @(cases)
Each of the clauses is matched at the current position.
The clauses are matched, in order, at the current position.
If any clause matches, the matching stops and the bindings
collected from that clause are retained. Any remaining clauses
after that one are not processed. If no clause matches, the
directive fails, and produces no bindings.

.meIP @(choose [ :longest < var | :shortest < var ])
Each of the clauses is matched at the current position in order. In this
construct, bindings established by an earlier clause are not visible to later
clauses.  Although any or all of the clauses can potentially match, the clause
which succeeds is the one which maximizes or minimizes the length of the
text bound to the specified variable. The other clauses have no effect.

For all of the parallel directives other than
.code @(none)
and
.codn @(choose) ,
the query
advances the input position by the greatest number of lines that match in any
of the successfully matching subclauses that are evaluated.  The
.code @(none)
directive does not advance the input position.

For instance if there are two subclauses, and one of them matches three lines,
but the other one matches five lines, then the overall clause is considered to
have made a five line match at its position. If more directives follow, they
begin matching five lines down from that position.

.dir require

The syntax of
.code @(require)
is:

.cblk
.mets @(require << lisp-expression )
.cble

The require directive evaluates a \*(TL expression. (See TXR LISP far
below.) If the expression yields a true value, then it succeeds, and matching
continues with the directives which follow. Otherwise the directive fails.

In the context of the
.code require
directive, the expression should not be introduced by the
.code @
symbol; it is expected to be a Lisp expression.

Example:

.cblk
  @; require that 4 is greater than 3
  @; This succeeds; therefore, @a is processed
  @(require (> (+ 2 2) 3))
  @a
.cble

.dir if

The
.code if
directive allows for conditional selection of pattern matching clauses,
based on the Boolean results Lisp expressions.

The syntax of the
.code if
directive can be exemplified as follows:

.cblk
.mets @(if << lisp-expr )
  .
  .
  .
.mets @(elif << lisp-expr )
  .
  .
  .
.mets @(elif << lisp-expr )
  .
  .
  .
  @(else)
  .
  .
  .
  @(end)
.cble

The
.code @(elif)
and
.code @(else)
clauses are all optional. If
.code @(else)
is present, it must be
last, before
.codn @(end) ,
after any
.code @(elif)
clauses. Any of the clauses may be empty.

See the \*(TL section about \*(TL expressions. In this directive,
\*(TL expressions are not introduced by the
.code @
symbol, just like in the
.code require
directive.

For example:

.cblk
  @(if (> (length str) 42))
  foo: @a @b
  @(else)
  {@c}
  @(end)
.cble

In this example, if the length of the variable
.code str
is greater than
.codn 42 ,
then matching continues with
.strn "foo: @a b" ,
otherwise it proceeds with
.codn {@c} .

More precisely, how the
.code if
directive works is as follows. The Lisp expressions are evaluated in order,
starting with the
.code if
expression, then the
.code elif
expressions if any are present. If any Lisp expression yields a true result
(any value other than
.codn nil )
then evaluation of Lisp expressions stops. The corresponding clause of that
Lisp expression is selected and pattern matching continues
with that clauses. The result of that clause (its success or failure,
and any newly bound variables) is then taken as the result of the
.code if
directive. If none of the Lisp expressions yield true, and an
.code else
clause is present, then that clause is processed and its result determines
the result of the
.code if
directive. If none of the Lisp expressions
yield true, and there is no
.code else
clause, then the
.code if
directive is deemed to have trivially succeeded, allowing matching to continue
with whatever directive follows it.

.dir gather

Sometimes text is structured as items that can appear in an arbitrary order.
When multiple matches need to be extracted, there is a combinatorial explosion
of possible orders, making it impractical to write pattern matches for all
the possible orders.

The
.code gather
directive is for these situations. It specifies multiple clauses
which all have to match somewhere in the data, but in any order.

For further convenience, the lines of the first clause of the
.code gather
directive
are implicitly treated as separate clauses.

The syntax follows this pattern

.cblk
  @(gather)
  one-line-query1
  one-line-query2
  .
  .
  .
  one-line-queryN
  @(and)
  multi
  line
  query1
  .
  .
  .
  @(and)
  multi
  line
  query2
  .
  .
  .
  @(end)
.cble

Of course the multi-line clauses are optional.   The
.code gather
directive takes
keyword parameters, see below.

.coNP The @ until / @ last clause in @ gather

Similarly to
.codn collect ,
.code gather
has an optional
.cod3 until / last
clause:

.cblk
  @(gather)
  ...
  @(until)
  ...
  @(end)
.cble

How gather works is that the text is searched for matches for the single line
and multi-line queries. The clauses are applied in the order in which they appear.
Whenever one of the clauses matches, any bindings it produces are retained and
it is removed from further consideration. Multiple clauses can match at the
same text position.  The position advances by the longest match from among the
clauses which matched.  If no clauses match, the position advances by one line.
The search stops when all clauses are eliminated, and then the cumulative
bindings are produced.  If the data runs out, but unmatched clauses remain, the
directive fails.

Example: extract several environment variables, which do not appear in a particular
order:

.cblk
  @(next :env)
  @(gather)
  USER=@USER
  HOME=@HOME
  SHELL=@SHELL
  @(end)
.cble

If the until or last clause is present and a match occurs, then the matches
from the other clauses are discarded and the gather terminates. The difference
between
.cod3 until / last
is that any bindings bindings established in last are
retained, and the input position is advanced past the matched material.
The
.cod3 until / last
clause has visibility to bindings established in the
previous clauses in that same iteration, even though those bindings
end up thrown away.

For consistency, the
.code :mandatory
keyword is supported in the
.cod3 until / last
clause of
.codn gather .
The semantics of using
.code :mandatory
in this situation is tricky. In particular, if it is in effect, and the
.code gather
terminates successfully by collecting all required matches, it will
trigger a failure. On the other hand, if the
.code until
or
.code last
clause activates before all required matches are gathered, a failure
also occurs, whether or not the clause is
.codn :mandatory .

Meaningful use of
.code :mandatory
requires that the gather be open-ended; it must allow some (or all) variables
not to be required. The presence of the option means that for the gather
to succeed, all required variables must be gathered first, but then termination
must be achieved via the
.cod3 until / last
clause before all gather clauses are satisfied.

.coNP Keyword parameters in @ gather
The
.code gather
directive accepts the keyword parameter
.codn :vars .
The argument to vars is
a list of required and optional variables.  Optional variables are denoted by
the specification of a default value. Example:

.cblk
  @(gather :vars (a b c (d "foo")))
  ...
  @(end)
.cble

Here,
.codn a ,
.codn b ,
.code c
and
.code e
are required variables, and
.code d
is optional.  Variable
.code e
is
required because its default value is the empty list
.codn () ,
same as the symbol
.codn nil .

The presence of
.code :vars
changes the behavior in three ways.

Firstly, even if all the clauses in the gather match successfully and are
eliminated, the directive will fail if the required variables do not have
bindings. It doesn't matter whether the bindings are existing, or whether they
are established by the gather.

Secondly, if some of the clauses of the gather did not match, but all
of the required variables have bindings, then the directive succeeds.
Without the presence of
.codn :vars ,
it would fail in this situation.

Thirdly, if
.code gather
succeeds (all required variables have bindings),
then all of the optional variables which do not have bindings are given
bindings to their default values.

.dir collect

The syntax of the
.code collect
directive is:

.cblk
  @(collect)
  ... lines of subquery
  @(end)
.cble

or with an until or last clause:

.cblk
  @(collect)
  ... lines of subquery: main clause
  @(until)
  ... lines of subquery: until clause
  @(end)

  @(collect)
  ... lines of subquery: main clause
  @(last)
  ... lines of subquery: last clause
  @(end)
.cble

The
.code repeat
symbol may be specified instead of
.codn collect ,
which changes the meaning, see below:

.cblk
  @(repeat)
  ... lines of subquery
  @(end)
.cble

The subquery is matched repeatedly, starting at the current line.
If it fails to match, it is tried starting at the subsequent line.
If it matches successfully, it is tried at the line following the
entire extent of matched data, if there is one. Thus, the collected regions do
not overlap. (Overlapping behavior can be obtained: see the
.code @(trailer)
directive).

Unless certain keywords are specified, or unless the collection is explicitly
failed with
.codn @(fail) ,
it always succeeds, even if it collects nothing,
and even if the
.cod3 until / last
clause never finds a match.

If no
.cod3 until / last
last clause is specified, and the collect is not limited
using parameters, the collection is unbounded: it consumes the entire data
file. If any query material follows such the
.code collect
clause, it will fail if it
tries to match anything in the current file; but of course, it is possible to
continue matching in another file by means of
.codn @(next) .

.coNP The @ until / @ last clause in @ collect

If an
.cod3 until / last
last clause is specified, the collection stops when that clause
matches at the current position.

If an
.code until
clause terminates collect, no bindings are collected at that
position, even if the main clause matches at that position also. Moreover, the
position is not advanced.  The remainder of the query begins matching at that
position.

If a last clause terminates collect, the behavior is different. Any bindings
captured by the main clause are thrown away, just like with the until clause.
However, the bindings in the last clause itself survive, and the position is
advanced to skip over that material.

Example:
.IP code:
.cblk
\ @(collect)
 @a
 @(until)
 42
 @b
 @(end)
 @c
.cble
.IP data:
.cblk
\ 1
 2
 3
 42
 5
 6
.cble
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 c="42"
.cble
.PP

The line
.code 42
is not collected, even though it matches
.codn @a .
Furthermore,
the
.code @(until)
does not advance the position, so variable
.code c
takes
.codn 42 .

If the
.code @(until)
is changed to
.code @(last)
the output will be different:
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 b="5"
 c="6"
.cble
.PP

The
.code 42
is not collected into the a list, just like before. But now
the binding captured by
.code @b
emerges. Furthermore, the position advances
so variable now takes
.codn 6 .

The binding variables within the clause of a collect are treated specially.
The multiple matches for each variable are collected into lists,
which then appear as array variables in the final output.

Example:
.IP code:
.cblk
\ @(collect)
 @a:@b:@c
 @(end)
.cble
.IP data:
.cblk
\ John:Doe:101
 Mary:Jane:202
 Bob:Coder:313
.cble
.IP result:
.cblk
\ a[0]="John"
 a[1]="Mary"
 a[2]="Bob"
 b[0]="Doe"
 b[1]="Jane"
 b[2]="Coder"
 c[0]="101"
 c[1]="202"
 c[2]="313"
.cble
.PP

The query matches the data in three places, so each variable becomes
a list of three elements, reported as an array.

Variables with list bindings may be referenced in a query. They denote a
multiple match. The
.code -D
command line option can establish a one-dimensional
list binding.

The clauses of
.code collect
may be nested.   Variable matches collated into lists in an
inner collect, are again collated into nested lists in the outer collect.
Thus an unbound variable wrapped in N nestings of
.code @(collect)
will
be an N-dimensional list. A one dimensional list is a list of strings;
a two dimensional list is a list of lists of strings, etc.

It is important to note that the variables which are bound within the main
clause of a collect. That is, the variables which are subject to
collection appear, within the collect, as normal one-value bindings. The
collation into lists happens outside of the collect. So for instance in the
query:

.cblk
 @(collect)
 @x=@x
 @(end)
.cble

The left
.code @x
establishes a binding for some material preceding an equal sign.
The right
.code @x
refers to that binding. The value of
.code @x
is different in each
iteration, and these values are collected. What finally comes out of the
collect clause is a single variable called
.code x
which holds a list containing each value that
was ever instantiated under that name within the collect clause.

Also note that the until clause has visibility over the bindings
established in the main clause. This is true even in the terminating
case when the until clause matches, and the bindings of the main clause
are discarded.

.coNP Keyword parameters in @ collect
By default,
.code collect
searches the rest of the input indefinitely,
or until the
.cod3 until / last
clause matches. It skips arbitrary amounts of
nonmatching material before the first match, and between matches.

Within the
.code @(collect)
syntax, it is possible to specify some useful keyword
parameters for additional control of the behavior. For instance

.cblk
  @(collect :maxgap 5)
.cble

means that the collect will terminate if it does not find a match within five
lines of the starting position, or if more than five lines are skipped since
any successful match. A
.code :maxgap
of
.code 0
means that the collected regions must be
adjacent. For instance:

.cblk
  @(collect :maxgap 0)
  M @a
  @(end)
.cble

means: from here, collect consecutive lines of the form
.strn "M ..." .
This will not
search for the first such line, nor will it skip lines which do not match this
form.

Other keywords are
.codn :mingap ,
and
.codn :gap .
The
.code :mingap
keyword specifies a minimum
gap between matches, but has no effect on the distance to the first match. The
.code :gap
keyword effectively specifies
.code :mingap
and
.code :maxgap
at the same time, and can only be
used if these other two are not used. Thus:

.cblk
  @(collect :gap 1)
  @a
  @(end)
.cble

means collect every other line starting with the current line. Several
other supported keywords are
.codn :times ,
.codn :mintimes ,
.code :maxtimes
and
.codn :lines .
The shorthand
.code ":times N"
means the same thing as
.codn ":mintimes N :maxtimes N" .
These specify how many matches should be collected. If there are fewer
than
.code :mintimes
matches, the collect fails. If
.code :maxtimes
matches are collected,
collect stops collecting immediately. Example:

.cblk
  @(collect :times 3)
  @a @b
  @(end)
.cble

This will collect a match for
.str @a @b
exactly three times. If three
matches are not found, it will fail.

The
.code :lines
parameter specifies the upper bound on how many lines
should be scanned by collect, measuring from the starting position.
The extent of the collect body is not counted. Example:

.cblk
  @(collect :lines 2)
  foo: @a
  bar: @b
  baz: @c
  @(end)
.cble

The above
.code collect
will look for a match only twice: at the current position,
and one line down.

There is one more keyword,
.codn :vars ,
described in the following section.

.coNP Specifying variables in @ collect
Normally, any variable for which a new binding occurs in a
.code collect
block is collected. A collect clause may be "sloppy": it can neglect to collect
some variables on some iterations, or bind some variables which are intended to
behave like local temporaries, but end up collated into lists. Another issue is
that the collect clause might not match anything at all, and then none of the
variables are bound.

The
.code :vars
keyword allows the query writer to add discipline the
.code collect
body.

The argument to
.code :vars
is a list of variable specs. A variable spec is either a
symbol, or a
.cblk
.meti >> ( symbol << expression )
.cble
pair, where the expression specifies a
default value.

When a
.code :vars
list is specified, it means that only the given variables can
emerge from the successful collect. Any newly introduced bindings for other
variables do not propagate.

Furthermore, for any variable which is not specified with a default value, the
collect body, whenever it matches successfully, must bind that variable. If it
neglects to bind the variable, an exception of type query-error is thrown.
(If a
.code collect
body matches successfully, but produces no new bindings, then
this error is suppressed.)

For any variable which does have a default value, if the
.code collect
body neglects
to bind that variable, the behavior is as if
.code collect
did bind that variable
to that default value.

The default values are expressions, and so can be quasiliterals.

Lastly, if in the event that
.code collect
does not match anything, the variables
specified in vars (whether or not they have a default value) are all bound to
empty lists. (These bindings are established after the processing of the
.cod3 until / last
last clause, if present.)

Example:

.cblk
  @(collect :vars (a b (c "foo")))
  @a @c
  @(end)
.cble

Here, if the body
.str @a @c
matches, an error will be thrown because one of the
mandatory variables is
.codn b ,
and the body neglects to produce a binding for
.codn b .

Example:

.cblk
  @(collect :vars (a (c "foo")))
  @a @b
  @(end)
.cble

Here, if
.str @a @b
matches, only
.code a
will be collected, but not
.codn b ,
because
.code b
is not
in the variable list. Furthermore, because there is no binding for
.code c
in the
body, a binding is created with the value
.strn foo ,
exactly as if
.code c
matched
such a piece of text.

In the following example, the assumption is that
.code "THIS NEVER MATCHES"
is not found anywhere in the input but the line
.code "THIS DOES MATCH"
is found and has a successor which is bound to
.codn a .
Because the body did not
match, the
.code :vars
.code a
and
.code b
should be bound to empty lists. But
.code a
is bound by the last clause to some text, so this takes precedence. Only
.code b
is bound to an empty list.

.cblk
  @(collect :vars (a b))
  THIS NEVER MATCHES
  @(last)
  THIS DOES MATCH
  @a
  @(end)
.cble

The following means: do not allow any variables to propagate out of any
iteration of the collect and therefore collect nothing:

.cblk
  @(collect :vars nil)
  ...
  @(end)
.cble

Instead of writing
.codn "@(collect :vars nil)" ,
it is possible to write
.codn @(repeat) .
.code @(repeat)
takes all collect keywords, except for
.codn :vars .
There is a
.code @(repeat)
directive used in
.code @(output)
clauses; that is a different directive.

.coNP Mandatory @ until and @ last

The
.cod3 until / last
clause supports the option keyword
.codn :mandatory ,
exemplified by the following:

.cblk
  @(collect)
  ...
  @(last :mandatory)
  ...
  @(end)
.cble

This means that the collect
.B must
be terminated by a match for the
.cod3 until / last
clause, or else by an explicit
.codn @(accept) .

Specifically, the collect cannot terminate due to simply running out of data,
or exceeding a limit on the number of matches that may be collected. In
those situations, if an
.code until
or
.code last
clause is present with
.codn :mandatory ,
the collect is deemed to have failed.

.dir coll

The
.code coll
directive is the horizontal version of
.codn collect .
Whereas
.code collect
works with multi-line clauses on line-oriented
material,
.code coll
works within a single line. With
.codn coll ,
it is possible to
recognize repeating regularities within a line and collect lists.

Regular-expression based Positive Match variables work well with coll.

Example: collect a comma-separated list, terminated by a space.
.IP code:
.cblk
\ @(coll)@{A /[^, ]+/}@(until) @(end)@B
.cble
.IP data:
.cblk
\ foo,bar,xyzzy blorch
.cble
.IP result:
.cblk
\ A[0]="foo"
 A[1]="bar"
 A[2]="xyzzy"
 B=blorch
.cble
.PP

Here, the variable
.code A
is bound to tokens which match the regular
expression
.codn "/[^, ]+/" :
non-empty sequence of characters other than commas or
spaces.

Like
.codn collect ,
.code coll
searches for matches.  If no match
occurs at the current character position, it tries at the next character
position. Whenever a match occurs, it continues at the character position which
follows the last character of the match, if such a position exists.

If not bounded by an until clause, it will exhaust the entire line.  If the
until clause matches, then the collection stops at that position,
and any bindings from that iteration are discarded.
Like collect, coll also supports an
.cod3 until / last
clause, which propagates variable
bindings and advances the position. The
.code :mandatory
keyword is supported.

.code coll
clauses nest, and variables bound within a coll are available to clauses
within the rest of the
.code coll
clause, including the
.cod3 until / last
clause, and appear as
single values. The final list aggregation is only visible after the
.code coll
clause.

The behavior of
.code coll
leads to difficulties when a delimited variable are used
to match material which is delimiter separated rather than terminated.
For instance, entries in a comma-separated files usually do
not appear as
.str a,b,c,
but rather
.strn a,b,c .

So for instance, the following result is not satisfactory:
.IP code:
.cblk
\ @(coll)@a @(end)
.cble
.IP data:
.cblk
\ 1 2 3 4 5
.cble
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 a[3]="4"
.cble
.PP

The
.code 5
is missing because it isn't followed by a space, which the text-delimited
variable match
.str "@a "
looks for.  After matching "4 ", coll continues to look for
matches, and doesn't find any.  It is tempting to try to fix it like this:
.IP code:
.cblk
\ @(coll)@a@/ ?/@(end)
.cble
.IP data:
.cblk
\ 1 2 3 4 5
.cble
.IP result:
.cblk
\ a[0]=""
 a[1]=""
 a[2]=""
 a[3]=""
 a[4]=""
 a[5]=""
 a[6]=""
 a[7]=""
 a[8]=""
.cble
.PP

The problem now is that the regular expression
.code "/ ?/"
(match either a space or nothing), matches at any position.
So when it is used as a variable
delimiter, it matches at the current position, which binds the empty string to
the variable, the extent of the match being zero. In this situation, the
.code coll
directive proceeds character by character. The solution is to use
positive matching: specify the regular expression which matches the item,
rather than a trying to match whatever follows.  The collect directive will
recognize all items which match the regular expression:
.IP code:
.cblk
\ @(coll)@{a /[^ ]+/}@(end)
.cble
.IP data:
.cblk
\ 1 2 3 4 5
.cble
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 a[3]="4"
 a[4]="5"
.cble
.PP

The
.code until
clause can specify a pattern which, when recognized, terminates
the collection. So for instance, suppose that the list of items may
or may not be terminated by a semicolon. We must exclude
the semicolon from being a valid character inside an item, and
add an until clause which recognizes a semicolon:
.IP code:
.cblk
\ @(coll)@{a /[^ ;]+/}@(until);@(end);
.cble
.IP data:
.cblk
\ 1 2 3 4 5;
.cble
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 a[3]="4"
 a[4]="5"
.cble
.PP

Whether followed by the semicolon or not, the items are collected properly.

Note that the
.code @(end)
is followed by a semicolon. That's because
when the
.code @(until)
clause meets a match, the matching material
is not consumed.

This repetition can, of course, be avoided by using
.code @(last)
instead of
.code @(until)
since
.code @(last)
consumes the terminating material.

Instead of the above regular-expression-based approach, this extraction problem
can also be solved with
.codn cases :
.IP code:
.cblk
\ @(coll)@(cases)@a @(or)@a@(end)@(end)
.cble
.IP data:
.cblk
\ 1 2 3 4 5
.cble
.IP result:
.cblk
\ a[0]="1"
 a[1]="2"
 a[2]="3"
 a[3]="4"
 a[4]="5"
.cble
.PP

.coNP Keyword parameters in @ coll
The
.code @(coll)
directive takes most of the same parameters as
.codn @(collect) .
See the section Keyword parameters in
.code collect
above.
So for instance
.code "@(coll :gap 0)"
means that the collects must be
consecutive, and
.code "@(coll :maxtimes 2)"
means that at most two matches
will be collected.  The
.code :lines
keyword does not exist, but there is
an analogous
.code :chars
keyword.

The
.code @(coll)
directive takes the
.code :vars
keyword.

The shorthand
.code @(rep)
may be used instead of
.codn "@(coll :vars nil)" .
.code @(rep)
takes all keywords, except
.codn :vars .

.dir flatten

The
.code flatten
directive can be used to convert variables to one dimensional
lists. Variables which have a scalar value are converted to lists containing
that value. Variables which are multidimensional lists are flattened to
one-dimensional lists.

Example (without
.codn @(flatten) )
.IP code:
.cblk
\ @b
 @(collect)
 @(collect)
 @a
 @(end)
 @(end)
.cble
.IP data:
.cblk
\ 0
 1
 2
 3
 4
 5
.cble
.IP result:
.cblk
\ b="0"
 a_0[0]="1"
 a_1[0]="2"
 a_2[0]="3"
 a_3[0]="4"
 a_4[0]="5"
.cble
.PP

Example (with
.codn @(flatten) ):
.IP code:
.cblk
\ @b
 @(collect)
 @(collect)
 @a
 @(end)
 @(end)
 @(flatten a b)
.cble
.IP data:
.cblk
\ 0
 1
 2
 3
 4
 5
.cble
.IP result:
.cblk
\ b="0"
 a[0]="1"
 a[1]="2"
 a[2]="3"
 a[3]="4"
 a[4]="5"
.cble
.PP


.dir merge

The
.code merge
directive provides a way of combining two or more variables
in a somewhat complicated but very useful way.

To understand what merge does we first have to define a property called depth.
The depth of an atom such as a string is defined as
.codn 1 .
The depth of an empty
list is
.codn 0 .
The depth of a nonempty list is one plus the depth of its deepest
element. So for instance
.str foo
has depth 1,
.cblk
("foo")
.cble
has depth 2, and
.cblk
("foo" ("bar"))
.cble
has depth three.

We can now define the binary (two argument) merge operation as follows.
.IP 1
.code "(merge A B)"
first normalizes the values
.code A
and
.code B
such that they have equal depth.
.IP 2
A value which has depth zero is put into a one element list. 
.IP 3
If either value has a smaller depth than the other, it is wrapped
in a list as many times as needed to give it equal depth.
Finally, the values are appended together.
.PP

Merge takes more than two arguments. These are merged by a left reduction. The
leftmost two values are merged, and then this result is merged with the third
value, and so on.

Merge is useful for combining the results from collects at different
levels of nesting such that elements are at the appropriate depth.

.dir cat

The
.code cat
directive converts a list variable into a single
piece of text. The syntax is:

.cblk
.mets @(cat < var <> [ sep ])
.cble

The
.meta sep
argument specifies a separating piece of text. If no separator
is specified, then a single space is used.

Example:
.IP code:
.cblk
\ @(coll)@{a /[^ ]+/}@(end)
 @(cat a ":")
.cble
.IP data:
.cblk
\ 1 2 3 4 5
.cble
.IP result:
.cblk
\ a="1:2:3:4:5"
.cble
.PP

.dir bind

The syntax of the
.code bind
directive is:

.cblk
.mets @(bind < pattern < expression >> { keyword << value }*)
.cble

The
.code bind
directive is a kind of pattern match, which matches one or more
variables on the left hand side pattern to the value of a variable on the
right hand side.  The right hand side variable must have a binding, or else the
directive fails. Any variables on the left hand side which are unbound receive
a matching piece of the right hand side value. Any variables on the left which
are already bound must match their corresponding value, or the bind fails. Any
variables which are already bound and which do match their corresponding value
remain unchanged (the match can be inexact).

The simplest bind is of one variable against itself, for instance bind
.code A
against
.codn A :

.cblk
  @(bind A A)
.cble

This will fail if
.code A
is not bound, (and complain loudly). If
.code A
is bound, it
succeeds, since
.code A
matches
.codn A .

The next simplest bind binds one variable to another:

.cblk
  @(bind A B)
.cble

Here, if
.code A
is unbound, it takes on the same value as
.codn B .
If
.code A
is bound, it has
to match
.codn B ,
or the bind fails. Matching means that either
.IP -
.code A
and
. code B
are the same text
.IP -
.code A
is text,
.code B
is a list, and
.code A
occurs within
.codn B .
.IP -
vice versa:
.code B
is text,
.code A
is a list, and
.code B
occurs within
.codn A .
.IP -
.code A
and
.code B
are lists and are either identical, or one is
found as substructure within the other.
.PP
The right hand side does not have to be a variable. It may be some other
object, like a string, quasiliteral, regexp, or list of strings, et cetera. For
instance

.cblk
  @(bind A "ab\etc")
.cble

will bind the string
.str ab\etc
to the variable
.code A
if
.code A
is unbound. If
.code A
is bound, this will fail unless
.code A
already contains an identical string. However, the right hand side of a bind
cannot be an unbound variable, nor a complex expression that contains unbound
variables.

The left hand side of
.code bind
can be a nested list pattern containing variables.
The last item of a list at any nesting level can be preceded by a
.code .
(dot), which means that the variable matches the rest of the list from that
position.

Example: suppose that the list A contains
.cblk
("now" "now" "brown" "cow").
.cble
Then the
directive
.codn "@(bind (H N . C) A)" ,
assuming that
.codn H ,
.code N
and
.code C
are unbound variables,
will bind
.code H
to
.strn how ,
code N
to
.strn now ,
and
.code C
to the remainder of the list
.cblk
("brown" "cow").
.cble

Example: suppose that the list
.code A
is nested to two dimensions and  contains
.cblk
(("how" "now") ("brown" "cow")).
.cble
Then
.code "@(bind ((H N) (B C)) A)"
binds
.code H
to
.strn how ,
.code N
to
.strn now ,
.code B
to
.str brown
and
.code C
to
.strn cow .

The dot notation may be used at any nesting level. it must be followed
by an item.  The forms
.code (.)
and
.code "(X .)"
are invalid, but
.code "(. X)"
is valid and equivalent to
.codn X .

The number of items in a left pattern match must match the number of items in
the corresponding right side object. So the pattern
.code ()
only matches
an empty list. The notations
.code ()
and
.code nil
mean exactly the same thing.

The symbols
.codn nil ,
.code t
and keyword symbols may be used on either side.
They represent themselves.  For example
.code "@(bind :foo :bar)"
fails,
but
.code "@(bind :foo :foo)"
succeeds since the two sides denote the same
keyword symbol object.

.coNP Keywords in the @ bind directive
The
.code bind
directive accepts these keywords:

.coIP :lfilt
The argument to
.code :lfilt
is a filter specification. When the left side pattern
contains a binding which is therefore matched against its counterpart from the
right side expression, the left side is filtered through the filter specified
by
.code :lfilt
for the purposes of the comparison. For example:

.cblk
  @(bind "a" "A" :lfilt :upcase)
.cble

produces a match, since the left side is the same as the right after
filtering through the :upcase filter.

.coIP :rfilt
The argument to
.code :rfilt
is a filter specification. The specified filter is
applied to the right hand side material prior to matching it against
the left side. The filter is not applied if the left side is a variable
with no binding. It is only applied to determine a match. Binding takes
place the unmodified right hand side object.

For example, the following produces a match:

.cblk
  @(bind "A" "a" :rfilt :upcase)
.cble

.coIP :filter
This keyword is a shorthand to specify both filters to the same value.
For instance
.code ":filter :upcase"
is equivalent to
.codn ":lfilt :upcase :rfilt :upcase" .

For a description of filters, see Output Filtering below.

Of course, compound filters like
.code "(:fromhtml :upcase)"
are supported with all these keywords. The filters apply across arbitrary
patterns and nested data.

Example:

.cblk
  @(bind (a b c) ("A" "B" "C"))
  @(bind (a b c) (("z" "a") "b" "c") :rfilt :upcase)
.cble

Here, the first bind establishes the values for
.codn a ,
.code b
and
.codn c ,
and the second bind
succeeds, because the value of a matches the second element of the list
.cblk
("z" "a")
.cble
if it is upcased, and likewise
.code b
matches
.str "b"
and
.code c
matches
.str c
if these are upcased.

.coNP Lisp forms in the @ bind directive

\*(TL forms, introduced by
.code @
may be used on either side of
.codn bind .


Example:

.cblk
  @(bind a @(+ 2 2))
  @(bind @(+ 2 2) @(* 2 2))
.cble

Here,
.code a
is bound to the integer
.codn 4 .
The second
.code bind
then succeeds because the forms
.code "(+ 2 2)"
and
.code "(* 2 2)"
produce equal values.

.dir set

The
.code set
directive syntactically resembles
.codn bind ,
but is not a pattern match. It overwrites
the previous values of variables with new values from the right hand side.
Each variable that is assigned must have an existing binding:
.code set
will not induce binding.

Examples follow.

Store the value of
.code A
back into
.codn A ,
an operation with no effect:

.cblk
  @(set A A)
.cble

Exchange the values of
.code A
and
.codn B :

.cblk
  @(set (A B) (B A))
.cble

Store a string into
.codn A :

.cblk
  @(set A "text")
.cble

Store a list into
.codn A :

.cblk
  @(set A ("line1" "line2"))
.cble

Destructuring assignment.
.code A
ends up with
.strn A ,
.code B
ends up with
.cblk
("B1" "B2")
.cble
and
.code C
binds to
.cblk
("C1" "C2").
.cble

.cblk
  @(bind D ("A" ("B1" "B2") "C1" "C2"))
  @(bind (A B C) (() () ()))
  @(set (A B . C) D)
.cble

Note that
.code set
does not support a \*(TL expression on the left side, so the following
are invalid syntax:

.cblk
  @(set @(+ 1 1) @(* 2 2))
  @(set @b @(list "a"))
.cble

The second one is erroneous even though there is a variable on the left.
Because it is preceded by the
.code @
escape, it is a Lisp variable, and not a pattern variable.

.dir rebind

The
.code rebind
directive resembles
.code set
but it is not an assignment.
It combines the semantics of
.codn local ,
.code bind
and
.codn set .
The expression on the right hand side is evaluated in the current
environment. Then the variables in the pattern on the left are introduced
as new bindings, whose values come from the pattern.

.code rebind
makes it easy to create temporary bindings based on existing bindings.

.cblk
  @(define pattern-function (arg))
  @;; inside a pattern function:
  @(rebind recursion-level @(+ recursion-level 1))
  @;; ...
  @(end)
.cble

When the function terminates, the previous value of recursion-level
is restored. The effect is like the following, but much easier
to write and faster to execute:

.cblk
  @(define pattern-function (arg))
  @;; inside a pattern function:
  @(local temp)
  @(set temp recursion-level)
  @(local recursion-level)
  @(set recursion-level @(+ temp 1))
  @;; ...
  @(end)
.cble

.dir forget

The
.code forget
has two spellings:
.code @(forget)
and
.codn @(local) .

The arguments are one or more symbols, for example:

.cblk
  @(forget a)
  @(local a b c)
.cble

this can be written

.cblk
  @(local a)
  @(local a b c)
.cble

Directives which follow the forget or local directive no longer see
any bindings for the symbols mentioned in that directive, and
can establish new bindings.

It is not an error if the bindings do not exist.

It is strongly recommended to use the
.code @(local)
spelling in functions,
because the forgetting action simulates local variables:
for the given symbols, the machine forgets any earlier variables
from outside of the function, and consequently, any new bindings
for those variables belong to the function. (Furthermore,
functions suppress the propagation of variables that are not
in their parameter list, so these locals will be automatically
forgotten when the function terminates.)

.dir do

The syntax of
.code @(do)
is:

.cblk
.mets @(do << lisp-expression )
.cble

The do directive evaluates a \*(TL expression. (See TXR LISP far
below.) The value of the expression is ignored, and matching continues
continues with the directives which follow the
.code do
directive, if any.

In the context of the
.code do
directive, the expression should not be introduced by the
.code @
symbol; it is expected to be a Lisp expression.

Example:

.cblk
  @; match text into variables a and b, then insert into hash table h
  @(bind h (hash :equal-based))
  @a:@b
  @(do (set [h a] b))
.cble

.SS* Blocks

.NP* Overview
Blocks are sections of a query which are either denoted by a name,
or are anonymous. They may nest: blocks can occur within blocks
and other constructs.

Blocks are useful for terminating parts of a pattern matching search
prematurely, and escaping to a higher level. This makes blocks not only
useful for simplifying the semantics of certain pattern matches,
but also an optimization tool.

Judicious use of blocks and escapes can reduce or eliminate the amount of
backtracking that \*(TX performs.

.dir block

The
.cblk
.meti @(block << name )
.cble
directive introduces a named block, except when
.meta name
is the symbol
.codn nil .
The
.code @(block)
directive introduces an unnamed block, equivalent
to
.codn "@(block nil)" .

The
.code @(skip)
and
.code @(collect)
directives introduce implicit anonymous blocks,
as do function bodies.

.NP* Block Scope

The names of blocks are in a distinct namespace from the variable binding
space. So
.code "@(block foo)"
is unrelated to the variable
.codn @foo .

A block extends from the
.code "@(block ...)"
directive which introduces it,
until the matching
.codn @(end) ,
and may be empty.  For instance:

.cblk
  @(some)
  abc
  @(block foo)
  xyz
  @(end)
  @(end)
.cble

Here, the block foo occurs in a
.code @(some)
clause, and so it extends to the
.code @(end)
which terminates the block.  After that
.codn @(end) ,
the name foo is not
associated with a block (is not "in scope"). The second
.code @(end)
terminates
the
.code @(some)
block.

The implicit anonymous block introduced by
.code @(skip)
has the same scope
as the
.codn @(skip) :
it extends over all of the material which follows the skip,
to the end of the containing subquery.

.NP* Block Nesting

Blocks may nest, and nested blocks may have the same names as blocks in
which they are nested. For instance:

.cblk
  @(block)
  @(block)
  ...
  @(end)
  @(end)
.cble

is a nesting of two anonymous blocks, and

.cblk
  @(block foo)
  @(block foo)
  @(end)
  @(end)
.cble

is a nesting of two named blocks which happen to have the same name.
When a nested block has the same name as an outer block, it creates
a block scope in which the outer block is "shadowed"; that is to say,
directives which refer to that block name within the nested block refer to the
inner block, and not to the outer one.

.NP* Block Semantics

A block normally does nothing. The query material in the block is evaluated
normally. However, a block serves as a termination point for
.code @(fail)
and
.code @(accept)
directives which are in scope of that block and refer to it.

The precise meaning of these directives is:

.meIP @(fail << name )
Immediately terminate the enclosing query block called
.metn name ,
as if that block
failed to match anything. If more than one block by that name encloses
the directive, the inner-most block is terminated. No bindings emerge from
a failed block.

.coIP @(fail)
Immediately terminate the innermost enclosing anonymous block, as if
that block failed to match.

If the implicit block introduced by
.code @(skip)
is terminated in this manner,
this has the effect of causing
.code skip
itself to fail. I.e. the behavior
is as if skip search did not find a match for the trailing material,
except that it takes place prematurely (before the end of the available
data source is reached).

If the implicit block associated with a
.code @(collect)
is terminated this way,
then the entire
.code collect
fails. This is a special behavior, because a
collect normally does not fail, even if it matches nothing and collects nothing!

To prematurely terminate a collect by means of its anonymous block, without
failing it, use
.codn @(accept) .

.meIP @(accept << name )
Immediately terminate the enclosing query block called
.metn name ,
as if that block
successfully matched. If more than one block by that name encloses the
directive, the inner-most block is terminated.  Any bindings established within
that block until this point emerge from that block.

.coIP @(accept)
Immediately terminate the innermost enclosing anonymous block, as if
that block successfully matched. Any bindings established within
that block until this point emerge from that block.

If the implicit block introduced by
.code @(skip)
is terminated in this manner,
this has the effect of causing the skip itself to succeed, as if
all of the trailing material had successfully matched.

If the implicit block associated with a
.code @(collect)
is terminated this way,
then the collection stops. All bindings collected in the current iteration of
the collect are discarded. Bindings collected in previous iterations are
retained, and collated into lists in accordance with the semantics of collect.

Example: alternative way to achieve
.code @(until)
termination:

.cblk
  @(collect)
  @  (maybe)
  ---
  @  (accept)
  @  (end)
  @LINE
  @(end)
.cble

This query will collect entire lines into a list called
.codn LINE .
However,
if the line
.code ---
is matched (by the embedded
.codn @(maybe) ),
the collection
is terminated. Only the lines up to, and not including the
.code ---
line, are collected. The effect is identical to:

.cblk
  @(collect)
  @LINE
  @(until)
  ---
  @(end)
.cble

The difference (not relevant in these examples) is that the until clause has
visibility into the bindings set up by the main clause.

However, the following example has a different meaning:

.cblk
  @(collect)
  @LINE
  @  (maybe)
  ---
  @  (accept)
  @  (end)
  @(end)
.cble

Now, lines are collected until the end of the data source, or until a line is
found which is followed by a
.code ---
line. If such a line is found,
the collection stops, and that line is not included in the collection!
The
.code @(accept)
terminates the process of the collect body, and so the
action of collecting the last
.code @LINE
binding into the list is not performed.
.PP

.NP* Data Extent of Terminated Blocks

A query block may have matched some material prior to being terminated by
.codn accept .
In that case, it is deemed to have only matched that material,
and not any material which follows. This may matter, depending on the context
in which the block occurs.

Example:
.IP code:
.cblk
\ @(some)
 @(block foo)
 @first
 @(accept foo)
 @ignored
 @(end)
 @second
.cble
.IP data:
.cblk
\ 1
 2
 3
.cble
.IP result:
.cblk
\ first="1"
 second="2"
.cble
.PP

At the point where the
.code accept
occurs, the foo block has matched the first line,
bound the text
.str 1
to the variable
.codn @first .
The block is then terminated.
Not only does the
.code @first
binding emerge from this terminated block, but
what also emerges is that the block advanced the data past the first line to
the second line. Next, the
.code @(some)
directive ends, and propagates the
bindings and position. Thus the
.code @second
which follows then matches the second
line and takes the text
.strn 2 .

In the following query, the foo block occurs inside a maybe clause.
Inside the foo block there is a
.code @(some)
clause. Its first subclause
matches variable
.code @first
and then terminates block foo. Since block foo is
outside of the
.code @(some)
directive, this has the effect of terminating the
.code @(some)
clause:
.IP code:
.cblk
\ @(maybe)
 @(block foo)
 @  (some)
 @first
 @  (accept foo)
 @  (or)
 @one
 @two
 @three
 @four
 @  (end)
 @(end)
 @second
.cble
.IP data:
.cblk
\ 1
 2
 3
 4
 5
.cble
.IP result:
.cblk
\ first="1"
 second="2"
.cble
.PP

The second clause of the
.code @(some)
directive, namely:

.cblk
  @one
  @two
  @three
  @four
.cble

is never processed. The reason is that subclauses are processed in top
to bottom order, but the processing was aborted within the
first clause the
.codn "@(accept foo)" .
The
.code @(some)
construct never gets the
opportunity to match four lines.

If the
.code "@(accept foo)"
line is removed from the above query, the output
is different:
.IP code:
.cblk
\ @(maybe)
 @(block foo)
 @  (some)
 @first
 @#          <--  @(accept foo) removed from here!!!
 @  (or)
 @one
 @two
 @three
 @four
 @  (end)
 @(end)
 @second
.cble
.IP data:
.cblk
\ 1
 2
 3
 4
 5
.cble
.IP result:
.cblk
\ first="1"
 one="1"
 two="2"
 three="3"
 four="4"
 second="5"
.cble
.PP

Now, all clauses of the
.code @(some)
directive have the opportunity to match.
The second clause grabs four lines, which is the longest match.
And so, the next line of input available for matching is
.codn 5 ,
which goes
to the
.code @second
variable.

.coNP Interaction Between the @ trailer and @ accept Directives

If one of the clauses which follow a
.code @(trailer)
requests a successful
termination to an outer block via
.codn @(accept) ,
then
.code @(trailer)
intercepts the escape and adjusts the data extent to the position
that it was given.

Example:
.IP code:
.cblk
\ @(block)
 @(trailer)
 @line1
 @line2
 @(accept)
 @(end)
 @line3
.cble
.IP data:
.cblk
\ 1
 2
 3
.cble
.IP result:
.cblk
\ line1="1"
 line2="2"
 line3="1"
.cble
.PP

The variable
.code line3
is bound to
.str 1
because although
.code @(accept)
yields a data
position which has advanced to the third line, this is intercepted by
.code @(trailer)
and adjusted back to the first line. Neglecting to do this adjustment
would violate the semantics of
.codn trailer .

Directives other than
.code @(trailer)
have no such special interaction with accept.

.SS* Functions

.NP* Overview
\*(TX functions allow a query to be structured to avoid repetition.
On a theoretical note, because
\*(TX functions support recursion, functions enable \*(TX to match some
kinds of patterns which exhibit self-embedding, or nesting,
and thus cannot be matched by a regular language.

Functions in \*(TX are not exactly like functions in mathematics or functional
languages, and are not like procedures in imperative programming languages.
They are not exactly like macros either. What it means for a
\*(TX function to take arguments and produce a result is different from
the conventional notion of a function.

A \*(TX function may have one or more parameters. When such a function is
invoked, an argument must be specified for each parameter.  However, a special
behavior is at play here. Namely, some or all of the argument expressions may
be unbound variables.  In that case, the corresponding parameters behave like
unbound variables also.  Thus \*(TX function calls can transmit the "unbound"
state from argument to parameter.

It should be mentioned that functions have access to all bindings that are
visible in the caller; functions may refer to variables which are not
mentioned in their parameter list.

With regard to returning, \*(TX functions are also unconventional. If the
function fails, then the function call is considered to have failed. The
function call behaves like a kind of match; if the function fails, then the
call is like a failed match.

When a function call succeeds, then the bindings emanating from that function
are processed specially. Firstly, any bindings for variables which do not
correspond to one of the function's parameters are thrown away. Functions may
internally bind arbitrary variables in order to get their job done, but only
those variables which are named in the function argument list may propagate out
of the function call.  Thus, a function with no arguments can only indicate
matching success or failure, but not produce any bindings. Secondly,
variables do not propagate out of the function directly, but undergo
a renaming. For each parameter which went into the function as an unbound
variable (because its corresponding argument was an unbound variable),
if that parameter now has a value, that value is bound onto the corresponding
argument.

Example:

.cblk
  @(define collect-words (list))
  @(coll)@{list /[^ \et]+/}@(end)
  @(end)
.cble

The above function
.code collect-words
contains a query which collects words from a
line (sequences of characters other than space or tab), into the list variable
called
.codn list .
This variable is named in the parameter list of the function,
therefore, its value, if it has one, is permitted to escape from the function
call.

Suppose the input data is:

.cblk
  Fine summer day
.cble

and the function is called like this:

.cblk
  @(collect-words wordlist)
.cble

The result (with
.codn "txr -B" )
is:

.cblk
  wordlist[0]=Fine
  wordlist[1]=summer
  wordlist[1]=day
.cble

How it works is that in the function call
.codn "@(collect-words wordlist)" ,
.code wordlist
is an unbound variable. The parameter corresponding to that
unbound variable is the parameter
.codn list .
Therefore, that parameter
is unbound over the body of the function.  The function body collects the
words of
.str Fine summer day
into the variable
.codn list ,
and then
yields the that binding.   Then the function call completes by
noticing that the function parameter
.code list
now has a binding, and
that the corresponding argument
.code wordlist
has no binding. The binding
is thus transferred to the
.code wordlist
variable.  After that, the
bindings produced by the function are thrown away. The only enduring
effects are:
.IP -
the function matched and consumed some input; and
.IP -
the function succeeded; and
.IP -
the
.code wordlist
variable now has a binding.
.PP
Another way to understand the parameter behavior is that function
parameters behave like proxies which represent their arguments.  If an argument
is an established value, such as a character string or bound variable, the
parameter is a proxy for that value and behaves just like that value. If an
argument is an unbound variable, the function parameter acts as a proxy
representing that unbound variable. The effect of binding the proxy is
that the variable becomes bound, an effect which is settled when the
function goes out of scope.

Within the function, both the original variable and the proxy are
visible simultaneously, and are independent.  What if a function binds both of
them? Suppose a function has a parameter called
.codn P ,
which is called with an argument
.codn A ,
which is an unbound variable, and then, in the function, both
.code A
and
.code P
bound.  This is
permitted, and they can even be bound to different values.  However, when the
function terminates, the local binding of A simply disappears (because
the symbol
.code A
is not among the parameters of the function).
Only the value bound to
.code P
emerges, and is bound to
.codn A ,
which still appears unbound at that point. The
.code P
binding disappears also, and the net effect is that
.code A
is now bound. The "proxy" binding of
.code A
through the parameter
.code P
"wins" the conflict with the direct binding.

.NP* Definition Syntax

Function definition syntax comes in two flavors: vertical and horizontal.
Horizontal definitions actually come in two forms, the distinction
between which is hardly noticeable, and the need for which is
made clear below.

A function definition begins with a
.code "@(define ...)"
directive. For vertical
functions, this is the only element in a line.

The
.code define
symbol must be followed by a symbol, which is the name of the
function being defined. After the symbol, there is a parenthesized optional
argument list. If there is no such list, or if the list is specified as
.code ()
or
the symbol
.code nil
then the function has no parameters. Examples of valid
.code define
syntax are:

.cblk
  @(define foo)
  @(define bar ())
  @(define match (a b c))
.cble

If the define directive is followed by more material on the same line, then
it defines a horizontal function:

.cblk
  @(define match-x)x@(end)
.cble

If the define is the sole element in a line, then it
is a vertical function, and the function definition continues below:

.cblk
  @(define match-x)
  x
  @(end)
.cble

The difference between the two is that a horizontal function matches
characters within a line, whereas a vertical function matches lines
within a stream. The former
.code match-x
matches the character
.codn x ,
advancing
to the next character position.  The latter
.code match-x
matches a line consisting
of the character
.codn x ,
advancing to the next line.

Material between
.code @(define)
and
.code @(end)
is the function body.  The define
directive may be followed directly by the
.code @(end)
directive, in which case the
function has an empty body.

Functions may be nested within function bodies. Such local functions have
dynamic scope. They are visible in the function body in which they are defined,
and in any functions invoked from that body.

The body of a function is an anonymous block. (See BLOCKS above).

.NP* Two Forms of The Horizontal Function

If a horizontal function is defined as the only element of a line,
it may not be followed by additional material. The following
construct is erroneous:

.cblk
  @(define horiz (x))@foo:@bar@(end)lalala
.cble

This kind of definition is actually considered to be in the vertical context,
and like other directives that have special effects and that do not match
anything, it does not consume a line of input. If the above syntax were
allowed, it would mean that the line would not only define a function but also
match
.codn "lalala" .
This would, in turn, would mean that the
.code @(define)...@(end)
is
actually in horizontal mode, and so it matches a span of zero characters within
a line (which means that is would require a line of input to match: a
surprising behavior for a non-matching directive!)

A horizontal function can be defined in an actual horizontal context. This
occurs if its is in a line where it is preceded by other material.
For instance:

.cblk
  X@(define fun)...@(end)Y
.cble

This is a query line which must match the text
.codn XY .
It also defines the function
.codn fun .
The main use of this form is for nested horizontal functions:

.cblk
  @(define fun)@(define local_fun)...@(end)@(end)
.cble

.NP* Vertical-Horizontal Overloading

A function of the same name may be defined as both vertical and horizontal.
Both functions are available at the same time. Which one is used by
a call is resolved by context. See the section Vertical Versus Horizontal Calls
below.

.NP* Call Syntax

A function is invoked by compound directive whose first symbol is the name of
that function. Additional elements in the directive are the arguments.
Arguments may be symbols, or other objects like string and character
literals, quasiliterals ore regular expressions.

Example:
.IP code:
.cblk
\ @(define pair (a b))
 @a @b
 @(end)
 @(pair first second)
 @(pair "ice" cream)
.cble
.IP data:
.cblk
\ one two
 ice milk
.cble
.IP result:
.cblk
\ first="one"
 second="two"
 cream="milk"
.cble
.PP

The first call to the function takes the line
.strn "one two" .
The parameter
.code a
takes
.str one
and parameter
.code b
takes
.strn two .
These are rebound to the arguments
.code first
and
.codn second .
The second call to the function binds the a parameter to the word
.strn "ice" ,
and the
.code b
is unbound, because the
corresponding argument
.code cream
is unbound. Thus inside the function,
.code a
is forced to match
.codn "ice" .
Then a space is matched and
.code b
collects the text
.strn milk .
When the function returns, the unbound
.str cream
variable gets this value.

If a symbol occurs multiple times in the argument list, it constrains
both parameters to bind to the same value. That is to say, all parameters
which, in the body of the function, bind a value, and which are all derived
from the same argument symbol must bind to the same value. This is settled when
the function terminates, not while it is matching. Example:
.IP code:
.cblk
\ @(define pair (a b))
 @a @b
 @(end)
 @(pair same same)
.cble
.IP data:
.cblk
\ one two
.cble
.IP result:
.cblk
\ [query fails]
.cble
.PP

Here the query fails because
.code a
and
.code b
are effectively proxies for the same unbound variable
.code same
and are bound to different values, creating a conflict which
constitutes a match failure.

.NP* Vertical Versus Horizontal Calls

A function call which is the only element of the query line in
which it occurs is ambiguous. It can go either to a vertical
function or to the horizontal one. If both are defined, then
it goes to the vertical one.

Example:
.IP code:
.cblk
\ @(define which (x))@(bind x "horizontal")@(end)
 @(define which (x))
 @(bind x "vertical")
 @(end)
 @(which fun)
.cble
.IP result:
.cblk
\ fun="vertical"
.cble
.PP

Not only does this call go to the vertical function, but
it is in a vertical context.

If only a horizontal function is defined, then that is the one which is called,
even if the call is the only element in the line. This takes place in a
horizontal character-matching context, which requires a line of input which can
be traversed:

Example:
.IP code:
.cblk
\ @(define which (x))@(bind x "horizontal")@(end)
 @(which fun)
.cble
.IP data:
.cblk
\ ABC
.cble
.IP result:
.cblk
\ [query fails]
.cble
.PP

The query fails because since
.code "@(which fun)"
is in horizontal mode,
it matches characters in a line. Since the function body consists
only of
.code "@(bind ...)"
which doesn't match any characters, the function
call requires an empty line to match. The line
.code ABC
is not empty,
and so there is a matching failure. The following
example corrects this:

Example:
.IP code:
.cblk
\ @(define which (x))@(bind x "horizontal")@(end)
 @(which fun)
.cble
.IP data:
.cblk
\ [empty line]
.cble
.IP result:
.cblk
\ fun="horizontal"
.cble
.PP

A call made in a clearly horizontal context will prefer the
horizontal function, and only fall back on the vertical one
if the horizontal one doesn't exist. (In this fall-back case,
the vertical function is called with empty data; it is useful
for calling vertical functions which process arguments and
produce values.)

In the next example, the call is followed by trailing material,
placing it in a horizontal context. Leading material will
do the same thing:

Example:
.IP code:
.cblk
\ @(define which (x))@(bind x "horizontal")@(end)
 @(define which (x))
 @(bind x "vertical")
 @(end)
 @(which fun)B
.cble
.IP data:
.cblk
\ B
.cble
.IP result:
.cblk
\ fun="horizontal"
.cble
.PP

.NP* Local Variables

As described earlier, variables bound in a function body which are not
parameters of the function are discarded when the function returns. However,
that, by itself, doesn't make these variables local, because pattern functions
have visibility to all variables in their calling environment. If a variable
.code x
exists already when a function is called, then an attempt to bind it inside a
function may result in a failure.  The
.code local
directive must be used in a
pattern function to list which variables are local. 

Example:

.cblk
  @(define path (path))@\e
    @(local x y)@\e
    @(cases)@\e
      (@(path x))@(path y)@(bind path `(@x)@y`)@\e
    @(or)@\e
      @{x /[.,;'!?][^ \et\ef\ev]/}@(path y)@(bind path `@x@y`)@\e
    @(or)@\e
      @{x /[^ .,;'!?()\et\ef\ev]/}@(path y)@(bind path `@x@y`)@\e
    @(or)@\e
      @(bind path "")@\e
    @(end)@\e
  @(end)
.cble

This is a horizontal function which matches a path, which lands into four
recursive cases. A path can be parenthesized path followed by a path; it can be
a certain character followed by a path, or it can be empty

This function ensures that the variables it uses internally,
.code x
and
.codn y ,
do not have anything to do with any inherited bindings for
.code x
and
.codn y .

Note that the function is recursive, which cannot work without
.code x
and
.code y
being local, even if no such bindings exist prior to the top-level invocation of the
function. The invocation
.code "@(path x)"
causes
.code x
to be bound, which is
visible inside the invocation
.codn "@(path y)" ,
but that invocation needs to have its own binding of
.code x
for local use.

.NP* Nested Functions

Function definitions may appear in a function. Such definitions
are visible in all functions which are invoked from the body
(and not necessarily enclosed in the body). In other words, the
scope is dynamic, not lexical.  Inner definitions shadow outer
definitions. This means that a caller can redirect the function
calls that take place in a callee, by defining local functions
which capture the references.

Example:
.IP code:
.cblk
\ @(define which)
 @  (fun)
 @(end)
 @(define fun)
 @  (output)
 toplevel fun!
 @  (end)
 @(end)
 @(define callee)
 @  (define fun)
 @    (output)
 local fun!
 @    (end)
 @  (end)
 @  (which)
 @(end)
 @(callee)
 @(which)
.cble
.IP output:
.cblk
\ local fun!
 toplevel fun!
.cble
.PP

Here, the function
.code which
is defined which calls
.codn fun .
A toplevel definition of
.code fun
is introduced which
outputs
.strn "toplevel fun!" .
The function
.code callee
provides its own local
definition of
.code fun
which outputs
.str "local fun!"
before calling
.codn which .
When
.code callee
is invoked, it calls
.codn which ,
whose
.code @(fun)
call is routed to callee's
local definition.  When
.code which
is called directly from the top level, its
.code fun
call goes to the toplevel definition.

.NP* Indirect Calls

Function indirection may be performed using the
.code call
directive. If
.meta fun-expr
is an expression which evaluates to a symbol, and
that symbol names a function which takes no arguments, then
.cblk
  @(call fun-expr)
.cble
may be used to invoke the function. Of course, additional
expressions may be supplied which specify arguments.

Example 1:

.cblk
\ @(define foo (arg))
  @(bind arg "abc")
  @(end)
  @(call @'foo b)
.cble

In this example, the effect is that
.code foo
is invoked, and
.code b
ends up bound to
.strn abc .

The
.code call
directive here uses the
.code @'foo
expression to calculate the name of the function to be invoked.
The
.code @
symbol indicates that the expression which follows is \*(TL ,
and
.code 'foo
is the \*(TL syntax for quoting a symbol. (See the
.code quote
operator).

Of course, this particular
.code call
expression can just be replaced by the direct invocation
syntax
.codn "@(foo b)" .

The power of
.code call
lies in being able to specify the function as a value which
comes from elsewhere in the program, as in the following example.

.cblk
\ @(define foo (arg))
  @(bind arg "abc")
  @(end)
  @(bind f @'foo)
  @(call f b)
.cble

Here the
.code call
directive obtains the name of the function from the
.code f
variable.

Note that function names are resolved to functions in the environment
that is apparent at the point in execution where the
.code call
takes place. Very simply, the directive
.code "@(call f args ...)"
is precisely equivalent to
.code "@(s args ...)"
if, at the point of the call,
.code f
is a variable which holds the symbol
.code s
and symbol
.code s
is defined as a function. Otherwise it is erroneous.

.SS* Modularization

.dirs load include

The syntax of the
.code load
and
.code include
directives is:

.cblk
.mets @(load << expr )
.mets @(include << expr )
.cble

Where
.meta expr
evaluates to a string giving the path of the file to load.
Unless the path is absolute, it is interpreted relative to the directory of the
source file from which the
.code @(load)
syntax was read. If there was no such
source file (for instance, the script was read from standard input),
then it is resolved relative to the current working directory.

If the file cannot be opened, then the
.code .txr
suffix is added and another
attempt is made. Thus load expressions need not refer to the suffix.
In the future, additional suffixes may be searched (compiled versions
of a file).

The two directives differ as follows. The action of
.code load
is not performed immediately but at evaluation time. Evaluation time
occurs after a \*(TX program is read from beginning to end and parsed.
The action of
.code include
is performed immediately, as the code is being scanned and parsed.
That is to say, as the \*(TX parser encounters
.code @(include)
it processes it immediately. The included material is read and parsed, and its
syntax tree is substituted in place of the
.code include
directive. The parser then
continues processing the original file after the
.code include
directive.

Note: the
.code include
directive is useful for loading \*(TX files which contain Lisp macros
which are needed by the parent program. The parent program cannot use
.code load
to bring in macros because macros are required during expansion, which
takes place prior to evaluation time, whereas
.code load
doesn't execute until evaluation time.

See also: the
.code self-path
and
.code stdlib
variables in \*(TL.

.SS* Output

.NP* Introduction

A \*(TX query may perform custom output. Output is performed by
.code output
clauses,
which may be embedded anywhere in the query, or placed at the end.  Output
occurs as a side effect of producing a part of a query which contains an
.code @(output)
directive, and is executed even if that part of the query ultimately
fails to find a match. Thus output can be useful for debugging.
An
.code output
clause specifies that its output goes to a file, pipe, or (by
default) standard output. If any output clause is executed whose destination is
standard output, \*(TX makes a note of this, and later, just prior to
termination, suppresses the usual printing of the variable bindings or the word
false.

.dir output

The syntax of the
.code @(output)
directive is:

.cblk
.mets @(output [ < destination ] { < bool-keyword | < keyword < value }* )
  .
  . one or more output directives or lines
  .
  @(end)
.cble

If the directive has arguments, then the first one is evaluated.
If it is an object other than a keyword symbol, then it specifies
the optional
.metn destination .
Any remaining arguments after the optional destination are
the keyword list. If the destination is missing, then the
entire argument list is a keyword list.

The destination may be a string which gives the path name of
a file to open for output. If the name is
.code -
it instead denotes standard output, and if it begins with
.code !
then the rest of the shell is treated as a shell command
to which the output is piped.  The destination string may be specified as a
variable which holds text, as a string literal or as a quasiliteral

Alternatively, the destination may be a stream object.

The keyword list consists of a mixture of Boolean keywords which
do not have an argument, or keywords with arguments.

The following Boolean keywords are supported:

.coIP :nothrow
The output directive throws an exception if the output destination
cannot be opened, unless the
.code :nothrow
keyword is present, in which
case the situation is treated as a match failure.

Note that since command pipes are processes that report errors
asynchronously, a failing command will not throw an immediate exception that
can be suppressed with
.codn :nothrow .
This is for synchronous errors, like
trying to open a destination file, but not having permissions, etc.

.coIP :append
This keyword is meaningful for files, specifying append mode: the output is to
be added to the end of the file rather than overwriting the file.

The following value keywords are supported:

.coIP :filter
The argument can be a symbol, which specifies a filter to be applied to
the variable substitutions occurring within the
.code output
clause.
The argument can also be a list of filter symbols, which specifies
that multiple filters are to be applied, in left to right order.

See the later sections Output Filtering below, and The Deffilter Directive.

.coIP :into
The argument of
.code :into
is a symbol which denotes a variable.
The output will go into that variable.  If the variable is unbound,
it will be created. Otherwise, its contents are overwritten
unless the
.code :append
keyword is used. If
.code :append
is used, then
the new content will be appended to the previous content of
the variable, after flattening the content to a list,
as if by the
.code flatten
directive.

.coIP :named
The argument of
.code :named
is a symbol which denotes a variable.
The file or pipe stream which is opened for the output is
stored in this variable, and is not closed at the end of the
output block. This allows a subsequent output block to continue
output on the same stream, which is possible using the
next two keywords,
.code :continue
or
.codn :finish .
A new binding is established for the variable, even if it
already has an existing binding.

.coIP :continue
A destination should not be specified if
.code :continue
is used.  The argument of
.code :continue
is an expression, such as a variable name, that evaluates to a
stream object. That stream object is used for the output block.
At the end of the output block, the stream is flushed, but not
closed.  A usage example is given in the documentation for the Close Directive
below.

.coIP :finish
A destination should not be specified if
.code :finish
is used.  The argument of
.code :finish
is an expression, such as a variable name, that evaluates to a
stream object. That stream object is used for the output block.
At the end of the output block, the stream is closed.
An example is given in the documentation for the Close Directive
below.

.NP* Output Text

Text in an output clause is not matched against anything, but is output
verbatim to the destination file, device or command pipe.

.NP* Output Variables

Variables occurring in an output clause do not match anything; instead
their contents are output.

A variable being output can be any object. If it is of a type other
than a list or string, it will be converted to a string as if by the
.code tostring
function in \*(TL.

A list is converted to a string in a special way: the elements are
individually converted to a string and then they are catenated together.
The default separator string is a single space: an alternate separation
can be specified as an argument in the brace substitution syntax.
Empty lists turn into an empty string.

Lists may be output within
.code @(repeat)
or
.code @(rep)
clauses. Each nesting of
these constructs removes one level of nesting from the list variables
that it contains.

In an output clause, the
.cblk
.meti >> @{ name << number }
.cble
variable syntax generates fixed-width
field, which contains the variable's text.  The absolute value of the
number specifies the field width. For instance
.code -20
and
.code 20
both specify a field
width of twenty.  If the text is longer than the field, then it overflows the
field. If the text is shorter than the field, then it is left-adjusted within
that field, if the width is specified as a positive number, and right-adjusted
if the width is specified as negative.

An output variable may specify a filter which overrides any filter established
for the output clause. The syntax for this is
.cblk
.meti @{NAME :filter << filterspec }.
.cble
The filter specification syntax is the same as in the output clause.
See Output Filtering below.

.NP* Output Variables: Indexing

Additional syntax is supported in output variables that does not appear
in pattern matching variables.

A square bracket index notation may be used to extract elements or
ranges from a variable, which works with strings, vectors and lists.  Elements
are indexed from zero. This notation is only available in brace-enclosed
syntax, and looks like this:

.meIP <> @{name[ expr ]}
Extract the element at the position given by
.metn expr .

.meIP <> @{name[ expr1..expr2 ]}
Extract a range of elements from the position given by
.metn expr1 ,
up to
one position less than the position given by
.metn expr2 .

If the variable is a list, it is treated as a list substitution,
exactly as if it were the value of an unsubscripted list variable.
The elements of the list are converted to strings and catenated
together wit ha separator string between them, the default one being
a single space.

An alternate character may be given as a string argument in the brace
notation.
.PP

Example:

.cblk
  @(bind a ("a" "b" "c" "d"))
  @(output)
  @{a[1..3] "," 10}
  @(end)
.cble

The above produces the text
.str b,c
in a field
.code 10
spaces wide. The
.code [1..3]
argument extracts a range of
.codn a ;
the
.str ","
argument specifies an alternate
separator string, and
.code 10
specifies the field width.

.NP* Output Substitutions

The brace syntax has another syntactic and semantic extension in
.code output
clauses. In place
of the symbol, an expression may appear. The value of that expression
is substituted.

Example:

.cblk
 @(bind a "foo")
 @(output)
 @{`@a:` -10}
.cble

Here, the quasiliteral expression
.code `@a:`
is evaluated, producing the string
.strn foo: .
This string is printed right-adjusted in a
.code 10
character field.

.dir repeat

The
.code repeat
directive generates repeated text from a "boilerplate",
by taking successive elements from lists. The syntax of repeat is
like this:

.cblk
  @(repeat)
  .
  .
  main clause material, required
  .
  .
  special clauses, optional
  .
  .
  @(end)
.cble

.code repeat
has four types of special clauses, any of which may be
specified with empty contents, or omitted entirely. They are described
below.

.code repeat
takes arguments, also described below.

All of the material in the main clause and optional clauses
is examined for the presence of variables.  If none of the variables
hold lists which contain at least one item, then no output is performed,
(unless the repeat specifies an
.code @(empty)
clause, see below).
Otherwise, among those variables which contain non-empty lists, repeat finds
the length of the longest list. This length of this list determines the number
of repetitions, R.

If the
.code repeat
contains only a main clause, then the lines of this clause is
output R times. Over the first repetition, all of the variables which, outside
of the repeat, contain lists are locally rebound to just their first item. Over
the second repetition, all of the list variables are bound to their second
item, and so forth. Any variables which hold shorter lists than the longest
list eventually end up with empty values over some repetitions.

Example: if the list
.code A
holds
.strn 1 ,
.str 2
and
.strn 3 ;
the list
.code B
holds
.strn A ,
.strn B ;
and the variable
.code C
holds
.strn X ,
then

.cblk
  @(repeat)
  >> @C
  >> @A @B
  @(end)
.cble

will produce three repetitions (since there are two lists, the longest
of which has three items). The output is:

.cblk
  >> X
  >> 1 A
  >> X
  >> 2 B
  >> X
  >> 3
.cble

The last line has a trailing space, since it is produced by
.strn "@A @B" ,
where
.code B
has an empty value. Since
.code C
is not a list variable, it
produces the same value in each repetition.

The special clauses are:

.coIP @(single)
If the
.code repeat
produces exactly one repetition, then the contents of this clause
are processed for that one and only repetition, instead of the main clause
or any other clause which would otherwise be processed.

.coIP @(first)
The body of this clause specifies an alternative body to be used for the first
repetition, instead of the material from the main clause.

.coIP @(last)
The body of this clause is used instead of the main clause for the last
repetition.

.coIP @(empty)
If the repeat produces no repetitions, then the body of this clause is output.
If this clause is absent or empty, the repeat produces no output.

.coIP "@(mod n m)"
The forms
.code n
and
.code m
are expressions that evaluate to integers. The value of
.code m
should be nonzero. The clause denoted this way is active if the repetition
modulo
.code m
is equal to
.codn n .
The first repetition is numbered zero.
For instance the clause headed by
.code "@(mod 0 2)"
will be used on repetitions 
0, 2, 4, 6, ...  and
.code "@(mod 1 2)"
will be used on repetitions 1, 3, 5, 7, ...

.coIP "@(modlast n m)"
The meaning of
.code n
and
.code m
is the same as in
.codn "@(mod n m)" ,
but one more condition
is imposed. This clause is used if the repetition modulo
.code m
is equal to
.codn n ,
and if it is the last repetition.
.PP

The precedence among the clauses which take an iteration is:
.codn "single > first > mod > modlast > last > main" .
That is if two or more of these
clauses can apply to a repetition, then the leftmost one in this precedence
list applies. For instance, if there is just a single repetition, then any of
these special clause types can apply to that repetition, since it is the only
repetition, as well as the first and last one. In this situation, if there is a
.code @(single)
clause present, then the repetition is processed using that clause.
Otherwise, if there is a
.code @(first)
clause present, that clause is used. Failing
that,
.code @(mod)
is used if there is such a clause and its numeric conditions
are satisfied. If there isn't, then
.code @(modlast)
clauses are considered, and if there
are none, or none of them activate, then
.code @(last)
is considered. Finally if none
of all these clauses are present or apply, then the repetition is processed
using the main clause.

Repeat supports arguments.

.cblk
.mets @(repeat
.mets \ \ \  [:counter >> { symbol | >> ( symbol << expr )}]
.mets \ \ \  [:vars >> ({ symbol | >> ( symbol << expr )}*)])
.cble

The
.code :counter
argument designates a symbol which will behave as an integer
variable over the scope of the clauses inside the repeat. The variable provides
access to the repetition count, starting at zero, incrementing with each
repetition. If the the argument is given as
.cblk
.meti >> ( symbol << expr )
.cble
then
.meta expr
is a Lisp expression whose value is taken as a displacement value which
is added to each iteration of the counter. For instance
.code ":counter (c 1)"
specifies a counter
.code c
which counts from 1.

The
.code :vars
argument specifies a list of variable names, or pairs consisting of a variable
name and Lisp expression. For every variable paired with a Lisp expression,
the expression is evaluated, and a binding is introduced, associating
that variable with the expression's value.

The repeat directive then processes the list of variables, selecting from it
those which have a binding, either a previously existing binding or one just
introduced from a Lisp expression. For each selected variable, repeat
will assume that the variable occur in the repeat block and contains
a list to be iterated.

Thus
.code :vars
Firstly, it is needed for situations in which
.code @(repeat)
is not able to deduce the existence of a variable in the block.
It does not dig very deeply to discover variables, and does not "see"
variables that are referenced via embedded \*(TL expressions.
For instance, the following produces no output:

.cblk
  @(bind list ("a" "b" "c"))
  @(output)
  @(repeat)
  @(format nil "<~a>" list)
  @(end)
  @(end)
.cble

Although the list variable appears in the repeat block, it is embedded
in a \*(TL construct. That construct will never be evaluated because
no repetitions take place: the repeat construct doesn't find any variables
and so doesn't iterate. The remedy is to provide a little help via
the :vars parameter:

.cblk
  @(bind list ("a" "b" "c"))
  @(output)
  @(repeat :vars (list))
  @(format nil "<~a>" list)
  @(end)
  @(end)
.cble

Now the repeat block iterates over list and the output is:

.cblk
  <a>
  <b>
  <c>
.cble

Secondly, The variable binding syntax supported by
.code :vars
additionally provides a solution for situations when it is necessary to iterate
over some list, but that list is the result of an expression, and not stored in
any variable. A repeat block iterates only over lists emanating from variables;
it does not iterate over lists pulled from arbitrary expressions.

Example: output all file names matching the
.code *.txr
pattern in the current directory:

.cblk
  @(output)
  @(repeat :vars (name (glob "*.txr")))
  @name
  @(end)
  @(end)
.cble

.coNP Nested @ repeat directives

If a
.code repeat
clause encloses variables which hold multidimensional lists,
those lists require additional nesting levels of repeat (or rep).
It is an error to attempt to output a list variable which has not been
decimated into primary elements via a repeat construct.

Suppose that a variable
.code X
is two-dimensional (contains a list of lists).
.code X
must be twice nested in a
.codn repeat .
The outer repeat will traverse the lists
contained in
.codn X .
The inner repeat will traverse the elements of each of these
lists.

A nested repeat may be embedded in any of the clauses of a repeat,
not only the main clause.

.dir rep

The
.code rep
directive is similar to
.codn repeat .
Whereas
.code repeat
is line oriented,
.code rep
generates material within a line. It has all the same clauses,
but everything is specified within one line:

.cblk
  @(rep)... main material ... .... special clauses ...@(end)
.cble

More than one
.code @(rep)
can occur within a line, mixed with other material.
A
.code @(rep)
can be nested within a
.code @(repeat)
or within another
.codn @(rep) .

Also,
.code @(rep)
accepts the same
.code :counter
and
.code :vars
arguments.

.coNP @ repeat and @ rep Examples

Example 1: show the list
.code L
in parentheses, with spaces between
the elements, or the word
.code EMPTY
if the list is empty:

.cblk
  @(output)
  @(rep)@L @(single)(@L)@(first)(@L @(last)@L)@(empty)EMPTY@(end)
  @(end)
.cble

Here, the
.code @(empty)
clause specifies
.codn EMPTY .
So if there are no repetitions,
the text
.code EMPTY
is produced. If there is a single item in the list
.codn L ,
then
.code @(single)(@L)
produces that item between parentheses.  Otherwise
if there are two or more items, the first item is produced with
a leading parenthesis followed by a space by
.code @(first)(@L
and the last item is produced with a closing parenthesis:
.codn @(last)@L) .
All items in between are emitted with a trailing space by
the main clause:
.codn @(rep)@L .

Example 2: show the list L like Example 1 above, but the empty list is
.codn () .

.cblk
  @(output)
  (@(rep)@L @(last)@L@(end))
  @(end)
.cble

This is simpler. The parentheses are part of the text which
surrounds the
.code @(rep)
construct, produced unconditionally.
If the list
.code L
is empty, then
.code @(rep)
produces no output, resulting in
.codn () .
If the list
.code L
has one or more items, then they are produced with
spaces each one, except the last which has no space.
If the list has exactly one item, then the
.code @(last)
applies to it
instead of the main clause: it is produced with no trailing space.

.dir close

The syntax of the
.code close
directive is:

.cblk
.mets @(close << expr )
.cble

Where
.meta expr
evaluates to a stream. The
.code close
directive can be
used to explicitly close streams created using
.cblk
.meti @(output ... :named << var )
.cble
syntax, as an alternative to
.cblk
.meti @(output :finish << expr ).
.cble

Examples:

Write two lines to
.str foo.txt
over two output blocks using
a single stream:

.cblk
  @(output "foo.txt" :named foo)
  Hello,
  @(end)
  @(output :continue foo)
  world!
  @(end)
  @(close foo)
.cble

The same as above, using
.code :finish
rather than
.code :continue
so that the stream is closed at the end of the second block:

.cblk
  @(output "foo.txt" :named foo)
  Hello,
  @(end)
  @(output :finish foo)
  world!
  @(end)
.cble

.NP* Output Filtering

Often it is necessary to transform the output to preserve its meaning
under the convention of a given data format. For instance, if a piece of
text contains the characters
.code <
or
.codn > ,
then if that text is being
substituted into HTML, these should be replaced by
.code &lt;
and
.codn &gt; .
This is what filtering is for.  Filtering is applied to the contents of output
variables, not to any template text.
\*(TX implements named filters.  Built-in filters are named by keywords, given
below. User-defined filters are possible, however.  See notes on the deffilter
directive below.

Instead of a filter name, the syntax
.cblk
.meti (fun << name )
.cble
can be used. This
denotes that the function called
.meta name
is to be used as a filter.
This is described in the next section Function Filters below.

Built-in filters named by keywords:

.coIP :tohtml
Filter text to HTML, representing special characters using HTML
ampersand sequences. For instance
.code >
is replaced by
.codn &gt; .

.coIP :tohtml*
Filter text to HTML, representing special characters using HTML
ampersand sequences. Unlike
.codn :tohtml ,
this filter doesn't treat the single and double quote characters.
It is not suitable for preparing HTML fragments which end up
inserted into HTML tag attributes.

.coIP :fromhtml
Filter text with HTML codes into text in which the codes are replaced by the
corresponding characters. For instance
.code &gt;
is replaced by
.codn > .

.coIP :upcase
Convert the 26 lower case letters of the English alphabet to upper case.

.coIP :downcase
Convert the 26 upper case letters of the English alphabet to lower case.

.coIP :frompercent
Decode percent-encoded text. Character triplets consisting
of the
.code %
character followed by a pair of hexadecimal digits (case insensitive)
are are converted to bytes having the value represented by the hexadecimal
digits (most significant nybble first). Sequences of one or more such bytes are
treated as UTF-8 data  and decoded to characters.

.coIP :topercent
Convert to percent encoding according to RFC 3986. The text is first converted
to UTF-8 bytes. The bytes are then converted back to text as follows.
Bytes in the range 0 to 32, and 127 to 255 (note: including the ASCII DEL), 
bytes whose values correspond to ASCII characters which are listed by RFC 3986 
as being in the "reserved set", and the byte value corresponding to the
ASCII
.code %
character are encoded as a three-character sequence consisting
of the
.code %
character followed by two hexadecimal digits derived from the
byte value (most significant nybble first, upper case). All other bytes
are converted directly to characters of the same value without any such
encoding.

.coIP :fromurl
Decode from URL encoding, which is like percent encoding, except that
if the unencoded
.code +
character occurs, it is decoded to a space character.  Of course
.code %20
still decodes to space, and
.code %2B
to the
.code +
character.

.coIP :tourl
Encode to URL encoding, which is like percent encoding except that
a space maps to
.code +
rather than
.codn %20 .
The
.code +
character, being in the
reserved set, encodes to
.codn %2B .

.coIP :frombase64
Decode from the Base 64 encoding described in RFC 4648.

.coIP :tobase64
Encodes to the RFC 4648 Base 64 encoding.

.coIP :tonumber
Converts strings to numbers. Strings that contain a period,
.code e
or
.code E
are converted to floating point as if by the Lisp function
.codn flo-str .
Otherwise they are converted to integer as if using
.code int-str
with a radix of 10.
Non-numeric junk results in the object
.codn nil .

.coIP :toint
Converts strings to integers as if using
.code int-str
with a radix of 10.
Non-numeric junk results in the object
.codn nil .

.coIP :tofloat
Converts strings to floating-point values as if using the function
.codn flo-str .
Non-numeric junk results in the object
.codn nil .

.coIP :hextoint
Converts strings to integers as if using
.code int-str
with a radix of 16.
Non-numeric junk results in the object
.codn nil .

.PP

Examples:

To escape HTML characters in all variable substitutions occurring in an
output clause, specify
.code ":filter :tohtml"
in the directive:

.cblk
  @(output :filter :tohtml)
  ...
  @(end)
.cble

To filter an individual variable, add the syntax to the variable spec:

.cblk
  @(output)
  @{x :filter :tohtml}
  @(end)
.cble

Multiple filters can be applied at the same time. For instance:

.cblk
  @(output)
  @{x :filter (:upcase :tohtml)}
  @(end)
.cble

This will fold the contents of
.code x
to upper case, and then encode any special
characters into HTML. Beware of combinations that do not make sense.
For instance, suppose the original text is HTML, containing codes
like
.codn &quot; .
The compound filter
.code "(:upcase :fromhtml)"
will not work
because
.code &quot;
will turn to
.code &QUOT;
which no longer be recognized by the
.code :fromhtml
filter, since the entity names in HTML codes
are case-sensitive.

Capture some numeric variables and convert to numbers:

.cblk
  @date @time @temperature @pressure
  @(filter :tofloat temperature pressure)
  @;; temperature and pressure can now be used in calculations
.cble

.NP* Function Filters

A function can be used as a filter. For this to be possible, the function must
conform to certain rules:
.IP 1.
The function must take two special arguments, which may be followed
by additional arguments.

.IP 2.
When the function is called, the first argument will be bound to a string,
and the second argument will be unbound. The function must produce a 
value by binding it to the second argument. If the filter is to be used
as the final filter in a chain, it must produce a string.

For instance, the following is a valid filter function:

.cblk
  @(define foo_to_bar (in out))
  @  (next :string in)
  @  (cases)
  foo
  @    (bind out "bar")
  @  (or)
  @    (bind out in)
  @  (end)
  @(end)
.cble

This function binds the
.code out
parameter to
.str bar
if the in parameter
is
.strn foo ,
otherwise it binds the
.code out
parameter to a copy of the
.code in
parameter.
This is a simple filter.

To use the filter, use the syntax
.code "(:fun foo_to_bar)"
in place of a filter name.
For instance in the bind directive:

.cblk
  @(bind "foo" "bar" :lfilt (:fun foo_to_bar))
.cble

The above should succeed since the left side is filtered from
.str foo
to
.strn bar ,
so that there is a match.

Of course, function filters can be used in a chain:

.cblk
  @(output :filter (:downcase (:fun foo_to_bar) :upcase))
  ...
  @(end)
.cble

Here is a split function which takes an extra argument
which specifies the separator:

.cblk
  @(define split (in out sep))
  @  (next :list in)
  @  (coll)@(maybe)@token@sep@(or)@token@(end)@(end)
  @  (bind out token)
  @(end)
.cble

Furthermore, note that it produces a list rather than a string.
This function separates the argument in into tokens according to the
separator text carried in the variable
.codn sep .

Here is another function,
.codn join ,
which catenates a list:

.cblk
  @(define join (in out sep))
  @  (output :into out)
  @  (rep)@in@sep@(last)@in@(end)
  @  (end)
  @(end)
.cble

Now here is these two being used in a chain:

.cblk
  @(bind text "how,are,you")
  @(output :filter (:fun split ",") (:fun join "-"))
  @text
  @(end)
.cble

Output:

.cblk
  how-are-you
.cble

When the filter invokes a function, it generates the first two arguments
internally to pass in the input value and capture the output. The remaining
arguments from the
.code "(:fun ...)"
construct are also passed to the function.
Thus the string objects
.str ","
and
.str "-"
are passed as the
.code sep
argument to
.code split
and
.codn join .

Note that
.code split
puts out a list, which
.code join
accepts. So the overall filter
chain operates on a string: a string goes into split, and a string comes out of
join.

.dir deffilter

The
.code deffilter
directive allows a query to define a custom filter, which
can then be used in
.code output
clauses to transform substituted data.

This directive's syntax is illustrated in this example:
.IP code:
.cblk
\ @(deffilter rot13
    ("a" "n")
    ("b" "o")
    ("c" "p")
    ("d" "q")
    ("e" "r")
    ("f" "s")
    ("g" "t")
    ("h" "u")
    ("i" "v")
    ("j" "w")
    ("k" "x")
    ("l" "y")
    ("m" "z")
    ("n" "a")
    ("o" "b")
    ("p" "c")
    ("q" "d")
    ("r" "e")
    ("s" "f")
    ("t" "g")
    ("u" "h")
    ("v" "i")
    ("w" "j")
    ("x" "k")
    ("y" "l")
    ("z" "m"))
 @(collect)
 @line
 @(end)
 @(output :filter rot13)
 @(repeat)
 @line
 @(end)
 @(end)
.cble
.IP data:
.cblk
\ hey there!
.cble
.IP output:
.cblk
\ url gurer!
.cble
.PP

The
.code deffilter
symbol must be followed by the name of the filter to be defined,
followed by forms which evaluate to lists of strings. Each list must
be at least two elements long and specifies one or more texts which are mapped
to a replacement text. For instance, the following specifies a telephone keypad
mapping from upper case letters to digits.

.cblk
  @(deffilter alpha_to_phone ("E" "0")
                             ("J" "N" "Q" "1")
                             ("R" "W" "X" "2")
                             ("D" "S" "Y" "3")
                             ("F" "T" "4")
                             ("A" "M" "5")
                             ("C" "I" "V" "6")
                             ("B" "K" "U" "7")
                             ("L" "O" "P" "8")
                             ("G" "H" "Z" "9"))

  @(deffilter foo (`@a` `@b`) ("c" `->@d`))

  @(bind x ("from" "to"))
  @(bind y ("---" "+++"))
  @(deffilter sub x y)
.cble

The last deffilter has the same effect as the
.cblk
@(deffilter sub ("from" "to") ("---" "+++"))
.cble
directive.

Filtering works using a longest match algorithm. The input is scanned from left
to right, and the longest piece of text is identified at every character
position which matches a string on the left hand side, and that text is
replaced with its associated replacement text. The scanning then continues
at the first character after the matched text.

If none of the strings matches at a given character position, then that
character is passed through the filter untranslated, and the scan continues at
the next character in the input.

Filtering is not in-place but rather instantiates a new text, and so
replacement text is not re-scanned for more replacements.

If a filter definition accidentally contains two or more repetitions of the
same left hand string with different right hand translations, the later ones
take precedence. No warning is issued.


.dir filter

The syntax of the
.code filter
directive is:

.cblk
  @(filter FILTER { VAR }+ )
.cble

A filter is specified, followed by one or more variables whose values
are filtered and stored back into each variable.

Example: convert
.codn a ,
.codn b ,
and
.code c
to upper case and HTML encode:

.cblk
  @(filter (:upcase :tohtml) a b c)
.cble

.SS* Exceptions

.NP* Introduction

The exceptions mechanism in \*(TX is another
disciplined form of non-local transfer, in addition to the blocks
mechanism (see BLOCKS above).  Like blocks, exceptions provide a construct
which serves as the target for a dynamic exit.  Both blocks and exceptions
can be used to bail out of deep nesting when some condition occurs.
However, exceptions provide more complexity. Exceptions are useful for
error handling, and \*(TX in fact maps certain error situations to exception
control transfers. However, exceptions are not inherently an error-handling
mechanism; they are a structured dynamic control transfer mechanism, one
of whose applications is error handling.

An exception control transfer (simply called an exception) is always identified
by a symbol, which is its type. Types are organized in a subtype-supertype
hierarchy.  For instance, the
.code file-error
exception type is a subtype of the
.code error
type. This means that a file error is a kind of error. An exception
handling block which catches exceptions of type
.code error
will catch exceptions of
type
.codn file-error ,
but a block which catches
.code file-error
will not catch all
exceptions of type
.codn error .
A
.code query-error
is a kind of error, but not a kind of
.codn file-error .
The symbol
.code t
is the supertype of every type: every exception type
is considered to be a kind of
.codn t .
(Mnemonic:
.code t
stands for type, as in any type).

Exceptions are handled using
.code @(catch)
clauses within a
.code @(try)
directive.

In addition to being useful for exception handling, the
.code @(try)
directive
also provides unwind protection by means of a
.code @(finally)
clause,
which specifies query material to be executed unconditionally when
the try clause terminates, no matter how it terminates.

.dir try

The general syntax of the
.code try
directive is

.cblk
  @(try)
  ... main clause, required ...
  ... optional catch clauses ...
  ... optional finally clause
  @(end)
.cble

A
.code catch
clause looks like:

.cblk
  @(catch TYPE [ PARAMETERS ])
  .
  .
  .
.cble

and also this simple form:

.cblk
  @(catch)
  .
  .
  .
.cble

which catches all exceptions, and is equivalent
to
.codn "@(catch t)" .

A
.code finally
clause looks like:

.cblk
  @(finally)
  ...
  .
  .
.cble

The main clause may not be empty, but the catch and finally may be.

A try clause is surrounded by an implicit anonymous block (see BLOCKS section
above). So for instance, the following is a no-op (an operation with no effect,
other than successful execution):

.cblk
  @(try)
  @(accept)
  @(end)
.cble

The
.code @(accept)
causes a successful termination of the implicit anonymous block.
Execution resumes with query lines or directives which follow, if any.

.code try
clauses and blocks interact. For instance, an
.code accept
from within
a try clause invokes a
.codn finally .
.IP code:
.cblk
\ @(block foo)
 @  (try)
 @    (accept foo)
 @  (finally)
 @     (output)
 bye!
 @     (end)
 @  (end)
.cble
.IP output:
.cblk
\ bye!
.cble
.PP

How this works: the
.code try
block's main clause is
.codn "@(accept foo)" .
This causes
the enclosing block named
.code foo
to terminate, as a successful match.
Since the
.code try
is nested within this block, it too must terminate
in order for the block to terminate. But the try has a
.code finally
clause,
which executes unconditionally, no matter how the try block
terminates. The
.code finally
clause performs some output, which is seen.

.coNP The @ finally clause

A
.code try
directive can terminate in one of three ways. The main clause
may match successfully, and possibly yield some new variable bindings.
The main clause may fail to match. Or the main clause may be terminated
by a non-local control transfer, like an exception being thrown or a block
return (like the block foo example in the previous section).

No matter how the
.code try
clause terminates, the
.code finally
clause is processed.

The
.code finally
clause is itself a query which binds variables, which leads to
questions: what happens to such variables? What if the
.code finally
block fails
as a query? As well as: what if a
.code finally
clause itself initiates a
control transfer?  Answers follow.

Firstly, a
.code finally
clause will contribute variable bindings only if the main
clause terminates normally (either as a successful or failed match).
If the main clause of the
.code try
block successfully matches, then the
.code finally
block continues
matching at the next position in the data, and contributes bindings.
If the main clause fails, then the
.code finally
block tries to match at the same position where the main clause failed.

The overall
.code try
directive succeeds as a match if either the main clause
or the
.code finally
clause succeed. If both fail, then the try directive is
a failed match.

Example:
.IP code:
.cblk
\ @(try)
 @a
 @(finally)
 @b
 @(end)
 @c
.cble
.IP data:
.cblk
\ 1
 2
 3
.cble
.IP result:
.cblk
\ a="1"
 b="2"
 c="3"
.cble
.PP

In this example, the main clause of the
.code try
captures line
.str 1
of the data as
variable
.codn a ,
then the finally clause captures
.str 2
as
.codn b ,
and then the query continues with the
.code @c
line after try block, so that
.code c
captures
.strn "3" .

Example:
.IP code:
.cblk
\ @(try)
 hello @a
 @(finally)
 @b
 @(end)
 @c
.cble
.IP data:
.cblk
\ 1
 2
.cble
.IP result:
.cblk
\ b="1"
 c="2"
.cble
.PP

In this example, the main clause of the
.code try
fails to match, because
the input is not prefixed with
.strn "hello " .
However, the
.code finally
clause
matches, binding
.code b
to
.strn "1" .
This means that the try block is a successful
match, and so processing continues with
.code @c
which captures
.strn "2" .

When
.code finally
clauses are processed during a non-local return,
they have no externally visible effect if they do not bind variables.
However, their execution makes itself known if they perform side effects,
such as output.

A
.code finally
clause guards only the main clause and the
.code catch
clauses. It does not
guard itself.   Once the finally clause is executing, the
.code try
block is no
longer guarded.  This means if a nonlocal transfer, such as a block accept
or exception, is initiated within the finally clause, it will not re-execute
the
.code finally
clause. The
.code finally
clause is simply abandoned.

The disestablishment of blocks and
.code try
clauses is properly interleaved
with the execution of
.code finally
clauses. This means that all surrounding
exit points are visible in a
.code finally
clause, even if the
.code finally
clause
is being invoked as part of a transfer to a distant exit point.
The finally clause can make a control transfer to an exit point which
is more near than the original one, thereby "hijacking" the control
transfer. Also, the anonymous block established by the
.code try
directive
is visible in the
.code finally
clause.

Example:

.cblk
  @(try)
  @  (try)
  @    (next "nonexistent-file")
  @  (finally)
  @    (accept)
  @  (end)
  @(catch file-error)
  @  (output)
  file error caught
  @  (end)
  @(end)
.cble

In this example, the
.code @(next)
directive throws an exception of type
.codn file-error ,
because the given file does not exist. The exit point for this exception is the
.code "@(catch file-error)"
clause in the outer-most
.code try
block. The inner block is
not eligible because it contains no catch clauses at all. However, the inner
try block has a finally clause, and so during the processing of this
exception which is headed for
.codn "@(catch file-error)" ,
the
.code finally
clause performs an anonymous
.codn accept .
The exit point for that
.code accept
is the anonymous block
surrounding the inner
.codn try .
So the original
transfer to the
.code catch
clause is thereby abandoned. The inner
.code try
terminates
successfully due to the
.codn accept ,
and since it constitutes the main clause of the outer try,
that also terminates successfully. The
.str "file error caught"
message is never printed.

.c1NP catch clauses

.code catch
clauses establish their associated
.code try
blocks as potential exit points for
exception-induced control transfers (called "throws").

A
.code catch
clause specifies an optional list of symbols which represent
the exception types which it catches. The
.code catch
clause will catch
exceptions which are a subtype of any one of those exception types.

If a
.code try
block has more than one
.code catch
clause which can match a given
exception, the first one will be invoked.

When a
.code catch
is invoked, it is of course understood that the main clause did
not terminate normally, and so the main clause could not have produced any
bindings.

.code catch
clauses are processed prior to
.codn finally .

If a
.code catch
clause itself throws an exception, that exception cannot
be caught by that same clause or its siblings in the same try block.
The
.code catch
clauses of that block are no longer visible at that point.
Nevertheless, the
.code catch
clauses are still protected by the finally block.
If a catch clause throws, or otherwise terminates, the
.code finally
block is still processed.

If a
.code finally
block throws an exception, then it is simply aborted;
the remaining directives in that block are not processed.

So the success or failure of the
.code try
block depends on the behavior of the
.code catch
clause or the
.code finally
clause, if there is one. If either of them succeed, then the try
block is considered a successful match.

Example:
.IP code:
.cblk
\ @(try)
 @  (next "nonexistent-file")
 @  x
 @  (catch file-error)
 @a
 @(finally)
 @b
 @(end)
 @c
.cble
.IP data:
.cblk
\ 1
 2
 3
.cble
.IP result:
.cblk
\ a="1"
 b="2"
 c="3"
.cble
.PP

Here, the
.code try
block's main clause is terminated abruptly by a
.code file-error
exception from the
.code @(next)
directive.   This is handled by the
.code catch
clause, which binds variable
.code a
to the input line
.strn 1 .
Then the
.code finally
clause executes, binding
.code b
to
.strn  2 .
The
.code try
block then terminates successfully, and so
.code @c
takes
.strn "3" .

.coNP @ catch Clauses with Parameters

A
.code catch
clause may have parameters following the type name, like this:

.cblk
  @(catch pair (a b))
.cble

To write a catch-all with parameters, explicitly write the
master supertype t:

.cblk
  @(catch t (arg ...))
.cble

Parameters are useful in conjunction with
.codn throw .
The built-in
.code error
exceptions carry one argument, which is a string containing
the error message. Using
.codn throw ,
arbitrary parameters can be passed
from the throw site to the catch site.

.dir throw

The
.code throw
directive generates an exception. A type must be specified,
followed by optional arguments. For example,

.cblk
  @(throw pair "a" `@file.txt`)
.cble

throws an exception of type
.codn pair ,
with two arguments, being
.str a
and the expansion of the quasiliteral
.codn `@file.txt` .

The selection of the target
.code catch
is performed purely using the type
name; the parameters are not involved in the selection.

Binding takes place between the arguments given in
.code throw
and the target
.codn catch .

If any
.code catch
parameter, for which a
.code throw
argument is given, is a bound
variable, it has to be identical to the argument, otherwise the catch fails.
(Control still passes to the
.codn catch ,
but the catch is a failed match).

.IP code:
.cblk
\ @(bind a "apple")
 @(try)
 @(throw e "banana")
 @(catch e (a))
 @(end)
.cble
.IP result:
.cblk
\ [query fails]
.cble
.PP

If any argument is an unbound variable, the corresponding parameter
in the
.code catch
is left alone: if it is an unbound variable, it remains
unbound, and if it is bound, it stays as is.
.IP code:
.cblk
\ @(try)
 @(trow e "honda" unbound)
 @(catch e (car1 car2))
 @car1 @car2
 @(end)
.cble
.IP data:
.cblk
\ honda toyota
.cble
.IP result:
.cblk
\ car1="honda"
 car2="toyota"
.cble
.PP

If a
.code catch
has fewer parameters than there are throw arguments,
the excess arguments are ignored:
.IP code:
.cblk
\ @(try)
 @(throw e "banana" "apple" "pear")
 @(catch e (fruit))
 @(end)
.cble
.IP result:
.cblk
\ fruit="banana"
.cble
.PP

If a
.code catch
has more parameters than there are throw arguments, the excess
parameters are left alone. They may be bound or unbound variables.
.IP code:
.cblk
\ @(try)
 @(trow e "honda")
 @(catch e (car1 car2))
 @car1 @car2
 @(end)
.cble
.IP data:
.cblk
\ honda toyota
.cble
.IP result:
.cblk
\ car1="honda"
 car2="toyota"
.cble
.PP

A
.code throw
argument passing a value to a
.code catch
parameter which is unbound causes
that parameter to be bound to that value.

.code throw
arguments are evaluated in the context of the
.codn throw ,
and the bindings
which are available there. Consideration of what parameters are bound
is done in the context of the catch.
.IP code:
.cblk
\ @(bind c "c")
 @(try)
 @(forget c)
 @(bind (a c) ("a" "lc"))
 @(throw e a c)
 @(catch e (b a))
 @(end)
.cble
.IP result:
.cblk
\ c="c"
 b="a"
 a="lc"
.cble
.PP

In the above example,
.code c
has a toplevel binding to the string
.strn "c" ,
but then becomes unbound
via
.code forget
within the
.code try
construct, and rebound to the value
.strn lc .
Since the
.code try
construct is terminated by a
.codn throw ,
these modifications of the
binding environment are discarded. Hence, at the end of the query, variable
.code c
ends up bound to the original value
.strn c .
The
.code throw
still takes place
within the scope of the bindings set up by the
.code try
clause, so the values of
.code a
and
.code c
that are thrown are
.str a
and
.strn lc .
However, at the
.code catch
site, variable
.code a
does not have a binding.  At that point, the binding to
.str a
established in
the
.code try
has disappeared already. Being unbound, the
.code catch
parameter
.code a
can take
whatever value the corresponding throw argument provides, so it ends up with
.strn lc .

.dir defex

The
.code defex
directive allows the query writer to invent custom exception types,
which are arranged in a type hierarchy (meaning that some exception types are
considered subtypes of other types).

Subtyping means that if an exception type
.code B
is a subtype of
.codn A ,
then every
exception of type
.code B
is also considered to be of type
.codn A .
So a catch for type
.code A
will also catch exceptions of type
.codn B .
Every type is a supertype of itself: an
.code A
is a kind of
.codn A .
This of course implies that every type is a subtype of itself
also.  Furthermore, every type is a subtype of the type
.codn t ,
which has no
supertype other than itself. Type
.code nil
is is a subtype of every type, including
itself.  The subtyping relationship is transitive also. If
.code A
is a subtype
of
.codn B ,
and
.code B
is a subtype of
.codn C ,
then
.code A
is a subtype of
.codn C .

.code defex
may be invoked with no arguments, in which case it does nothing:

.cblk
  @(defex)
.cble

It may be invoked with one argument, which must be a symbol. This introduces a
new exception type. Strictly speaking, such an introduction is not necessary;
any symbol may be used as an exception type without being introduced by
.codn @(defex) :

.cblk
  @(defex a)
.cble

Therefore, this also does nothing, other than document the intent to use
a as an exception.

If two or more argument symbols are given, the symbols are all introduced as
types, engaged in a subtype-supertype relationship from left to right.
That is to say, the first (leftmost) symbol is a subtype of the next one,
which is a subtype of the next one and so on. The last symbol, if it
had not been already defined as a subtype of some type, becomes a
direct subtype of the master supertype
.codn t .
Example:

.cblk
  @(defex d e)
  @(defex a b c d)
.cble

The first directive defines
.code d
as a subtype of
.codn e ,
and
.code e
as a subtype of
.codn t .
The second defines
.code a
as a subtype of
.codn b ,
.code b
as a subtype of
.codn c ,
and
.code c
as a subtype of
.codn d ,
which is already defined as a subtype of
.codn e .
Thus
.code a
is now a subtype of
.codn e .
The the above can be condensed to:

.cblk
  @(defex a b c d e)
.cble

Example:
.IP code:
.cblk
\ @(defex gorilla ape primate)
 @(defex monkey primate)
 @(defex human primate)
 @(collect)
 @(try)
 @(skip)
 @(cases)
 gorilla @name
 @(throw gorilla name)
 @(or)
 monkey @name
 @(throw monkey name)
 @(or)
 human @name
 @(throw human name)
 @(end)@#cases
 @(catch primate (name))
 @kind @name
 @(output)
 we have a primate @name of kind @kind
 @(end)@#output
 @(end)@#try
 @(end)@#collect
.cble
.IP data:
.cblk
\ gorilla joe
 human bob
 monkey alice
.cble
.IP output:
.cblk
\ we have a primate joe of kind gorilla
 we have a primate bob of kind human
 we have a primate alice of kind monkey
.cble
.PP

Exception types have a pervasive scope. Once a type relationship is introduced,
it is visible everywhere. Moreover, the
.code defex
directive is destructive,
meaning that the supertype of a type can be redefined. This is necessary so
that something like the following works right:

.cblk
  @(defex gorilla ape)
  @(defex ape primate)
.cble

These directives are evaluated in sequence. So after the first one, the
.code ape
type has the type
.code t
as its immediate supertype.  But in the second directive,
.code ape
appears again, and is assigned the
.code primate
supertype, while retaining
.code gorilla
as a subtype.  This situation could be diagnosed as an
error, forcing the programmer to reorder the statements, but instead
\*(TX obliges. However, there are limitations.  It is an error to define a
subtype-supertype relationship between two types if they are already connected
by such a relationship, directly or transitively. So the following
definitions are in error:

.cblk
  @(defex a b)
  @(defex b c)
  @(defex a c)@# error: a is already a subtype of c, through b

  @(defex x y)
  @(defex y x)@# error: circularity; y is already a supertype of x.
.cble

.dir assert

The
.code assert
directive requires the remaining query or sub-query which follows it
to match. If the remainder fails to match, the assert directive throws an
exception. If the directive is simply

.cblk
  @(assert)
.cble

Then it throws an assertion of type assert, which is a subtype of error.
The assert directive also takes arguments similar to the throw
directive. The following assert directive, if it triggers, will throw
an exception of type
.codn foo ,
with arguments
.code 1
and
.strn 2 :

.cblk
  @(assert foo 1 "2")
.cble

Example:

.cblk
  @(collect)
  Important Header
  ----------------
  @(assert)
  Foo: @a, @b
  @(end)
.cble

Without the assertion in places, if the
.code "Foo: @a, @b"
part does not
match, then the entire interior of the
.code @(collect)
clause fails,
and the collect continues searching for another match.

With the assertion in place, if the text
.str "Important Header"
and its
underline match, then the remainder of the collect body must
match, otherwise an exception is thrown. Now the program will not
silently skip over any Important Header sections due to a problem
in its matching logic. This is particularly useful when the matching is varied
with numerous cases, and they must all be handled.

There is a horizontal
.code assert
directive also. For instance:

.cblk
  abc@(assert)d@x
.cble

asserts that if the prefix
.str abc
is matched, then it must be
followed by a successful match for
.strn "d@x" ,
or else an exception is thrown.

.SH* TXR LISP
The \*(TX language contains an embedded Lisp dialect called \*(TL.

This language is exposed in \*(TX in several ways.

Firstly, in any situation that calls for an expression, a Lisp 
expression can be used, if it is preceded by the
.code @
character. The Lisp expression
is evaluated and its value  becomes the value of that expression.
Thus, \*(TX directives are embedded in literal text using
.codn @ ,
and Lisp expressions
are embedded in directives using
.code @
also.

Secondly, certain directives evaluate Lisp expressions without
requiring
.codn @ .
These are
.codn @(do) ,
.codn @(require) ,
.codn @(assert) ,
.code @(if)
and
.codn @(next) .

Thirdly, \*(TL code can be placed into files. On the command
line, \*(TX treats files with a
.str ".tl"
suffix as \*(TL code, and the
.code @(load)
directive does also.

Lastly, \*(TL expressions can be evaluated via the
command line, using the
.code -e
and
.code -p
options.

.B
Examples:

Bind variable
.code a
to the integer 4:

.cblk
  @(bind a @(+ 2 2))
.cble

Bind variable
.code b
to the standard input stream. Note that
.code @
is not required on a Lisp variable:

.cblk
  @(bind a *stdin*)
.cble

Define several Lisp functions inside
.codn @(do) :

.cblk
  @(do
    (defun add (x y) (+ x y))

    (defun occurs (item list)
      (cond ((null list) nil)
            ((atom list) (eql item list))
            (t (or (eq (first list) item)
                   (occurs item (rest list)))))))
.cble

Trigger a failure unless previously bound variable
.code answer
is greater than 42:

.cblk
  @(require (> (int-str answer) 42)
.cble

.SS* Overview

\*(TL is a small and simple dialect, like Scheme, but much more similar to
Common Lisp than Scheme. It has separate value and function binding namespaces,
like Common Lisp (and thus is a Lisp-2 type dialect), and represents Boolean
.B true
and
.B false
with the symbols
.code t
and
.code nil
(note the case sensitivity of
identifiers denoting symbols!) Furthermore, the symbol
.code nil
is also the empty list, which terminates nonempty lists.

\*(TL has lexically scoped local variables and dynamic global variables,
similarly to Common Lisp, including the convention that
.code defvar
marks symbols for dynamic binding in local scopes. Lexical closures
are supported. \*(TL also supports global lexical variables via
.codn defvarl .

Functions are lexically scoped in \*(TL; they can be
defined in pervasive global environment using
.code defun
or in local scopes using
.code flet
and
.codn labels .

.SS* Additional Syntax

Much of the \*(TL syntax has been introduced in the previous sections of the
manual, since directive forms are based on it. There is some additional syntax
that is useful in \*(TL programming.

.NP* Symbol Tokens

The symbol tokens in \*(TL,
called a
.meta lident
(Lisp identifier) has a similar syntax to the
.meta bident
(braced identifier) in the \*(TX pattern language. It may consist of
all the same characters, as well as the
.code /
(slash) character which may not be used in a
.metn bident .
Thus a
.meta lident
may consist of these characters, in addition to letters and numbers:

.cblk
 ! $ % & * + - < = > ? \e _ ~ /
.cble

and of course, may not look like a number. A lone
.code /
is a symbol in \*(TL. The token
.code /abc/
is also a symbol, and not a regular expression, like it is in the braced
variable syntax. Within \*(TL, regular expressions are written with
a leading
.codn # .

.NP* Consing Dot

Unlike other major Lisp dialects, \*(TL allows a consing dot with no forms
preceding it. This construct simply denotes the form which follows the dot.
That is to say, the parser implements the following transformation:

.cblk
  (. expr) -> expr
.cble

This is convenient in writing function argument lists that only take
variable arguments. Instead of the syntax:

.cblk
  (defun fun args ...)
.cble

the following syntax can be used:

.cblk
  (defun fun (. args) ...)
.cble

When a
.code lambda
form is printed, it is printed in the following style.

.cblk
  (lambda nil ...) -> (lambda () ...)
  (lambda sym ...) -> (lambda (. sym) ...)
  (lambda (sym) ...) -> (lambda (sym) ...)
.cble

In no other circumstances is
.code nil
printed as
.codn () ,
or an atom
.code sym
as
.codn "(. sym)" .

.NP* Referencing Dot

A dot token which is flanked by expressions on both sides, without any
intervening whitespace, is the referencing dot, and not the consing dot.
The referencing dot is a syntactic sugar which translated to the
.code qref
syntax ("quoted ref"). This syntax denotes structure access;
see Structures.

.cblk
  ;; a.b may be almost any expressions
  a.b           <-->  (qref a b)
  a.b.c         <-->  (qref a b c)
  a.(qref b c)  <-->  (qref a b c)
  (qref a b).c  <-->  (qref (qref a b) c)
.cble

That is to say, this dot operator constructs a
.code qref
expression out of its left and right arguments. If the right argument
of the dot is already a qref expression (whether produced by another instance
of the dot operator, or expressed directly) it is merged. And the qref dot
operator is right-to-left associative, so that
.code a.b.c
first produces
.code "(qref b c)"
via the right dot, and then
.code a
is adjoined into the syntax via the right dot.

Integer tokens cannot be involved in this syntax, because they
form floating-point constants when juxtaposed with a dot.
Such ambiguous uses of floating-point tokens are diagnosed as syntax errors:

.cblk
  (a.4)   ;; error: cramped floating-point literal
  (a .4)  ;; good: a followed by 0.4
.cble


.NP* Quote and Quasiquote

.meIP >> ' expr

The quote character in front of an expression is used for suppressing evaluation,
which is useful for forms that evaluate to something other than themselves.
For instance if
.code "'(+ 2 2)"
is evaluated, the value is the three-element list
.codn "(+ 2 2)" ,
whereas if
.code "(+ 2 2)"
is evaluated, the value is
.codn 4 .
Similarly, the value of
.code 'a
is the symbol
.code a
itself, whereas the value of
.code a
is the contents of the variable
.codn a .

.meIP >> ^ qq-template

The caret in front of an expression is a quasiquote. A quasiquote is like
a quote, but with the possibility of substitution of material.

Under a quasiquote, form is considered to be a quasiquote template. The template
is considered to be a literal structure, except that it may contain
the notations
.cblk
.meti >> , expr
.cble
and
.cblk
.meti >> ,* expr
.cble
which denote non-constant parts.

A quasiquote gets translated into code which, when evaluated, constructs
the structure implied by
.metn qq-template ,
taking into account the unquotes and splices.

A quasiquote also processes nested quasiquotes specially.

If
.meta qq-template
does not contain any unquotes or splices (which match its
level of nesting), or is simply an atom, then
.cblk
.meti >> ^ qq-template
.cble
is equivalent to
.cblk
.meti >> ' qq-template .
.cble
in other words, it is like an ordinary quote.  For instance
.code "^(a b ^(c ,d))"
is equivalent to
.codn "'(a b ^(c ,d))" .
Although there is an unquote ,d it
belongs to the inner quasiquote
.codn "^(c ,d)" ,
and the outer quasiquote does not have
any unquotes of its own, making it equivalent to a quote.

Dialect note: in Common Lisp and Scheme,
.code ^form
is written
.codn `form ,
and
quasiquotes are also informally known as backquotes.  In \*(TX, the backquote
character
.code `
used for quasi string literals.

.meIP >> , expr

The comma character is used within a
.meta qq-template
to denote an unquote.  Whereas the quasiquote suppresses evaluation,
similarly to the quote, the comma introduces an exception: an element
of a form which is evaluated. For example, list
.code "^(a b c ,(+ 2 2) (+ 2 2))"
is the list
.codn "(a b c 4 (+ 2 2))" .
Everything
in the quasiquote stands for itself, except for the
.code ",(+ 2 2)"
which is evaluated.

Note: if a variable is called
.codn *x* ,
then the syntax
.code ,*x*
means
.codn ",* x*" :
splice
the value of
.codn x* .
In this situation, whitespace between the comma and the
variable name should be used:
.codn ", *x*" .

.meIP >> ,* expr

The comma-star operator is used within quasiquote list to denote a splicing
unquote.  The form which follows
.code ,*
must evaluate to a list. That list is spliced into
the structure which the quasiquote denotes. For example:
.code "'(a b c ,*(list (+ 3 3) (+ 4 4) d))"
evaluates to
.codn "(a b c 6 8 d)" .
The expression
.code "(list (+ 3 3) (+ 4 4))"
is evaluated to produce the list
.codn "(6 8)" ,
and this list is spliced into the quoted template.

Dialect note: in other Lisp dialects, the equivalent syntax is usually
.code ,@
(comma at). The
.code @
character already has an assigned meaning, so
.code *
is used.

.NP* Quasiquoting non-List Objects
Quasiquoting is supported over hash table and vector literals (see Vectors
and Hashes below).  A hash table or vector literal can be quoted, like any
object, for instance:

.cblk
  '#(1 2 3)
.cble

The
.code "#(1 2 3)"
literal is turned into a vector atom right in the \*(TX parser,
and this atom is being quoted: this is
.cblk
.meti (quote << atom )
.cble
syntactically, which evaluates to
.metn atom .

When a vector is quasi-quoted, this is a case of
.cblk
.meti >> ^ atom
.cble
which evaluates to
.metn atom .

A vector can be quasiquoted, for example:

.cblk
  ^#(1 2 3)
.cble

Of course, unquotes can occur within it.

.cblk
  (let ((a 42))
    ^#(1 ,a 3)) ; value is #(1 42 3)
.cble

In this situation, the
.code ^#(...)
notation produces code which constructs a vector.

The vector in the following example is also a quasivector. It contains
unquotes, and though the quasiquote is not directly applied to it,
it is embedded in a quasiquote:

.cblk
  (let ((a 42))
    ^(a b c #(d ,a))) ; value is (a b c #(d 42))
.cble

Hash table literals have two parts: the list of hash construction
arguments and the key-value pairs. For instance:

.cblk
   #H((:equal-based) (a 1) (b 2))
.cble

where
.code (:equal-based)
is the list of construction arguments and the pairs
.code "(a 1)"
and
.code "(b 2)"
are the key/value entries. Hash literals may be quasiquoted.  In
quasiquoting, the arguments and pairs are treated as separate syntax; it is not
one big list.  So the following is not a possible way to express the above
hash:

.cblk
  ;; not supported: splicing across the entire syntax
  (let ((hash-syntax '((:equal-based) (a 1) (b 2))))
    ^#H(,*hash-syntax))
.cble

This is correct:

.cblk
  ;; fine: splicing hash arguments and contents separately
  (let ((hash-args '(:equal-based))
        (hash-contents '((a 1) (b 2))))
    ^#H(,hash-args ,*hash-contents))
.cble

.NP* Quasiquoting combined with Quasiliterals
When a quasiliteral is embedded in a quasiquote, it is possible to use
splicing to insert material into the quasiliteral.

Example:

.cblk
  (eval (let ((a 3)) ^`abc @,a @{,a} @{(list 1 2 ,a)}`))

  -> "abc 3 3 1 2 3"
.cble

.NP* Vector Literals

.coIP "#(...)"

A hash token followed by a list denotes a vector. For example
.code "#(1 2 a)"
is a three-element vector containing the numbers
.code 1
and
.codn 2 ,
and the symbol
.codn a .

.NP* Struct Literals

.meIP >> #H( name >> { slot << value }*)

The notation
.code #S
followed by a nested list syntax denotes a struct literal.
The first item in the syntax is a symbol denoting the struct type
name. This must be the name of a struct type, otherwise the
literal is erroneous.  Followed by the struct type are slot names
interleaved with their values. Each slot name which is present in the
literal must name a slot in the struct type, though not
all slots in the struct type must be present in the literal.
When a struct literal is read, the denoted struct type is
constructed as if by a call to
.code make-struct
whose
.meta plist
argument is formed from the
.meta slot
and
.meta value
elements of the literal, individually quoted to suppress their
evaluation as forms.

.NP* Hash Literals

.meIP <> #H(( hash-argument *) >> ( key << value )*)

The notation
.code #H
followed by a nested list syntax denotes a hash table literal.
The first item in the syntax is a list of keywords. These are the same
keywords as are used when calling the function hash to construct
a hash table. Allowed keywords are:
.codn :equal-based ,
.code :weak-keys
and
.codn :weak-values .
An empty list can be specified as
.code nil
or
.codn () ,
which defaults to a
hash table based on the
.code eql
function, with no weak semantics.

.NP* Range Literals

.meIP >> #R( from << to )

The notation
.code #R
followed by a two-element list syntax denotes a range literal.

.coNP The @ .. notation
In \*(TL, there is a special "dotdot" notation consisting of a pair of dots.
This can be written between successive atoms or compound expressions, and is a
shorthand for
.codn rcons .

That is to say,
.code "A .. B"
translates to
.codn "(rcons A B)" ,
and so for instance
.code "(a b .. (c d) e .. f . g)"
means
.codn "(a (rcons b (c d)) (rcons e f) . g)" .

The
.code rcons
function constructs a range object, which denotes a pair of values.
Range objects are most commonly used for referencing subranges of
sequences.

For instance, if
.code L
is a list, then
.code "[L 1 .. 3]"
computes a sublist of
.code L
consisting of
elements 1 through 2 (counting from zero).

Note that if this notation is used in the dot position of an improper
list, the transformation still applies. That is, the syntax
.code "(a . b .. c)"
is valid and produces the object
.code "(a . (rcons b c))"
which is another way of writing
.codn "(a rcons b c)" ,
which is quite probably nonsense.

The notation's
.code ..
operator associates right to left, so that
.code a..b..c
denotes
.codn "(rcons a (rcons b c))" .

Note that range objects are not printed using the dotdot notation.
A range literal has the syntax of a two-element list, prefixed by
.codn #R .
(See Range Literals above).

In any context where the dotdot notation may be used, and where
it is evaluated to its value, a range literal may also be specified.
If an evaluated dotdot notation specifies two constant expressions, then
an equivalent range literal can replace it. For instance the
form
.code "[L 1 .. 3]"
can also be written
.codn "[L #R(1 3)]" .
The two are syntactically different, and so if these expressions are being
considered for their syntax rather than value, they are not the same.

.NP* The DWIM Brackets
\*(TL has a square bracket notation. The syntax
.code [...]
is a shorthand
way of writing
.codn "(dwim ...)" .
The
.code []
syntax is useful for situations
where the expressive style of a Lisp-1 dialect is useful.

For instance if
.code foo
is a variable which holds a function object, then
.code "[foo 3]"
can be used to call it, instead of
.codn "(call foo 3)" .
If foo is a vector, then
.code "[foo 3]"
retrieves the fourth element, like
.codn "(vecref foo 3)" .
Indexing over lists,
strings and hash tables is possible, and the notation is assignable.

Furthermore, any arguments enclosed in
.code []
which are symbols are treated
according to a modified namespace lookup rule.

More details are given in the documentation for the
.code dwim
operator.

.NP* Compound Forms
In \*(TL, there are two types of compound forms: the Lisp-2 style
compound forms, denoted by ordinary lists that are expressed with parentheses.
There are Lisp-1 style compound forms denoted by the DWIM Brackets, described
in the previous section.

The first position of an ordinary Lisp-2 style compound form, is expected to
have a function or operator name.  Then arguments follow. There may
also be an expression in the dotted position, if the form is a function call.

If the form is a function call then the arguments are evaluated. If any of the
arguments are symbols, they are treated according to Lisp-2 namespacing rules.

.NP* Dot Position in Function Calls

If there is an expression in the dotted position of a function call
expression, it is also evaluated, and the resulting value is involved in the
function call in a special way.

Firstly, note that a compound form cannot be used in the dot position,
for obvious reasons, namely that
.code "(a b c . (foo z))"
does not mean that there is
a compound form in the dot position, but denotes an alternate spelling for
.codn "(a b c foo z)" ,
where foo behaves as a variable. (There exists a special exception to this,
namely that the meta-numbers and meta-symbols of the
.code op
operator can be used in the dot position).

If the dot position of a compound form is an atom, then the behavior
may be understood according to the following transformations:

.cblk
  (f a b c ... . x)  -->  (apply (fun f) a b c ... x)
  [f a b c ... . x]  -->  [apply f a b c ... x]
.cble

Effectively, the dot notation constitutes a shorthand for
.codn apply .

Examples:

.cblk
  ;; a contains 3
  ;; b contains 4
  ;; c contains #(5 6 7)
  ;; s contains "xyz"

  (foo a b . c)  ;; calls (foo 3 4 5 6 7)
  (foo a)        ;; calls (foo 3)
  (foo . s)      ;; calls (foo #\ex #\ey #\ez)

  (list . a)     ;; yields 3
  (list a . b)   ;; yields (3 . 4)
  (list a . c)   ;; yields (3 5 6 7)
  (list* a c)    ;; yields (3 . #(5 6 7))

  (cons a . b)   ;; error: cons isn't variadic.
  (cons a b . c) ;; error: cons requires exactly two arguments.

  [foo a b . c]  ;; calls (foo 3 4 5 6 7)

  [c 1]          ;; indexes into vector #(5 6 7) to yield 6

  (call (op list 1 . @1) 2) ;; yields 2
.cble

Note that the atom in the dot position of a function call may
be a symbol macro. Since the semantics works as if by
transformation to an apply form in which the original dot
position atom is an ordinary argument, the symbol macro
may produce a compound form.

Thus:

.cblk
  (symacrolet ((x 2))
    (list 1 . x))  ;; yields (1 . 2)

  (symacrolet ((x (list 1 2)))
    (list 1 . x))  ;; (yields (1 . 3))
.cble

That is to say, the expansion of
.code x
is not substituted into the form
.code "(list 1 . x)"
but rather the transformation to
.code apply
syntax takes place first, and
so the substitution of
.code x
takes place in a form resembling
.codn "(apply (fun list) 1 x)" .

Dialect Note:

In some other Lisp dialects like ANSI Common Lisp, the improper list syntax may
not be used as a function call; a function called apply (or similar) must be
used for application even if the expression which gives the trailing arguments
is a symbol. Moreover, applying sequences other than lists is not supported.

.NP* Improper Lists as Macro Calls

\*(TL allows macros to be called using forms which are improper lists.
These forms are simply destructured by the usual macro parameter list
destructuring. To be callable this way, the macro must have an argument
list which specifies a parameter match in the dot position. This dot position
must either match the terminating atom of the improper list form,
or else match the trailing portion of the improper list form.

For instance if a macro mac is defined as

.cblk
  (defmacro mac (a b . c) ...)
.cble

then it may not be invoked as
.code "(mac 1 . 2)"
because the required argument
.code b
is not satisfied, and so the
.code 2
argument cannot match the dot position
.code c
as required. The macro may be called as
.code "(mac 1 2 . 3)"
in which case
.code c
receives the form
.codn 3 .
If it is called as
.code "(mac 1 2 3 . 4)"
then
.code c
receives the improper list form
.codn "3 . 4" .

.NP* Regular Expression Literals
In \*(TL, the
.code /
character can occur in symbol names, and the
.code /
token
is a symbol. Therefore the
.code /regex/
syntax is not used for denoting regular expressions; rather, the
.code #/regex/
syntax is used.

.coSS Generalization of List Accessors
In ancient Lisp in the 1960's, it was not possible to apply the operations
.code car
and
.code cdr
to the
.code nil
symbol (empty list), because it is not a
.code cons
cell. In
the InterLisp dialect, this restriction was lifted: these operations were
extended to accept
.code nil
(and return
.codn nil ).
The convention was adopted in
other Lisp dialects such as MacLisp and eventually in Common Lisp. Thus there
exists an object which is not a cons, yet which takes
.code car
and
.codn cdr .

In \*(TL, this relaxation is extended further. For the sake of convenience,
the operations
.code car
and
.codn cdr ,
are made to work with strings and vectors:

.cblk
  (cdr "") -> nil
  (car "") -> nil

  (car "abc") -> #\ea
  (cdr "abc") -> "bc"

  (cdr #(1 2 3)) -> #(2 3)
  (car #(1 2 3)) -> 1
.cble

The
.code ldiff
function is also extended in a special way. When the right parameter
is a string or vector, then it uses the equal equality test rather than eq
for detecting the tail of the list.

.cblk
  (ldiff "abcd" "cd") -> (#\ea #\eb)
.cble

The
.code ldiff
operation starts with
.str "abcd"
and repeatedly applies
.code cdr
to produce
.str "bcd"
and
.strn "cd" ,
until the suffix is equal to the second argument:
.cblk
(equal "cd" "cd")
.cble
yields true.

Operations based on
.codn car ,
.code cdr
and
.codn ldiff ,
such as
.code keep-if
and
.code remq
extend to
strings and vectors.

Most derived list processing operations such as
.code remq
or
.code mapcar
obey the following
rule: the returned object follows the type of the leftmost input list object.
For instance, if one or more sequences are processed by
.codn mapcar ,
and the
leftmost one is a character string, the function is expected to return
characters, which are converted to a character string. However, in the
event that the objects produced cannot be assembled into that type of
sequence, a list is returned instead.

For example
.cblk
[mapcar list "ab" "12"]
.cble
returns
.codn "((#\ea #\eb) (#\e1 #\e2))" ,
because a string cannot hold lists of characters. However
.cblk
[mappend list "ab" "12"]
.cble
returns
.strn "a1b2" .

The lazy versions of these functions such as
.code mapcar*
do not have this behavior;
they produce lazy lists.

.SS* Callable Objects

In \*(TL, sequences (strings, vectors and lists) and hashes can be used
as functions everywhere, not just with the DWIM brackets. Sequences work
as one or two-argument functions. With a single argument, an element is
selected by position and returned. With two arguments, a range is extracted and
returned. Hashes also work as one or two argument functions, corresponding
to the arguments of the gethash function.

Moreover, when a sequence is used as a function of one argument, and the
argument is a range object rather than an integer, then the call is equivalent
to the two-argument form.  This is the basis for array slice syntax like
.cblk
["abc" 0..1] .
.cble

.B Example 1:

.cblk
  (mapcar "abc" '(2 0 1)) -> (#\ec #\ea #\eb)
.cble

Here,
.code mapcar
treats the string
.str abc
as a function of one argument (since there
is one list argument). This function maps the indices
.codn 0 ,
.code 1
and
.code 2
to the
corresponding characters of string
.strn abc .
Through this function, the list of integer indices
.code "(2 0 1)"
is taken to the list of characters
.codn "(#\ec #\ea #\eb)" .

.B Example 2:

.cblk
  (call '(1 2 3 4) 1..3) -> (2 3)
.cble

Here, the shorthand
.code "1 .. 3"
denotes
.codn "(rcons 1 3)" .
A range used as an argument
to a sequence performs range extraction: taking a slice starting at
index 1, up to and not including index 3, as if by the call
.codn "(sub '(1 2 3 4) 1 3)" .

.B Example 3:

.cblk
  (call '(1 2 3 4) '(0 2)) -> (1 2)
.cble

A list of indices applied to a sequence is equivalent to using the
select function, as if
.code "(select '(1 2 3 4) '(0 2))"
were called.

.SS* Special Variables
Similarly to Common Lisp, \*(TL is lexically scoped by default, but
also has dynamically scoped (a.k.a "special") variables.

When a variable is defined with
.code defvar
or
.codn defparm ,
a binding for the symbol is
introduced in the global name space, regardless of in what scope the
.code defvar
form occurs.

Furthermore, at the time the defvar form is evaluated, the symbol which
names the variable is tagged as special.

When a symbol is tagged as special, it behaves differently when it is used
in a lexical binding construct like
.codn let ,
and all other such constructs
such as function parameter lists. Such a binding is not the usual lexical
binding, but a "rebinding" of the global variable. Over the dynamic scope
of the form, the global variable takes on the value given to it by the
rebinding. When the form terminates, the prior value of the variable
is restored. (This is true no matter how the form terminates; even if by
an exception.)

Because of this "pervasive special" behavior of a symbol that has been
used as the name of a global variable, a good practice is to make global
variables have visually distinct names via the "earmuffs" convention:
beginning and ending the name with an asterisk.

.TP* "Example:"

.cblk
  (defvar *x* 42)     ;; *x* has a value of 42

  (defun print-x ()
    (format t "~a\en" *x*))

  (let ((*x* "abc"))  ;; this overrides *x*
    (print-x))        ;; *x* is now "abc" and so that is printed

  (print-x)           ;; *x* is 42 again and so "42" is printed
.cble

.TP* "Dialect Note 1:"

The terms
.I bind
and
.I binding
are used differently in \*(TL compared to ANSI Common Lisp.
In \*(TL binding is an association between a symbol and an abstract storage
location. The association is registered in some namespace, such as the global
namespace or a lexical scope.  That storage location, in turn, contains a
value. In ANSI Lisp, a binding of a dynamic variable is the association between
the symbol and a value.  It is possible for a dynamic variable to exist, and
not have a value.  A value can be assigned, which creates a binding.
In \*(TL, an assignment is an operation which transfers a value into
a binding, not one which creates a binding.

In ANSI Lisp, a dynamic variable can exist which has no value. Accessing
the value signals a condition, but storing a value is permitted; doing so
creates a binding. By contrast, in \*(TL a global variable cannot exist without
a value. If a
.code defvar
form doesn't specify a value, and the variable doesn't exist, it is
created with a value of
.codn nil .

.TP* "Dialect Note 2:"

Unlike ANSI Common Lisp, \*(TL has global lexical variables in addition to
special variables. These are defined using
.code defvarl
and
.codn defparml .
The only difference is that when variables are introduced by these macros,
the symbols are not marked special, so their binding in lexical scopes
is not altered to dynamic binding.

Many variables in \*(TL's standard library are global lexicals.
Those which are special variables obey the "earmuffs" convention
in their naming. For instance
.codn s-ifmt ,
.code log-emerg
and
.code sig-hup
are global lexicals, because they provide constant values
for which overriding doesn't make sense. On the other hand the standard
output stream variable
.code *stdout*
is special. Overriding it over a dynamic scope is very useful.

.TP* "Dialect Note 3:"

In Common Lisp,
.code defparm
is known as
.codn defparameter .

.SS* Syntactic Places and Accessors

The \*(TL feature known as
.I syntactic places
allows programs to use
the syntax of a form which is used to
.I access
a value from an environment or
object, as an expression which denotes a
.I place
where a value may be
.I stored.

They are almost exactly the
same concept as "generalized references" in Common Lisp, and are related to
"lvalues" in languages in the C family, or "designators" in Pascal.

.NP* Symbolic Places

A symbol is a is a syntactic place if it names a variable. If
.code a
is a variable, then it may be assigned using the
.code set
operator: the form
.code "(set a 42)"
causes
.code a
to have the integer value 42.

.NP* Compound Places

A compound expression can be a syntactic place, if its leftmost constituent is
as symbol which is specially registered, and if the form has the correct syntax
for that kind of place, and suitable semantics. Such an expression is a compound
place.

An example of a compound place is a
.code car
form. If
.code c
is an expression denoting a
.code cons
cell, then
.code "(car c)"
is not only an expression which retrieves the value of the
.code car
field of the cell. It is also a syntactic place which denotes that field as
a storage location. Consequently, the expression
.cblk
(set (car c) "abc")
.cble
stores the character string
.str "abc"
in that location.  Although the same effect can be obtained with
.cblk
(rplaca c "abc")
.cble
the syntactic place frees the programmer from having to remember
different update functions for different kinds of places.
There are
various other advantages. \*(TL provides a plethora of operators
for modifying a place in addition to
.codn set .
Subject to certain usage restrictions, these operators work uniformly on all
places. For instance, the expression
.code "(rotate (car x) [str 3] y)"
causes three different kinds of places to exchange contents,
while the three expressions denoting those places
are evaluated only once. New kinds of place update macros like
.code rotate
are quite easily defined, as are new kinds of compound places.

.NP* Accessor Functions

When a function call form such as the above
.code "(car x)"
is a syntactic place, then the function is called an
.IR accessor .
This term is used throughout this document to denote functions
which have associated syntactic places.

.NP* Macro Call Syntactic Places

Syntactic places can be macros (global and lexical), including symbol macros.
So for instance in
.code "(set x 42)"
the
.code x
place can actually be a symbolic macro which expands to, say,
.codn "(cdr y)" .
This means that the assignment is effectively
.codn "(set (cdr y) 42)" .

.NP* User-Defined Syntactic Places and Place Operators

Syntactic places, as well as operators upon syntactic places,
are both open-ended. Code can be written quite easily in \*(TL to introduce
new kinds of places, as well as new place-mutating operators.
New places can be introduced with the help of the
.code defplace
macro, or possibly the
.code define-place-macro
macro in simple cases when a new syntactic place can be expressed as a
transformation to the syntax of an existing place.
Three ways exist for developing new place update macros (place operators).
They can be written using the ordinary macro definer
ordinary macro definer
.codn defmacro ,
with the help of special utility macros called
.codn with-update-expander ,
.codn with-clobber-expander ,
and
.codn with-delete-expander .
They can also be written using
.code defmacro
in conjunction with the operators
.code placelet
or
.codn placelet* .
Simple update macros similar to
.code inc
and
.code push
can be written compactly using
.codn define-modify-macro .

.NP* Deletable Places

Unlike generalized references in Common Lisp, \*(TL syntactic
places support the concept of deletion. Some kinds of places
can be deleted, which is an action distinct from (but does not preclude) being
overwritten with a value. What exactly it means for a place to be deleted,
or whether that is even permitted, depends on the kind of place.
For instance a place which denotes a lexical variable may not be deleted,
whereas a global variable may be.
A place which denotes a hash table entry may be deleted, and results in the
entry being removed from the hash table. Deleting a place in a list
causes the trailing items, if any, or else the terminating atom, to
move in to close the gap. Users may, of course, define new kinds of places
which support deletion semantics.

.NP* Evaluation of Places

To bring about their effect, place operators must evaluate one or
more places. Moreover, some of them evaluate additional forms which are not
places. Which arguments of a place operator form are places and which are
ordinary forms depends on its specific syntax. For all the built-in place
operators, the position of an argument in the syntax determines whether it is
treated as (and consequently required to be) a syntactic place, or whether it is
an ordinary form.

All built-in place operators perform the evaluation of place and non-place
argument forms in strict left to right order.

Place forms are evaluated not in order to compute a value, but in order to
determine the storage location.  In addition to determining a storage location,
the evaluation of a place form may possibly give rise to side effects.
Once a place is fully evaluated, the storage location can then be accessed.
Access to the storage location is not considered part of the evaluation of a
place.  To determine a storage location means to compute some hidden referential
object which provides subsequent access to that location without the need for a
re-evaluation of the original place form.  (The subsequent access to the
place through this referential object may still require a multi-step traversal
of a data structure; minimizing such steps is a matter of optimization.)

Place forms may themselves be compounds, which contain subexpressions that must
be evaluated. All such evaluation for the built-in places takes place in left
to right order.

Certain place operators, such as
.code shift
and
.codn rotate ,
exhibit an unspecified behavior with regard to the timing of the access
of the prior value of a place, relative to the evaluation of places
which occur later in the same place operator form. Access to the prior values
may be delayed until the entire form is evaluated, or it may be interleaved
into the evaluation of the form. For example, in the form
.codn "(shift a b c 1)" ,
the prior value of
.code a
can be accessed and saved as soon as
.code a
is evaluated, prior to the evaluation of
.codn b .
Alternatively,
.code a
may be accessed and saved later, after the evaluation of
.code b
or after the evaluation of all the forms.  This issue affects the behavior of
place-modifying forms whose subforms contain side effects. It is recommended
that such forms not be used in programs.

.NP* Nested Places

Certain place forms are required to have one or more arguments which
are themselves places. The prime example of this, and the only example from
among built-in syntactic places, are DWIM forms. A DWIM form has the syntax

.cblk
.mets (dwim < obj-place < index <> [ alt ])
.cble

and of course the square-bracket-notation equivalent:

.cblk
.mets >> [ obj-place < index <> [ alt ]]
.cble

Note that not only is the entire form a place, denoting some element or element
range of
.metn obj-place ,
but there is the added constraint that
.meta obj-place
must also itself be a syntactic place.

This requirement is necessary, because it supports the behavior that
when the element or element range is updated, then
.meta obj-place
is also potentially updated.

After the assignment
.cblk
(set [obj 0..3] '("forty" "two"))
.cble
not only is the range of places denoted by
.code "[obj 0..3]"
replaced by the list of strings
.cblk
("forty" "two")
.cble
but
.code obj
may also be overwritten with a new value.

This behavior is necessary because the DWIM brackets notation maintains
the illusion of an encapsulated array-like container over several dis-similar
types, including Lisp lists.  But Lisp lists do not behave as fully
encapsulated containers.  Some mutations on Lisp lists return new objects,
which then have to stored (or otherwise accepted) in place of the original
objects in order to maintain the array-like container illusion.

.NP* Built-In Syntactic Places

The following is a summary of the built-in place forms, in addition to symbolic
places denoting variables. Of course, new syntactic place forms can be
defined by \*(TX programs.

.cblk
.mets (car << object )
.mets (first << object )
.mets (rest << object )
.mets (second << object )
.mets (third << object )
.mets ...
.mets (tenth << object )
.mets (cdr << object )
.mets (caar << object )
.mets (cadr << object )
.mets (cdar << object )
.mets (cddr << object )
.mets ...
.mets (cdddddr << object )
.mets (nthcdr < index << list )
.mets (rest << object )
.mets (vecref < vec << idx )
.mets (chr-str < str << idx )
.mets (gethash < hash < key <> [ alt ])
.mets (dwim < obj-place < index <> [ alt ])
.mets >> [ obj-place < index <> [ alt ]] ;; equivalent to dwim
.mets (symbol-value << symbol-valued-form )
.mets (symbol-function << symbol-valued-form )
.mets (symbol-macro << symbol-valued-form )
.mets (fun << function-name )
.mets (force << promise )
.mets (errno)
.cble

.NP* Built-In Place-Mutating Operators

The following is a summary of the built-in place mutating macros.
They are described in detail in their own sections.

.meIP (set >> { place << new-value }*)
Assigns the values of expressions to places, performing assignments in left to right order,
returning the value assigned to the rightmost place.

.meIP (pset >> { place << new-value }*)
Assigns the values of expressions to places, performing the determination of
places and evaluation of the expressions left to right, but the assignment
in parallel. Returns the value assigned to the rightmost place.

.meIP (zap < place <> [ new-value ])
Assigns
.meta new-value
to place, defaulting to
.codn nil ,
and returns the prior value.

.meIP (flip << place )
Logically toggles the Boolean value of
.metn place ,
and returns the new value.

.meIP (inc < place <> [ delta ])
Increments
.meta place
by
.metn delta ,
which defaults to 1, and returns the new value.

.meIP (dec < place <> [ delta ])
Decrements
.meta place
by
.metn delta ,
which defaults to 1, and returns the new value.

.meIP (swap < left-place << right-place )
Exchanges the values of
.meta left-place
and
.metn right-place .

.meIP (push < item << place )
Pushes
.meta item
into the list stored in
.code place
and returns
.codn item .

.meIP (pop << place )
Pop the list stored in
.meta place
and returns the popped value.

.meIP (shift << place + << shift-in-value)
Treats one or more places as a "multi-place shift register".
Values are shifted to the left among the places. The
rightmost place receives
.metn shift-in-value ,
and the value of the leftmost place emerges as the return value.

.meIP (rotate << place *)
Treats zero or more places as a "multi-place rotate register".
The places exchange values among themselves, by a rotation
by one place to the left. The value of the leftmost place
goes to the rightmost place, and that value is returned.

.meIP (del << place )
Deletes a place which supports deletion, and returns
the value which existed in that place prior to deletion.

.PP

.SS* Namespaces and Environments

\*(TL is a Lisp-2 dialect: it features separate namespaces for
functions and variables.

.NP* Global Functions and Operator Macros

In \*(TL, global functions and operator macros co-exist, meaning that the same
symbol can be defined as both a macro and a function.

There is a global namespace for functions,
into which functions can be introduced with the
.code defun
macro.  The global function environment can be inspected and modified using the
.code symbol-function
accessor.

There is a global namespace for macros, into which
macros are introduced with the
.code defmacro
macro. The global function environment can be inspected and modified using the
.code symbol-macro
accessor.

If a name
.code x
is defined as both a function and a macro, then an expression of the form
.code "(x ...)"
is expanded by the macro, whereas an expression of the form
.code "[x ...]"
refers to the function. Moreover, the macro can produce a call to the
function.  The expression
.code "(fun x)"
will retrieve the function object.

.NP* Global and Dynamic Variables

There is a global namespace for variables also.
The operators
.code defvar
and
.code defparm
introduce bindings into this namespace. These operators have the
side effect of marking a symbol as a special variable,
of the symbol are treated as dynamic variables, subject to
rebinding.  The global variable namespace together with the special dynamic
rebinding is called the dynamic environment.
The dynamic environment can be inspected and modified using the
.code symbol-value
accessor.

The operators
.code defvarl
and
.code defparml
introduce bindings into the global namespace without marking
symbols as special variables. Such bindings are called global lexical
variables.

.NP* Global Symbol Macros

Symbol macros may be defined over the global variable namespace
using
.codn defsymacro .

.NP* Lexical Environments

In addition to global and dynamic namespaces, \*(TL provides lexically scoped
binding for functions, variables, macros, and symbol macros.
Lexical variable binding are introduced with
.codn let ,
.code let*
or various binding macros derived from these. Lexical functions are bound
with
.code flet
and
.codn labels .
Lexical macros are established with
.code macrolet
and lexical symbol macros with
.codn symacrolet .

Macros receive an environment parameter with which they may expand
forms in their correct environment, and perform some limited introspection
over that environment in order to determine the nature of bindings,
or the classification of forms in those environments. This introspection
is provided by
.codn lexical-var-p ,
.codn lexical-fun-p ,
and
.codn lexical-lisp1-binding .

Lexical operator macros and lexical functions can also co-exist in the
following way.  A lexical function shadows a global or lexical macro
completely. However, the reverse is not the case. A lexical macro shadows
only those uses of a function which look like macro calls. This is
succinctly demonstrated by the following form:

.cblk
  (flet ((foo () 43))
    (macrolet ((foo () 44))
      (list (fun foo) (foo) [foo])))

  -> (#<interpreted fun: lambda nil> 44 43)
.cble

The
.code "(fun foo)"
and
.code [fun]
expressions are oblivious to the macro; the macro expansion process
process the symbol
.code foo
in those contexts. However the form
.code (foo)
is subject to macro-expansion and replaced with
.codn 44 .

If the
.code flet
and
.code macrolet
are reversed, the behavior is different:

.cblk
  (macrolet ((foo () 44))
    (flet ((foo () 43))
      (list (fun foo) (foo) [foo])))

  -> (#<interpreted fun: lambda nil> 43 43)
.cble

All three forms refer to the function, which lexically shadows the macro.

.NP* Pattern Language and Lisp Scope Nesting

\*(TL expressions can be embedded in the \*(TX pattern language in various
ways. Likewise, the pattern language can be invoked from \*(TL. This
brings about the possibility that Lisp code attempts to access
pattern variables bound in the pattern language. The \*(TX pattern language
can also attempt to access \*(TL variables.

The rules are as follows, but they have undergone historic changes.  See the
COMPATIBILITY section, in particular notes under 138 and 121, and also 124.

A Lisp expression evaluated from the \*(TX pattern language executes
in a null lexical environment. The current set of pattern variables captured
up to that point by the pattern language are installed as dynamic variables.
They shadow any Lisp global variables (whether those are defined
by
.code defvar
or
.codn defvarl ).

In the reverse direction, a variable reference from the \*(TX pattern
language searches the pattern variable space first. If a variable doesn't
exist there, then the lookup refers to the \*(TL global variable space.
The pattern language doesn't see Lisp lexical variables.

When Lisp code is evaluated from the pattern language, the pattern variable
bindings are not only installed as dynamic variables for the sake of their
visibility from Lisp, but they are also specially stored in a dynamic
environment frame.  When \*(TX pattern code is re-entered from Lisp, these
bindings are picked up from the closest such environment frame, allowing the
nested invocation of pattern code to continue with the bindings captured by
outer pattern code.

Concisely, in any context in which a symbol has both a binding as a Lisp global
variable as well as a pattern variable, that symbol refers to the pattern
variable. Pattern variables are propagated through Lisp evaluation into
nested invocations of the pattern language.

The pattern language can also reference
Lisp variables using the
.code @
prefix, which is a consequence of that prefix introducing an expression that is
evaluated as Lisp, the name of a variable being such an expression.

.SH* LISP OPERATOR, FUNCTION AND MACRO REFERENCE

.SS* Conventions
The following sections list all of the special operators, macros
and functions in \*(TL.

In these sections Syntax is indicated using these conventions:

.meIP < word
.ie n \{\
A symbol in angle brackets
.\}
.el \{\
A symbol in
.meta fixed-width-italic
font
.\}
denotes some syntactic unit: it
may be a symbol or compound form. The syntactic unit is explained
in the corresponding Description section.

.meIP {syntax}* << word *
This indicates a repetition of zero or more of the given
syntax enclosed in the braces or syntactic unit.
The curly braces may be omitted if the scope of the
.code *
is clear.

.meIP {syntax}+ << word +
This indicates a repetition of one or more of the given
syntax enclosed in the braces or syntactic unit.
The curly braces may be omitted if the scope of the
.code +
is clear.

.coIP {syntax | syntax | ...}
This indicates a choice among alternatives.
May be combined with
.code +
or
.code *
repetition.

.meIP [syntax] <> [ word ]
Square brackets indicate optional syntax.

.meIP syntax -> < result
The arrow notation is used in examples to indicate that the evaluation
of the given syntax produces a value, whose printed representation is
.metn result .

.SS* Form Evaluation
A compound expression with a symbol as its first element, if
intended to be evaluated, denotes either an operator invocation or a function
call. This depends on whether the symbol names an operator or a function.

When the form is an operator invocation, the interpretation of the meaning of
that form is under the complete control of that operator.

If the compound form is a function call, the remaining forms, if any, denote
argument expressions to the function.  They are evaluated in left to right
order to produce the argument values, which are passed to the function.  An
exception is thrown if there are not enough arguments, or too many.  Programs
can define named functions with the defun operator

Some operators are macros. There exist predefined macros in the library, and
macro operators can also be user-defined using the macro-defining operator
.codn defmacro .
Operators that are not macros are called special operators.

Macro operators work as functions which are given the source code of the form.
They analyze the form, and translate it to another form which is substituted in
their place.   This happens during a code walking phase called the expansion
phase, which is applied to each top-level expression prior to evaluation. All
macros occurring in a form are expanded in the expansion phase, and subsequent
evaluation takes place on a structure which is devoid of macros. All that
remains are the executable forms of special operators, function calls,
symbols denoting either variables or themselves, and atoms such as numeric
and string literals.

Special operators can also perform code transformations during the expansion
phase, but that is not considered macroexpansion, but rather an adjustment
of the representation of the operator into an required executable form.
In effect, it is post-macro compilation phase.

Note that Lisp forms occurring in \*(TX pattern language are not individual
top-level forms. Rather, the entire \*(TX query is parsed at the same time, and
the macros occurring in its Lisp forms are expanded at that time.

.coNP Operator @ quote
.synb
.mets (quote << form )
.syne
.desc
The
.code quote
operator, when evaluated, suppresses the evaluation of
.metn form ,
and instead returns
.meta form
itself as an object. For example, if
.meta form
is a symbol, then
.meta form
is not evaluated to the symbol's value; rather
the symbol itself is returned.

Note: the quote syntax
.cblk
.meti >> ' <form>
.cble
is translated to
.cblk
.meti (quote << form ).
.cble

.TP* Example:

.cblk
  ;; yields symbol a itself, not value of variable a
  (quote a) -> a

  ;; yields three-element list (+ 2 2), not 4.
  (quote (+ 2 2)) -> (+ 2 2)
.cble


.SS* Variable Binding

Variables are associations between symbols and storage locations
which hold values. These associations are called
.IR bindings .

Bindings are held in a context called an
.IR environment .

.I Lexical
environments hold local variables, and nest according to the syntactic
structure of the program. Lexical bindings are always introduced by a
some form known as a
.I "binding construct",
and the corresponding environment is instantiated during the evaluation
of that construct. There also exist bindings outside of any binding
construct, in the so-called
.I global environment .
Bindings in the global environment can be temporarily shadowed by
lexically-established binding in the
.I dynamic environment .
See the Special Variables section above.

Certain special symbols cannot be used as variable names, namely the
symbols
.code t
and
.codn nil ,
and all of the keyword symbols (symbols in the keyword package), which are
denoted by a leading colon. When any of these symbols is evaluated as
a form, the resulting value is that symbol itself. It is said that these
special symbols are self-evaluating or self-quoting, similarly to all
other atom objects such as numbers or strings.

When a form consisting of a symbol, other than the above special symbols, is
evaluated, it is treated as a variable, and yields the value of
the variable's storage location. If the variable doesn't exist,
an exception is thrown.

Note: symbol forms may also denote invocations of symbol macros. (See the
operators
.code defsymacro
and
.codn symacrolet ).
All macros, including symbol macros, which occur inside
a form are fully expanded prior to the evaluation of a form, therefore
evaluation does not consider the possibility of a symbol being
a symbol macro.

.coNP Operator @ defvar and macro @ defparm
.synb
.mets (defvar < sym <> [ value ])
.mets (defparm < sym << value )
.syne
.desc
The
.code defvar
operator binds a name in the variable namespace of the global environment.
Binding a name means creating a binding: recording, in some namespace of some
environment, an association between a name and some named entity. In the
case of a variable binding, that entity is a storage location for a value.
The value of a variable is that which has most recently been written into the
storage location, and is also said to be a value of the binding, or stored
in the binding.

If the variable named
.meta sym
already exists in the global environment, the
form has no effect; the
.meta value
form is not evaluated, and the value of the
variable is unchanged.

If the variable does not exist, then a new binding is introduced, with a value
given by evaluating the
.meta value
form. If the form is absent, the variable is initialized
to
.codn nil .

The
.meta value
form is evaluated in the environment
in which the
.code defvar
form occurs, not necessarily in the global environment.

The symbols
.code t
and
.code nil
may not be used as variables, and neither
can be keyword symbols: symbols denoted by a leading colon.

In addition to creating a binding, the
.code defvar
operator also marks
.meta sym
as the name of a special variable. This changes what it means to bind
that symbol in a lexical binding construct such as the
.code let
operator, or a function parameter list. See the section "Special Variables" far
above.

The
.code defparm
macro behaves like
.code defvar
when a variable named
.meta sym
doesn't already exist.

If
.meta sym
already denotes a variable binding in the global namespace,
.code defparm
evaluates the
.meta value
form and assigns the resulting value to the variable.

The following equivalence holds:

.cblk
  (defparm x y)  <-->  (prog1 (defvar x) (set x y))
.cble

The
.code defvar
and
.code defparm
forms return
.metn sym .

.coNP Macros @ defvarl and @ defparml
.synb
.mets (defvarl < sym <> [ value ])
.mets (defparml < sym << value )
.syne
.desc
The
.code defvarl
and
.code defparml
macros behave, respectively, almost exactly like
.code defvar
and
.codn defparm .

The difference is that these operators do not mark
.meta sym
as special.

If a global variable
.meta sym
does not previously exist, then after the evaluation of
either of these forms
.cblk
.meti (boundp << sym )
.cble
is true, but
.cblk
.meti (special-var-p << sym )
.cble
isn't.

If
.meta sym
had been already introduced as a special variable, it stays that way
after the evaluation of
.code defvarl
or
.codn defparml .

.coNP Operators @ let and @ let*
.synb
.mets (let >> ({ sym | >> ( sym << init-form )}*) << body-form *)
.mets (let* >> ({ sym | >> ( sym << init-form )}*) << body-form *)
.syne
.desc
The
.code let
and
.code let*
operators introduce a new scope with variables and
evaluate forms in that scope. The operator symbol, either
.code let
or
.codn let* ,
is followed by a list which can contain any mixture of variable
name symbols, or
.cblk
.meti >> ( sym << init-form )
.cble
pairs.  A symbol
denotes the name of variable to be instantiated and initialized
to the value
.codn nil .
A symbol specified with an init-form denotes
a variable which is initialized from the value of the
.metn init-form .

The symbols
.code t
and
.code nil
may not be used as variables, and neither
can be keyword symbols: symbols denoted by a leading colon.

The difference between
.code let
and
.code let*
is that in
.codn let* ,
later
.codn init-form -s
have visibility over the variables established by earlier variables
in the same let* construct. In plain
.codn let ,
the variables are not visible to any of the
.metn init-form -s.

When the variables are established, then the
.metn body-form -s
are evaluated in order. The value of the last
.meta body-form
becomes the return value of the
.codn let .

If there are no
.metn body-form -s,
then the return value
.code nil
is produced.

The list of variables may be empty.

.TP* Examples:
.cblk
  (let ((a 1) (b 2)) (list a b)) -> (1 2)
  (let* ((a 1) (b (+ a 1))) (list a b (+ a b))) -> (1 2 3)
  (let ()) -> nil
  (let (:a nil)) -> error, :a and nil can't be used as variables
.cble

.SS* Functions
.coNP Operator @ defun
.synb
.mets (defun < name <> ( param * [: << opt-param *] [. << rest-param ])
.mets \ \  << body-form )
.syne
.desc
The
.code defun
operator introduces a new function in the global function namespace.
The function is similar to a lambda, and has the same parameter syntax
and semantics as the
.code lambda
operator.

Unlike in
.codn lambda ,
the
.metn body-form -s
of a
.code defun
are surrounded by a block.
The name of this block is the same as the name of the function, making it
possible to terminate the function and return a value using
.cblk
.meti (return-from < name << value ).
.cble
For more information, see the definition of the block operator.

A function may call itself by name, allowing for recursion.

The special symbols
.code t
and
.code nil
may not be used as function names. Neither can keyword symbols.

It is possible to define methods with
.codn defun ,
as an alternative to the
.code defmeth
macro.

To define a method, the syntax
.cblk
.meti (meth < type << name )
.cble
should be used as the argument to the
.meta name
parameter.

The syntax
.cblk
.meti (defun (meth type name) args forms)
.cble
is equivalent to the
.cblk
.meti (defmeth type name args forms)
.cble
syntax.

.TP* "Dialect Note:"
In ANSI Common Lisp, keywords may be used as function names.
In TXR Lisp, they may not.

.TP* "Dialect Note:"
A function defined by
.code defun
may co-exist with a macro defined by
.codn defmacro .
This is not permitted in ANSI Common Lisp.

.coNP Operator @ lambda
.synb
.mets (lambda <> ( param * [: << opt-param *] [. << rest-param ])
.mets \ \  << body-form )
.mets (lambda < rest-param
.mets \ \  << body-form )
.syne
.desc
The
.code lambda
operator produces a value which is a function.  Like in most other
Lisps, functions are objects in \*(TL.  They can be passed to functions as
arguments, returned from functions, aggregated into lists, stored in variables,
et cetera.

The first argument of
.code lambda
is the list of parameters for the function.   It
may be empty, and it may also be an improper list (dot notation) where the
terminating atom is a symbol other than
.codn nil .
It can also be a single symbol.

The second and subsequent arguments are the forms making up the function body.
The body may be empty.

When a function is called, the parameters are instantiated as variables that
are visible to the body forms. The variables are initialized from the values of
the argument expressions appearing in the function call.

The dotted notation can be used to write a function that accepts
a variable number of arguments. There are two ways write a function that
accepts only a variable argument list and no required arguments:

.cblk
.mets (lambda (. << rest-param ) ...)
.mets (lambda < rest-param ...)
.cble

(These notations are syntactically equivalent because the list notation
.code "(. X)"
actually denotes the object
.code X
which isn't wrapped in any list).

The keyword symbol
.code :
(colon) can appear in the parameter list. This is
the symbol in the keyword package whose name is the empty string.  This
symbol is treated specially: it serves as a separator between
required parameters and optional parameters.  Furthermore, the
.code :
symbol has a role to play in function calls: it can be specified as an argument
value to an optional parameter by which the caller indicates that the
optional argument is not being specified. It will be processed exactly
that way.

An optional parameter can also be written in the form
.cblk
.meti >> ( name < expr <> [ sym ]).
.cble
In this situation, if the call does not specify a value for the parameter
(or specifies a value as the keyword
.code :
(colon)) then the parameter takes on the
value of the expression
.metn expr .
If
.meta sym
is specified, then
.meta sym
will be
introduced as an additional binding with a Boolean value which indicates
whether or not the optional parameter had been specified by the caller.

The initializer expressions are evaluated an environment in which
all of the previous parameters are visible, in addition to the surrounding
environment of the lambda. For instance:

.cblk
  (let ((default 0))
    (lambda (str : (end (length str)) (counter default))
      (list str end counter)))
.cble

In this
.codn lambda ,
the initializing expression for the optional parameter
end is
.codn "(length str)" ,
and the
.code str
variable it refers to is the previous
argument. The initializer for the optional variable counter is
the expression default, and it refers to the binding established
by the surrounding let. This reference is captured as part of the
.codn lambda 's
lexical closure.

.TP* Examples:
.IP "Counting function:"
This function, which takes no arguments, captures the
variable
.codn counter .
Whenever this object is called, it increments
.code counter
by
.code 1
and returns the incremented value.

.cblk
  (let ((counter 0))
    (lambda () (inc counter)))
.cble

.IP "Function that takes two or more arguments:"
The third and subsequent arguments are aggregated into a list passed as the
single parameter
.codn z :

.cblk
  (lambda (x y . z) (list 'my-arguments-are x y z))
.cble

.IP "Variadic function:"

.cblk
  (lambda args (list 'my-list-of-arguments args))
.cble

.IP "Optional arguments:"

.cblk
  [(lambda (x : y) (list x y)) 1] -> (1 nil)
  [(lambda (x : y) (list x y)) 1 2] -> (1 2)
.cble

.coNP Macros @ flet and @ labels
.synb
.mets (flet >> ({( name < param-list << function-body-form *)}*)
.mets \ \  << body-form *)

.mets (labels >> ({( name < param-list << function-body-form *)}*)
.mets \ \  << body-form *)
.syne
.desc
The
.code flet
and
.code labels
macros bind local, named functions in the lexical scope.
The difference between
.code flet
and
.code labels
is that a function defined by
.code labels
can see itself, and therefore recurse directly by name. Moreover, if multiple
functions are defined by the same labels construct, they all have each other's
names in scope of their bodies.
By contrast, a
.codn flet -defined
function does not have itself in scope and cannot recurse.
Multiple functions in the same
.code flet
do not have each other's names in their scopes.

More formally, the
.metn function-body-form -s
and
.meta param-list
of the functions defined by
.code labels
are in a scope in which all of the function
names being defined by that same
.code labels
construct are visible.

Under both
.code labels
and
.codn flet ,
the local functions that are defined are
lexically visible to the main
.metn body-form -s.

Note that
.code labels
and
.code flet
are properly scoped with regard to macros.
During macro expansion, function bindings introduced by these
macro operators shadow macros defined by
.code macrolet
and
.codn defmacro .

Furthermore, function bindings introduced by
.code labels
and
.code flet
also shadow symbol macros defined by
.codn symacrolet ,
when those symbol macros occur as arguments of a
.code dwim
form.

See also: the
.code macrolet
operator.

.TP* "Dialect Note:"

The
.code flet
and
.code labels
macros do not establish named blocks around the body forms
of the local functions which they bind. This differs from
ANSI Common Lisp, whose local function have implicit named blocks,
allowing for
.code return-from
to be used.

.TP* Examples:
.cblk
  ;; Wastefully slow algorithm for determining evenness.
  ;; Note:
  ;; - mutual recursion between labels-defined functions
  ;; - inner is-even bound by labels shadows the outer
  ;;   one bound by defun so the (is-even n) call goes
  ;;   to the local function.

  (defun is-even (n)
   (labels ((is-even (n)
              (if (zerop n) t (is-odd (- n 1))))
            (is-odd (n)
              (if (zerop n) nil (is-even (- n 1)))))
     (is-even n)))
.cble

.coNP Function @ call
.synb
.mets (call < function << argument *)
.syne
.desc
The
.code call
function invokes
.metn function ,
passing it the given arguments, if any.

.TP* Examples:
Apply arguments
.code "1 2"
to a
.code lambda
which adds them to produce
.codn 3 :

.cblk
  (call (lambda (a b) (+ a b)) 1 2)
.cble

Useless use of
.code call
on a named function; equivalent to
.codn "(list 1 2)" :

.cblk
  (call (fun list) 1 2)
.cble

.coNP Operator @ fun
.synb
.mets (fun << function-name )
.syne
.desc
The
.code fun
operator retrieves the function object corresponding to a named
function in the current lexical environment.

The
.meta function-name
is a symbol denoting a named function: a built in
function, or one defined by
.codn defun .

Note: the
.code fun
operator does not see macro bindings. It is possible to
retrieve a global macro expander using
.codn symbol-function .

.TP* "Dialect Note:"
A lambda expression is not a function name in \*(TL. The
syntax
.code "(fun (lambda ...))"
is invalid.

.coNP Operator @ dwim
.synb
.mets (dwim << argument *)
.mets <> [ argument *]
.mets (set (dwim < obj-place < index <> [ alt ]) << new-value )
.mets (set >> [ obj-place < index <> [ alt ]] << new-value )
.syne
.desc
The
.code dwim
operator's name is an acronym: DWIM may be taken to mean
"Do What I Mean", or alternatively, "Dispatch, in a Way that is
Intelligent and Meaningful".

The notation
.code [...]
is a shorthand which denotes
.codn "(dwim ...)" .

The
.code dwim
operator takes a variable number of arguments, which are
treated as expressions to be individually macro-expanded
and evaluated, using the same rules.

This means that the first argument isn't a function name, but an ordinary
expression which can simply compute a function object (or, more generally,
a callable object).

Furthermore, for those arguments of
.code dwim
which are symbols (after all macro-expansion is performed), the evaluation
rules are altered. For the purposes of resolving symbols to values, the
function and variable binding namespaces are considered to be merged into a
single space, creating a situation that is very similar to a Lisp-1 style
dialect.

This special Lisp-1 evaluation is not recursively applied.  All arguments of
.code dwim
which, after macro expansion, are not symbols are evaluated using the
normal Lisp-2 evaluation rules. Thus, the DWIM operator must be used
in every expression where the Lisp-1 rules for reducing symbols to
values are desired.

If a symbol has bindings both in the variable and function namespace in scope,
and is referenced by a dwim argument, this constitutes a conflict which is
resolved according to two rules.  When nested scopes are concerned, then an
inner binding shadows an outer binding, regardless of their kind.  An inner
variable binding for a symbol shadows an outer or global function binding,
and vice versa.

If a symbol is bound to both a function and variable in the global namespace,
then the variable binding is favored.

Macros do not participate in the special scope conflation, with one
exception. What this means is that the space of symbol macros is not folded
together with the space of operator macros. An argument of
.code dwim
that is a symbol might be
symbol macro, variable or function, but it cannot be interpreted as the name of
a operator macro.

The exception is this: from the perspective of a
.code dwim
form, function bindings can shadow symbol macros. If a
function binding is defined in an inner scope relative to a symbol macro for
the same symbol,
using
.code flet
or
.codn labels ,
the function hides the symbol macro. In other words, when
macro expansion processes an argument of a
.code dwim
form, and that argument is a symbol, it is treated specially
in order to provide a consistent name lookup behavior. If the innermost
binding for that symbol is a function binding, it refers to that
function binding, even if a more outer symbol macro binding exists,
and so the symbol is not expanded using the symbol macro.
By contrast, in an ordinary form, a symbolic argument never resolves
to a function binding. The symbol refers to either a symbol macro or a
variable, whichever is nested closer.

If, after macro expansion, the leftmost argument of the
.code dwim
is the name of a special operator or macro, the
.code dwim
form doesn't denote an invocation of that operator or macro.  A
.code dwim
form is an invocation of the
.code dwim
operator, and the leftmost argument of that operator, if it is a symbol, is
treated as a binding to be resolved in the variable or function namespace,
like any other argument.
Thus
.code "[if x y]"
is an invocation of the
.code if
function, not the
.code if
operator.

How many arguments are required by the
.code dwim
operator depends on the type of
object to which the first argument expression evaluates.  The possibilities
are:
.RS
.meIP >> [ function << argument *]
Call the given function object with the given arguments.

.meIP >> [ symbol << argument *]
If the first expression evaluates to a symbol, that symbol
is resolved in the function namespace, and then
the resulting function, if found, is called with the
given arguments.

.meIP >> [ sequence << index ]
Retrieve an element from
.metn sequence ,
at the specified
.metn index ,
which is a nonnegative integer.

This form is also a place if the
.meta sequence
subform is a place. If a value is stored to this place, it replaces the
element.

The place may also be deleted, which has the effect of removing the element
from the sequence, shifting the elements at higher indices, if any, down one
element position, and shortening the sequence by one.

.meIP >> [ sequence << from-index..to-below-index ]
Retrieve the specified range of elements.
The range of elements is specified in the
.code from
and
.code to
fields of a range object. The
.code ..
(dotdot) syntactic sugar denotes it construction via the
.code rcons
function.  See the section on Range Indexing below.

This form is also a syntactic place, if the
.meta sequence
subform is a place. Storing a value in this place
has the effect of replacing the subsequence with
a new subsequence. Deleting the place has the
effect of removing the specified subsequence
from
.metn sequence .
The
.meta new-value
argument in a range assignment can be a string, vector or list,
regardless of whether the target is a string, vector or list.
If the target is a string, the replacement sequence must be
a string, or a list or vector of characters.

.meIP >> [ sequence << index-list ]
Elements specified
by
.metn index-list ,
which may be a list or vector,
are extracted from
.meta sequence
and returned as a sequence
of the same kind as
.metn sequence .

This form is equivalent to
.cblk
.meti (select < sequence << where-index )
.cble
except when the target of an assignment operation.

This form is a syntactic place if
.meta sequence
is one. If a sequence is assigned to this place,
then elements of the sequence are distributed to the
specified locations.

The following equivalences hold between index-list-based indexing
and the
.code select
and
.code replace
functions, except that
.code set
always returns the value assigned, whereas
.code replace
returns its first argument:

.cblk
  [seq idx-list] <--> (select seq idx-list)

  (set [seq idx-list] new) <--> (replace seq new idx-list)
.cble

Note that unlike the select function, this does not support
.cblk
.meti >> [ hash << index-list ]
.cble
because since hash keys may be lists, that syntax is
indistinguishable from a simple hash lookup where
.meta index-list
is the key.

.meIP >> [ hash < key <> [ alt ]]
Retrieve a value from the hash table corresponding to
.metn key ,
or else return
.meta alt
if there is no such entry. The expression
.meta alt
is always evaluated, whether or not its value is used.

.RE
.PP

.TP* "Range Indexing:"
Vector and list range indexing is based from zero, meaning
that the first element is numbered zero, the second one
and so on.
zero. Negative values are allowed; the value
.code -1
refers to the last element of the vector or
list, and
.code -2
to the second last and so forth. Thus the range
.code "1 .. -2"
means
"everything except for the first element and the last two".

The symbol
.code t
represents the position one past the end of the vector, string or
list, so
.code "0 .. t"
denotes the entire list or vector, and the range
.code "t .. t"
represents the empty range just beyond the last element.
It is possible to assign to
.codn "t .. t" .
For instance:

.cblk
  (defvar list '(1 2 3))
  (set [list t .. t] '(4)) ;; list is now (1 2 3 4)
.cble

The value zero has a "floating" behavior when used as the end of a range.
If the start of the range is a negative value, and the end of the
range is zero, the zero is interpreted as being the position past the
end of the sequence, rather than the first element. For instance the range
.code -1..0
means the same thing as
.codn -1..t .
Zero at the start of a range
always means the first element, so that
.code 0..-1
refers to all the elements except for the last one.

.TP* Notes:
The dwim operator allows for a Lisp-1 flavor of programming in \*(TL,
which is principally a Lisp-2 dialect.

A Lisp-1 dialect is one in which an expression like
.code "(a b)"
treats both a and b
as expressions subject to the same evaluation rules\(emat least, when
.code a
isn't an operator or an operator macro. This means that the symbols
.code a
and
.code b
are resolved to values in the same namespace. The form denotes a function call
if the value of variable
.code a
is a function object.  Thus in a Lisp-1, named functions do not exist as
such: they are just variable bindings.  In a Lisp-1, the form
.code "(car 1)"
means that there
is a variable called
.codn car ,
which holds a function, which is retrieved from that
variable and the argument
.code 1
is applied to it. In the expression
.codn "(car car)" ,
both occurrences of
.code car
refer to the variable, and so this form applies the
.code car
function to itself. It is almost certainly meaningless.
In a Lisp-2
.code "(car 1)"
means that there is a function called
.codn car ,
in the function namespace. In the expression
.code "(car car)"
the two occurrences refer to different bindings:
one is a function and the other a variable.
Thus there can exist a variable
.code car
which holds a cons cell object, rather than the
.code car
function, and the form makes sense.

The Lisp-1 approach is useful for functional programming, because it eliminates
cluttering occurrences of the call and fun operators.  For instance:

.cblk
  ;; regular notation

  (call foo (fun second) '((1 a) (2 b)))

  ;; [] notation

  [foo second '((1 a) (2 b))]
.cble

Lisp-1 dialects can also provide useful extensions by giving a meaning
to objects other than functions in the first position of a form,
and the
.code dwim/[...]
syntax does exactly this.

\*(TL is a Lisp-2 because Lisp-2 also has advantages. Lisp-2 programs
which use macros naturally achieve hygiene because lexical variables do
not interfere with the function namespace. If a Lisp-2 program has
a local variable called
.codn list ,
this does not interfere with the hidden use of the function
.code list
in a macro expansion in the same block of code. Lisp-1 dialects have to
provide hygienic macro systems to attack this problem. Furthermore, even when
not using macros, Lisp-1 programmers have to avoid using the names of functions
as lexical variable names, if the enclosing code might use them.

The two namespaces of a Lisp-2 also naturally accommodate symbol macros and
operator macros.  Whereas functions and variables can be represented in a
single namespace readily, because functions are data objects, this is not so
with symbol macros and operator macros, the latter of which are distinguished
syntactically by their position in a form. In a Lisp-1 dialect, given
.codn "(foo bar)" ,
either of the two symbols could be a symbol macro, but only
.code foo
can possibly be an operator macro. Yet, having only a single namespace, a
Lisp-1 doesn't permit
.codn "(foo foo)" ,
where
.code foo
is simultaneously a symbol macro and an operator macro, though the situation is
unambiguous by syntax even in Lisp-1.  In other words, Lisp-1 dialects do not
entirely remove the special syntactic recognition given to the leftmost
position of a compound form, yet at the same time they prohibit
the user from taking full advantage of it by providing only one namespace.

\*(TL provides
the "best of both worlds": the DWIM brackets notation provides a model of
Lisp-1 computation that is purer than Lisp-1 dialects (since the leftmost
argument is not given any special syntactic treatment at all)
while the Lisp-2 foundation provides a traditional Lisp environment with its
"natural hygiene".

.SS* Sequencing, Selection and Iteration
.coNP Operators @ progn and @ prog1
.synb
.mets (progn << form *)
.mets (prog1 << form *)
.syne
.desc
The
.code progn
operator evaluates forms in order, and returns the value
of the last form. The return value of the form
.code (progn)
is
.codn nil .

The
.code prog1
operator evaluates forms in order, and returns the value
of the first form. The return value of the form
.code (prog1)
is
.codn nil .

Various other operators such as
.code let
also arrange for the evaluation
of a body of forms, the value of the last of which is returned.
These operators are said to feature an implicit
.codn progn .

.coNP Operator @ cond
.synb
.mets (cond >> {( test << form *)}*)
.syne
.desc
The
.code cond
operator provides a multi-branching conditional evaluation of
forms. Enclosed in the cond form are groups of forms expressed as lists.
Each group must be a list of at least one form.

The forms are processed from left to right as follows: the first form,
.metn test ,
in each group is evaluated. If it evaluates true, then the remaining
forms in that group, if any, are also evaluated. Processing then terminates and
the result of the last form in the group is taken as the result of cond.
If
.meta test
is the only form in the group, then result of
.meta test
is taken
as the result of
.codn cond .

If the first form of a group yields
.codn nil ,
then processing continues with the
next group, if any. If all form groups yield
.codn nil ,
then the cond form yields
.codn nil .
This holds in the case that the syntax is empty:
.code (cond)
yields
.codn nil .

.coNP Macros @, caseq @ caseql and @ casequal
.synb
.mets (caseq < test-form << normal-clause * <> [ else-clause ])
.mets (caseql < test-form << normal-clause * <> [ else-clause ])
.mets (casequal < test-form << normal-clause * <> [ else-clause ])
.syne
.desc
These three macros arrange for the evaluation of of
.metn test-form ,
whose value is then compared against the key or keys in each
.meta normal-clause
in turn.
When the value matches a key, then the remaining forms of
.meta normal-clause
are evaluated, and the value of the last form is returned; subsequent
clauses are not evaluated. When the value doesn't match any of the keys
of a
.meta normal-clause
then the next
.meta normal-clause
is tested.
If all these clauses are exhausted, and there is no
.metn else-clause ,
then the value nil is returned. Otherwise, the forms in the
.meta else-clause
are evaluated, and the value of the last one is returned.

The syntax of a
.meta normal-clause
takes on these two forms:

.cblk
.mets >> ( key << form *)
.cble

where
.meta key
may be an atom which denotes a single key, or else a list
of keys.  There is a restriction that the symbol
.code t
may not be used
as
.metn key .
The form
.code (t)
may be used as a key to match that symbol.

The syntax of an
.meta else-clause
is:

.cblk
.mets (t << form *)
.cble

which resembles a form that is often used as the final clause
in the
.code cond
syntax.

The three forms of the case construct differ from what type of
test they apply between the value of
.meta test-form
and the keys.
The
.code caseq
macro generates code which uses the
.code eq
function's
equality. The
.code caseql
macro uses
.codn eql ,
and
.code casequal
uses
.codn equal .

.TP* Example
.cblk
  (let ((command-symbol (casequal command-string
                          (("q" "quit") 'quit)
                          (("a" "add") 'add)
                          (("d" "del" "delete") 'delete)
                          (t 'unknown))))
    ...)
.cble

.coNP Operator/function @ if
.synb
.mets (if < cond < t-form <> [ e-form ])
.mets [if < cond < then <> [ else ]]
.syne
.desc
There exist both an
.code if
operator and an
.code if
function. A list form with the symbol
.code if
in the fist position is interpreted as an invocation of the
.code if
operator.
The function can be accessed using the DWIM bracket notation and in other
ways.

The
.code if
operator provides a simple two-way-selective evaluation control.
The
.meta cond
form is evaluated. If it yields true then
.meta t-form
is evaluated, and that form's return value becomes the return value of the
.codn if .
If
.meta cond
yields false, then
.meta e-form
is evaluated and its return value is taken to be that of
.codn if .
If
.meta e-form
is omitted, then the behavior is as if
.meta e-form
were specified as
.codn nil .

The
.code if
function provides no evaluation control. All of arguments
are evaluated from left to right. If the
.meta cond
argument is true, then it
returns the
.meta then
argument, otherwise it returns the value of the
.meta else
argument if present, otherwise it returns
.codn nil .

.coNP Operator/function @ and
.synb
.mets (and << form *)
.mets [and << arg *]
.syne
.desc
There exist both an
.code and
operator and an
.code and
function. A list form with the
symbol
.code and
in the fist position is interpreted as an invocation of the
operator.  The function can be accessed using the DWIM bracket notation and in
other ways.

The
.code and
operator provides three functionalities in one.  It computes the
logical "and" function over several forms.  It controls evaluation (a.k.a.
"short-circuiting").  It also provides an idiom for the convenient substitution
of a value in place of
.code nil
when some other values are all true.

The
.code and
operator evaluates as follows. First, a return value is
established and initialized to the value
.codn t .
The
.metn form -s,
if any, are
evaluated from left to right.  The return value is overwritten with
the result of each form. Evaluation stops when all forms are exhausted,
or when
.code nil
is stored in the return value.
When evaluation stops, the operator yields the return value.

The
.code and
function provides no evaluation control; it receives all of its
arguments fully evaluated. If it is given no arguments, it returns
.codn t .
If it is given one or more arguments, and any of them are
.codn nil ,
it returns
.codn nil .
Otherwise it returns the value of the last argument.

.TP* Examples:
.cblk
  (and) -> t
  (and (> 10 5) (stringp "foo")) -> t
  (and 1 2 3) -> 3  ;; short-hand for (if (and 1 2) 3).
.cble

.coNP Operator/function @ or
.synb
.mets (or << form *)
.mets [or << arg *]
.syne
.desc
There exist both an
.code or
operator and an
.code or
function. A list form with the
symbol
.code or
in the fist position is interpreted as an invocation of the
operator.  The function can be accessed using the DWIM bracket notation and in
other ways.

The or operator provides three functionalities in one.  It computes the
logical "or" function over several forms.  It controls evaluation (a.k.a.
"short-circuiting").  The behavior of
.code or
also provides an idiom for the selection of the first non-nil value from a
sequence of forms.

The
.code or
operator evaluates as follows.  First, a return value is
established and initialized to the value
.codn nil .
The
.metn form -s,
if any,
are evaluated from left to right. The return value is overwritten
with the result of each
.metn form .
Evaluation stops when all forms are
exhausted, or when a true value is stored into the return value.
When evaluation stops, the operator yields the return value.

The
.code or
function provides no evaluation control; it receives all of its
arguments fully evaluated. If it is given no arguments, it returns
.codn nil .
If all of its arguments are
.codn nil ,
it also returns
.codn nil .
Otherwise, it
returns the value of the first argument which isn't
.codn nil .

.TP* Examples:
.cblk
  (or) -> nil
  (or 1 2) -> 1
  (or nil 2) -> 2
  (or (> 10 20) (stringp "foo")) -> t
.cble

.coNP Macros @ when and @ unless
.synb
.mets (when < expression << form *)
.mets (unless < expression << form *)
.syne
.desc
The when macro operator evaluates
.metn expression .
If
.meta expression
yields
true, and there are additional forms, then each
.meta form
is evaluated.
The value of the last form is becomes the result value of the when form.
If there are no forms, then the result is
.codn nil .

The
.code unless
operator is similar to when, except that it reverses the
logic of the test. The forms, if any, are evaluated if, and only if
.meta expression
is false.

.coNP Macros @ while and @ until
.synb
.mets (while < expression << form *)
.mets (until < expression << form *)
.syne
.desc
The
.code while
macro operator provides a looping construct.  It evaluates
.metn expression .
If
.meta expression
yields
.codn nil ,
then the evaluation of the
.code while
form
terminates, producing the value
.codn nil .
Otherwise, if there are additional forms,
then each
.meta form
is evaluated.  Next, evaluation returns to
.metn expression ,
repeating all of the previous steps.

The
.code until
macro operator is similar to while, except that the until form
terminates when
.meta expression
evaluates true, rather than false.

These operators arrange for the evaluation of all their enclosed forms
in an anonymous block. Any of the
.metn form -s,
or
.metn expression ,
may use
the
.code return
operator to terminate the loop, and optionally to specify
a result value for the form.

The only way these forms can yield a value other than
.code nil
is if the
.code return
operator is used to terminate the implicit anonymous block,
and is given an argument, which becomes the result value.

.coNP Macros @ while* and @ until*
.synb
.mets (while* < expression << form *)
.mets (until* < expression << form *)
.syne
.desc
The
.code while*
and
.code until*
macros are similar, respectively, to the macros
.code while
and
.codn until .

They differ in one respect: they begin by evaluating the
.metn form -s
one time unconditionally, without first evaluating
.metn expression .
After this evaluation, the subsequent behavior is
like that of
.code while
or
.codn until .

Another way to regard the behavior is that that these forms execute
one iteration unconditionally, without evaluating the termination test prior to
the first iteration. Yet another view is that these constructs relocate the
test from the "top of the loop" to the "bottom of the loop".

.coNP Macro @ whilet
.synb
.mets (whilet >> ({ sym | >> ( sym << init-form )}+)
.mets \ \  << body-form *)
.syne
.desc
The
.code whilet
macro provides a construct which combines iteration with variable
binding.

The evaluation of the form takes place as follows. First, fresh bindings are
established for
.metn sym -s
as if by the
.code let*
operator.
It is an error for the list of variable bindings to be empty.

After the establishment of the bindings, the the value of the
.meta sym
is tested. If the value is
.codn nil ,
then
.code whilet
terminates. Otherwise,
.metn body-form -s
are evaluated in the scope of the variable bindings, and then
.code whilet
iterates from the beginning, again establishing fresh bindings for the
.metn sym -s,
and testing the value of the last
.metn sym .

All evaluation takes place in an anonymous block, which can be
terminated with the
.code return
operator. Doing so terminates the loop.
If the
.code whilet
loop is thus terminated by an explicit
.codn return ,
a return value can be specified. Under normal termination, the return value is
.codn nil .

.TP* Examples:
.cblk
  ;; read lines of text from *std-input* and print them,
  ;; until the end-of-stream condition:

  (whilet ((line (get-line)))
    (put-line line))

  ;; read lines of text from *std-input* and print them,
  ;; until the end-of-stream condition occurs or
  ;; a line is identical to the character string "end".

  (whilet ((line (get-line))
           (more (and line (not (equal line "end")))))
    (put-line line))
.cble

.coNP Macros @ iflet and @ whenlet
.synb
.mets (iflet >> {({ sym | >> ( sym << init-form )}+) | << atom-form }
.mets \ \  < then-form <> [ else-form ])
.mets (whenlet >> {({ sym | >> ( sym << init-form )}+) | << atom-form }
.mets \ \  << body-form *)
.syne
.desc
The
.code iflet
and
.code whenlet
macros combine the variable binding of
.code let*
with conditional evaluation of
.code if
and
.codn when ,
respectively.

In either construct's syntax, a non-compound form
.meta atom-form
may appear in place of the variable binding list. In this case,
.meta atom-form
is evaluated as a form, and the construct is equivalent to
its respective ordinary
.code if
or
.code when
counterpart.

If the list of variable bindings is empty, it is interpreted as the atom
.code nil
and treated as an
.codn atom-form .

If one or more bindings are specified rather than
.metn atom-form ,
then the evaluation of these forms takes
place as follows. First, fresh bindings are established for
.metn sym -s
as if by the
.code let*
operator.

Then, the last variable's value is tested. If it is not
.code nil
then the test is true, otherwise false.

In the case of the
.code iflet
operator, if the test is true, the operator evaluates
.meta then-form
and yields its value. Otherwise the test is false, and if the
optional
.meta else-form
is present, that is evaluated instead and its value is returned.
If this form is missing, then
.code nil
is returned.

In the case of the
.code whenlet
operator, if the test is true, then the
.metn body-form -s,
if any, are evaluated. The value of the last one is
returned, otherwise
.code nil
if the forms are missing.
If the test is false, then evaluation of
.metn body-form -s
is skipped, and
.code nil
is returned.

.TP* Examples:
.cblk
  ;; dispose of foo-resource if present
  (whenlet ((foo-res (get-foo-resource obj)))
    (foo-shutdown foo-res)
    (set-foo-resource obj nil))

  ;; Contrast with: above, using when and let
  (let ((foo-res (get-foo-resource obj)))
    (when foo-res
      (foo-shutdown foo-res)
      (set-foo-resource obj nil)))

  ;; print frobosity value if it exceeds 150
  (whenlet ((fv (get-frobosity-value))
            (exceeds-p (> fv 150)))
    (format t "frobosity value ~a exceeds 150\en" fv))

  ;; yield 4: 3 interpreted as atom-form
  (whenlet 3 4)

  ;; yield 4: nil interpreted as atom-form
  (iflet () 3 4)
.cble

.coNP Macro @ condlet
.synb
.mets (condlet
.mets \ \  ([({ sym | >> ( sym << init-form )}+) | << atom-form ]
.mets \ \ \  << body-form *)*)
.syne
.desc
The
.code condlet
macro generalizes
.codn iflet .

Each argument is a compound consisting of at least one item: a list of
bindings or
.metn atom-form .
This item is followed by zero or more
.metn body-form -s.

If the are are no
.metn body-form -s
then the situation is treated as if there were a single
.meta body-form
specified as
.codn nil .

The arguments of
.code condlet
are considered in sequence, starting with the
leftmost.

If the argument's left item is an
.meta atom-form
then the form is evaluated. If it yields true, then the
.metn body-form -s
next to it are evaluated in order, and the
.code condlet
form terminates, yielding the value obtained from the last
.metn body-form .
If
.meta atom-form
yields false, then the next argument is considered, if there is one.

If the argument's left item is a list of bindings, then it is processed
with exactly the same logic as under the
.code iflet
macro. If the last binding contains a true value, then the
adjoining
.metn body-form -s
are evaluated in a scope in which all of the bindings are visible, and
.code condlet
terminates, yielding the value of the last
.metn body-form .
Otherwise, the next argument of
.code condlet
is considered (processed in a scope in which the bindings produced
by the current item are no longer visible).

If
.code condlet
runs out of arguments, it terminates and returns
.codn nil .

.TP* Example:
.cblk
  (let ((l '(1 2 3)))
    (condlet
       ;; first arg
       (((a (first l)   ;; a binding gets 1
         (b (second l)) ;; b binding gets 2
         (g (> a b))))  ;; last variable g is nil
        'foo)           ;; not evaluated
       ;; second arg
       (((b (second l)  ;; b gets 2
         (c (third l))  ;; c gets 3
         (g (> b c))))  ;; last variable g is true
        'bar)))         ;; condlet terminates
   --> bar              ;; result is bar
.cble

.coNP Macro @ ifa
.synb
.mets (ifa < cond < then <> [ else ])
.syne
.desc
The
.code ifa
macro provides a anaphoric conditional operator resembling the
.code if
operator. Around the evaluation of the
.meta then
and
.meta else
forms, the symbol
.code it
is implicitly bound to a subexpression of
.metn cond ,
a subexpression which is thereby identified as the
.IR it-form .
This
.code it
alias provides a convenient reference to that place or value, similar to the
word "it" in the English language, and similar anaphoric pronouns in other
languages.

If
.code it
is bound to a place form, the binding is established
as if using the
.code placelet
operator: the form is evaluated only once, even if the
.code it
alias is used multiple times in the
.meta then
or
.meta else
expressions.  Otherwise, if the form is not a syntactic place
.code it
is bound as an ordinary lexical variable to
the form's value.

An
.I it-candidate
is an an expression viable for having its value or storage location
bound to the
.code it
symbol. An it-candidate is any expression which is not a constant expression
according to the
.code constantp
function, and not a symbol.

The
.code ifa
macro imposes applies several rules to the
.meta cond
expression:
.RS
.IP 1.
The
.meta cond
expression must be either an atom, a function call form,
or a
.code dwim
form.  Otherwise the
.code ifa
expression is ill-formed, and throws an exception at
macro-expansion time. For the purposes of these rules,
a
.code dwim
form is considered as a function call expression, whose first
argument is the second element of the form. That is to say,
.code "[f x]"
which is equivalent to
.code "(dwim f x)"
is treated similarly to
.code "(f x)"
as a one-argument call.

.IP 2.
If the
.meta cond
expression is a function call with two or more arguments,
at most one of them may be an it-candidate.
If two or more arguments are it-candidates, the situation
is ambiguous. The
.code ifa
expression is ill-formed and throws an exception at macro-expansion
time.
.IP 3.
If
.meta cond
is an atom, or a function call expression with no arguments,
then the
.code it
symbol is not bound. Effectively,
.code ifa
macro behaves like the ordinary
.code if
operator.
.IP 4.
If
.meta cond
is a function call or
.code dwim
expression with exactly one argument, then the
.code it
variable is bound to the argument expression, except when
the function being called is
.codn not ,
.codn null ,
or
.codn false .
This binding occurs regardless of whether the expression is
an it-candidate.
.IP 5.
If
.meta cond
is a function call with exactly one argument to the Boolean negation
function which goes by one of the three names
.codn not ,
.codn null ,
or
.codn false ,
then that situation is handled by a rewrite according to the following pattern:

.cblk
.mets (ifa (not << expr ) < then << else ) -> (ifa < expr < else << then )
.cble

which applies likewise for
.code null
or
.code false
substituted for
.codn not .
The Boolean inverse function is removed, and the 
.meta then
and
.meta else
expressions are exchanged.
.IP 6.
If
.meta cond
is a function call with two or more arguments, then it is only
well-formed if at most one of those arguments is an it-candidate.
If there is one such argument, then the
.code it
variable is bound to it.
.IP 7.
Otherwise the variable is bound
to the leftmost argument expression, regardless of whether that
argument expression is an it-candidate.
.RE

.IP
In all other regards, the
.code ifa
macro behaves similarly to
.codn if .

The
.meta cond
expression is evaluated, and, if applicable,
the value of, or storage location denoted by the appropriate argument is
captured and bound to the variable
.code it
whose scope extends over the
.meta then
form, as well as over
.metn else ,
if present.

If
.meta cond
yields a true value, then
.meta then
is evaluated and the resulting value is returned, otherwise
.meta else
is evaluated if present and its value is returned.
A missing
.meta else
is treated as if it were the
.code nil
form.

.TP* Examples:
.cblk
  (ifa t 1 0)  ->  1

  ;; Rule 7: it binds to (* x x), which is
  ;; the only it-candidate.
  (let ((x 6) (y 49))
    (ifa (> y (* x x)) ;; it binds to (* x x)
      (list it)))
  -> (36)

  ;; Rule 4: it binds to argument of evenp,
  ;; even though 4 isn't an it-candidate.
  (ifa (evenp 4)
    (list it))
  -> (4)

  ;; Rule 5:
  (ifa (not (oddp 4))
    (list it))
  -> (4)

  ;; Violation of Rule 1:
  ;; while is not a function
  (ifa (while t (print 42))
    (list it))
  --> exception!

  ;; Violation of Rule 2:
  (let ((x 6) (y 49))
    (ifa (> (* y y y) (* x x)))
      (list it))
  --> exception!
.cble

.coNP Macro @ conda
.synb
.mets (conda >> {( test << form *)}*)
.syne
.desc
The
.code conda
operator provides a multi-branching conditional evaluation of
forms, similarly to the
.code cond
operator. Enclosed in the cond form are groups of forms expressed as lists.
Each group must be a list of at least one form.

The
.code conda
operator is anaphoric: it expands into a nested structure of zero or more
.code ifa
invocations, according to these patterns:

.cblk
  (conda) -> nil
  (conda (x y ...) ...) -> (ifa x (progn y ...) (conda ...))
.cble

Thus,
.code conda
inherits all the restrictions on the
.meta test
expressions from
.codn ifa ,
as well as the anaphoric
.code it
variable feature.

.coNP Macro @ dotimes
.synb
.mets (dotimes >> ( var < count-form <> [ result-form ]) << body-form *)
.syne
.desc
The
.code dotimes
macro implements a simple counting loop.
.meta var
is established as a variable, and initialized to zero.
.meta count-form
is evaluated one time to produce a limiting value, which should be a number.
Then, if the value of
.meta var
is less than the limiting value, the
.metn body-form -s
are evaluated,
.meta var
is incremented by one, and the process repeats with a new comparison
of
.meta var
against the limiting value possibly leading to another evaluation of
the forms.

If
.meta var
is found to equal or exceed the limiting value, then the loop terminates.

When the loop terminates, its return value is
.code nil
unless a
.meta result-form
is present, in which case the value of that form specifies the return value.

.metn body-form -s
as well as
.meta result-form
are evaluated in the scope in which the binding of
.meta var
is visible.

.coNP Operators @, each @, each* @, collect-each @, collect-each* @ append-each and @ append-each*
.synb
.mets (each >> ({( sym << init-form )}*) << body-form *)
.mets (each* >> ({( sym << init-form )}*) << body-form *)
.mets (collect-each >> ({( sym << init-form )}*) << body-form *)
.mets (collect-each* >> ({( sym << init-form )}*) << body-form *)
.mets (append-each >> ({( sym << init-form )}*) << body-form *)
.mets (append-each* >> ({( sym << init-form )}*) << body-form *)
.syne
.desc
These operators establish a loop for iterating over the elements of one or more
lists. Each
.meta init-form
must evaluate to a list. The lists are then iterated in
parallel over repeated evaluations of the
.metn body-form -s,
with each
.meta sym
variable being assigned to successive elements of its list. The shortest list
determines the number of iterations, so if any of the
.metn init-form -s
evaluate to
an empty list, the body is not executed.

The body forms are enclosed in an anonymous block, allowing the
.code return
operator to terminate the loop prematurely and optionally specify
the return value.

The
.code collect-each
and
.code collect-each*
variants are like
.code each
and
.codn each* ,
except that for each iteration, the resulting value of the body is collected
into a list. When the iteration terminates, the return value of the
.code collect-each
or
.code collect-each*
operator is this collection.

The
.code append-each
and
.code append-each*
variants are like
.code each
and
.codn each* ,
except that for each iteration other than the last, the resulting value of the
body must be a list. The last iteration may produce either an atom or a list.
The objects produced by the iterations are combined together as if they
were arguments to the append function, and the resulting value is the
value of the
.code append-each
or
.code append-each*
operator.

The alternate forms denoted by the adorned symbols
.codn each* ,
.code collect-each*
and
.codn append-each* ,
differ from
.codn each ,
.code collect-each
and
.code append-each*
in the following way. The plain forms evaluate the
.metn init-form -s
in an environment in which none of the
.code sym
variables are yet visible. By contrast, the alternate
forms evaluate each
.meta init-form
in an environment in which bindings for the
previous
.meta sym
variables are visible.  In this phase of evaluation,
.meta sym
variables are list-valued: one by one they are each bound to the list object
emanating from their corresponding
.metn init-form .
Just before the first loop
iteration, however, the
.meta sym
variables are assigned the first item from each
of their lists.

.TP* Example:
.cblk
 ;; print numbers from 1 to 10 and whether they are even or odd
 (each* ((n (range 1 10)) ;; n list a list here!
         (even (collect-each ((n m)) (evenp m))))
   ;; n is an item here!
   (format t "~s is ~s\en" n (if even "even" "odd")))
.cble
.TP* Output:
.cblk
 1 is odd
 2 is even
 3 is odd
 4 is even
 5 is odd
 6 is even
 7 is odd
 8 is even
 9 is odd
 10 is even
.cble

.coNP Operators @ for and @ for*
.synb
.mets ({for | for*} >> ({ sym | >> ( sym << init-form )}*)
.mets \ \ \ \ \ \ \ \ \ \ \ \ \  >> ([ test-form << result-form *])
.mets \ \ \ \ \ \ \ \ \ \ \ \ \  <> ( inc-form *)
.mets \ \  << body-form *)
.syne
.desc
The
.code for
and
.code for*
operators combine variable binding with loop iteration.
The first argument is a list of variables with optional initializers,
exactly the same as in the
.code let
and
.code let*
operators. Furthermore, the
difference between
.code for
and
.code for*
is like that between
.code let
and
.code let*
with regard to this list of variables.

The
.code for
and
.code for*
operators execute these steps:
.RS
.IP 1.
Establish an anonymous block over the entire form, allowing
the
.code return
operator to be used to terminate the loop.
.IP 2.
Establish bindings for the specified variables similarly to
.code let
and
.codn let* .
The variable bindings are visible over the
.metn test-form ,
each
.metn result-form ,
each
.meta inc-form
and each
.metn body-form .
.IP 3.
Evaluate
.metn test-form .
If
.meta test-form
yields
.codn nil ,
then the loop terminates.  Each
.meta result-form
is evaluated, and the value of the last of these
forms is is the result value of the loop.
If there are no
.metn result-form -s
then the result value is
.codn nil .
If the
.meta test-form
is omitted, then the test
is taken to be true, and the loop does not terminate.
.IP 4.
Otherwise, if
.meta test-form
yields true, then each
.meta body-form
is evaluated in turn. Then, each
.code inc-form
is evaluated in turn and processing resumes at step 2.
.RE

.IP
Furthermore, the
.code for
and
.code for*
operators establish an anonymous block,
allowing the
.code return
operator to be used to terminate at any point.


.coNP Operators @ block and @ block*
.synb
.mets (block < name << body-form *)
.mets (block* < name-form << body-form *)
.syne
.desc
The
.code block
operator introduces a named block around the execution of
some forms. The
.meta name
argument must be a symbol. Since a block name is not
a variable binding, keyword symbols are permitted, and so are the symbols
.code t
and
.codn nil .
A block named by the symbol nil is slightly special: it is
understood to be an anonymous block.

The
.code block*
operator differs from
.code block
in that it evaluates
.metn name-form ,
which is expected to produce a symbol. The resulting symbol
is used for the name of the block.

A named or anonymous block establishes an exit point for the
.code return-from
or
.code return
operator, respectively. These operators can be invoked within a block
to cause its immediate termination with a specified return value.

A block also establishes a prompt for a
.IR "delimited continuation" .
Anywhere in a block, a continuation can be captured using the
.code sys:capture-cont
function. Delimited continuations are described in the section
Delimited Continuations. A delimited continuation allows an apparently
abandoned block to be restarted at the capture point, with the
entire call chain and dynamic environment between the prompt and the capture
point intact.

Blocks in \*(TL have dynamic scope. This means that the following
situation is allowed:

.cblk
  (defun func () (return-from foo 42))
  (block foo (func))
.cble

The function can return from the
.code foo
block even though the
.code foo
block
does not lexically surround
.codn foo .

It is because blocks are dynamic that the
.code block*
variant exists; for lexically scoped blocks, it would make little
sense to have support a dynamically computed name.

Thus blocks in \*(TL provide dynamic non-local returns, as well
as returns out of lexical nesting.

.TP* "Dialect Note:"
In Common Lisp, blocks are lexical. A separate mechanism consisting of
catch and throw operators performs non-local transfer based on symbols.
The \*(TL example:

.cblk
  (defun func () (return-from foo 42))
  (block foo (func))
.cble

is not allowed in Common Lisp, but can be transliterated to:

.cblk
  (defun func () (throw 'foo 42))
  (catch 'foo (func))
.cble

Note that foo is quoted in CL. This underscores the dynamic nature of
the construct.
.code throw
itself is a function and not an operator. Also note that the CL
example, in turn, is even more closely transcribed back into \*(TL
simply by replacing its
.code throw
and
.code catch
with
.code return*
and
.codn block* :

.cblk
  (defun func () (return* 'foo 42))
  (block* 'foo (func))
.cble

Common Lisp blocks also do not support delimited continuations.

.coNP Operators @ return and @ return-from
.synb
.mets (return <> [ value ])
.mets (return-from < name <> [ value ])
.syne
.desc
The
.code return
operator must be dynamically enclosed within an anonymous
block (a block named by the symbol
.codn nil ).
It immediately terminates the
evaluation of the innermost anonymous block which encloses it, causing
it to return the specified value. If the value is omitted, the anonymous
block returns
.codn nil .

The
.code return-from
operator must be dynamically enclosed within a named block
whose name matches the
.meta name
argument. It immediately terminates the
evaluation of the innermost such block, causing it to return the specified
value. If the value is omitted, that block returns
.codn nil .

.TP* Example:
.cblk
    (block foo
      (let ((a "abc\en")
            (b "def\en"))
        (pprint a *stdout*)
        (return-from foo 42)
        (pprint b *stdout*)))
.cble

Here, the output produced is
.strn "abc" .
The value of
.code b
is not printed
because.
.code return-from
terminates block
.codn foo ,
and so the second pprint form is not evaluated.

.coNP Function @ return*
.synb
.mets (return* < name <> [ value ])
.syne
.desc
The
.code return*
function is similar to the the
.code return-from
operator, except that
.code name
is an ordinary function parameter, and so when
.code return*
is used, an argument expression must be specified which evaluates
to a symbol. Thus
.code return*
allows the target block of a return to be dynamically computed.

The following equivalence holds between the operator and function:

.cblk
  (return-from a b)  <-->  (return* 'a b)
.cble

Expressions used as
.meta name
arguments to
.code return*
which do not simply quote a symbol have no equivalent in
.codn return-from .

.SS* Evaluation

.coNP Function @ eval
.synb
.mets (eval < form <> [ env ])
.syne
.desc
The
.code eval
function treats the
.meta form
object as a Lisp expression, which is
evaluated. The side effects implied by the form are performed, and the value
which it produces is returned. The optional
.meta env
object specifies an environment for
resolving the function and variable references encountered in the expression.
If this argument is omitted
.code nil
then evaluation takes place in the global environment.

See also: the
.code make-env
function.

.coNP Function @ constantp
.synb
.mets (constantp < form >> [ env ])
.syne
.desc
The
.code constantp
function determines whether
.meta form
is a constant form, with respect to environment
.metn env .

If
.meta env
is absent, the global environment is used.
The
.meta env
argument is used for macro-expanding
.metn form .

Currently,
.code constantp
returns true for any form, which, after macro-expansion is a compound
form with the symbol
.code quote
in its first position, a non-symbolic atom, or one of the symbols
which evaluate to themselves and cannot be bound as variables.
These symbols are the keyword symbols, and the symbols
.code t
and
.codn nil .

In the future,
.code constantp
will be able to recognize more constant forms, such as calls to certain
functions whose arguments are constant forms.

.coNP Function @ make-env
.synb
.mets (make-env >> [ variable-bindings >> [ function-bindings <> [ next-env ]]])
.syne
.desc
The
.code make-env
function creates an environment object suitable as the
.code env
parameter.

The
.meta variable-bindings
and
.meta function-bindings
parameters, if specified,
should be association lists, mapping symbols to objects.  The objects in
.meta function-bindings
should be functions, or objects callable as functions.

The
.meta next-env
argument, if specified, should be an environment.

Note: bindings can also be added to an environment using the
.code env-vbind
and
.code env-fbind
functions.

.coNP Functions @ env-vbind and @ env-fbind
.synb
.mets (env-vbind < env < symbol << value )
.mets (env-fbind < env < symbol << value )
.syne
.desc
These functions bind a symbol to a value in either the function or variable
space of environment
.codn env .

Values established in the function space should be functions or objects that
can be used as functions such as lists, strings, arrays or hashes.

If
.meta symbol
already exists in the environment, in the given space, then its
value is updated with
.codn value .

.SS* Global Environment
.coNP Accessors @, symbol-function @ symbol-macro and @ symbol-value
.synb
.mets (symbol-function << symbol )
.mets (symbol-macro << symbol )
.mets (symbol-value << symbol )
.mets (set (symbol-function << symbol ) << new-value )
.mets (set (symbol-macro << symbol ) << new-value )
.mets (set (symbol-value << symbol ) << new-value )
.syne
.desc

The
.code symbol-function
function retrieves the value of the global function binding of the
given
.meta symbol
if it has one: that is, the function object bound to the
.metn symbol .
If
.meta symbol
has no global function binding, then
.code nil
is returned.

The
.code symbol-macro
function retrieves the value of the global macro binding of
.meta symbol
if it has one.  The value of a macro binding isn't a function object, but a
list of the following form:

.cblk
.mets (#<environment object> < macro-parameter-list << body-form *)
.cble

This representation is likely to change or expand to include other
forms in future \*(TX versions.

Note: the name of this function has nothing to do with symbol macros;
it is named for consistency with
.code symbol-function
and
.codn symbol-value ,
referring to the "macro-expander binding of the symbol cell".

The
.code symbol-value
function retrieves the value of a either a global variable or a global
symbol macro, whichever exists.  Otherwise it returns
.codn nil .

The value of a symbol macro binding is simply the replacement form.

A
.codn symbol-function ,
.codn symbol-macro ,
or
.code symbol-value
form denotes a place.  If
.meta symbol
has a binding in, respectively, the function or variable namespace
of the global environment, then a value may be stored in the place,
otherwise an error is thrown. Deleting a place doesn't require a binding;
it takes place as if using the
.code fmakunbound
or
.code makunbound
functions. If a nonexistent place is deleted, the prior value yielded
by the deletion is deemed to be
.codn nil .

.TP* "Dialect note:"

In ANSI Common Lisp, the
.code symbol-function
function retrieves a function, macro or special operator binding.
These are all in one space and may not co-exist. In \*(TL, it
retrieves strictly a function binding.  The
.code symbol-macro
function doesn't exist in Common Lisp.

.coNP Functions @, boundp @ fboundp and @ mboundp
.synb
.mets (boundp << symbol )
.mets (fboundp << symbol )
.mets (mboundp << symbol )
.syne
.desc
.code boundp
returns
.code t
if the symbol is bound as a variable or symbol macro in the global
environment, otherwise
.codn nil .

.code fboundp
returns
.code t
if the symbol has a function binding in the global
environment, otherwise it returns nil
.codn nil .

.TP* "Dialect Note:"

The ANSI Common Lisp
.code fboundp
yields true if its argument has a function, macro or operator
binding. The behavior of the Common Lisp expression
.code "(fboundp x)"
in Common Lisp can be obtained in \*(TL using the
.cblk
  (or (fboundp x) (mboundp x) (special-operator-p x))
.cble
expression.

.code mboundp
returns
.code t
if the symbol has an operator macro binding in the global environment,
otherwise
.codn nil .

.coNP Functions @, makunbound @ fmakunbound and @ mmakunbound
.synb
.mets (makunbound << symbol )
.mets (fmakunbound << symbol )
.mets (mmakunbound << symbol )
.syne
.desc
The function
.code makunbound
removes any binding for
.meta symbol
from the variable namespace of the global environment. If
.meta symbol
has no such binding, it does nothing.
In either case, it returns
.metn symbol .

Both variables and symbol macros are bindings in the variable namespace.

Additionally, if
.meta symbol
was previously marked as special, for instance
by
.codn defvar ,
this marking is removed by
.codn makunbound .

The function
.code fmakunbound
removes any binding for
.meta symbol
from the function namespace of the global environment. If
.meta symbol
has no such binding, it does nothing.
In either case, it returns
.metn symbol .

The function
.code mmakunbound
removes any binding for
.meta symbol
from the operator macro namespace of the global environment.  If
.meta symbol
has no such binding, it does nothing.
In either case, it returns
.metn symbol .

.TP* "Dialect Note:"

The behavior of these functions differs from ANSI Common Lisp.

The
.code makunbound
function in Common Lisp only removes a value from a dynamic variable. The
dynamic variable does not cease to exist, it only ceases to have a value
(because a binding is a value).  The special property from a symbol is also not
removed.  In \*(TL, the variable ceases to exist. The binding
of a variable isn't its value, it is the variable itself: the association
between a name and an abstract storage location, in some environment.
If the binding is undone, the variable disappears.

The
.code fmakunbound
function in Common Lisp removes a function or macro binding, which
do not coexist.

The
.code mmakunbound
function doesn't exist in Common Lisp.

.coNP Function @ func-get-form
.synb
.mets (func-get-form << func )
.syne
.desc
The
.code func-get-form
function retrieves a source code form of
.metn func ,
which must be an interpreted function. The source code form has the syntax
.cblk
.meti >> ( name < arglist << body-form *) .
.cble

.coNP Function @ func-get-name
.synb
.mets (func-get-name < func <> [ env ])
.syne
.desc
The
.code func-get-name
tries to resolve the function object
.meta func
to a name. If that is not possible, it returns
.codn nil .

The resolution is performed by an exhaustive search through
up to three spaces.

If an environment is specified by
.metn env ,
then this is searched first. If a binding is found in that
environment which resolves to the function, then the search
terminates and the binding's symbol is returned as the
function's name.

If the search through environment
.meta env
fails, or if that argument is not specified, then the
global environment is searched for a function binding
which resolves to
.metn func .
If such a binding is found, then the search terminates,
and the binding's symbol is returned. If two or more
symbols in the global environment resolve to the function,
it is not specified which one is returned.

If the global function environment search fails,
then the function is considered as a possible method.
The static slot space of all struct types is searched for
a slot which contains
.metn func .
If such a slot is found, then the method name is returned,
consisting of the syntax
.cblk
.meti (meth < type << name )
.cble
where
.meta type
is a symbol denoting the struct type and
.meta name
is the static slot of the struct type which holds
.metn func .

If all the searches fail, then
.code nil
is returned.

.coNP Function @ func-get-env
.synb
.mets (func-get-env << func )
.syne
.desc
The
.code func-get-env
function retrieves the environment object associated with
function
.metn func .
The environment object holds the captured bindings of a
lexical closure.

.coNP Function @ functionp
.synb
.mets (functionp << obj )
.syne
.desc
The
.code functionp
function returns
.code t
if
.meta obj
is a function, otherwise it returns
.codn nil .

.coNP Function @ interp-fun-p
.synb
.mets (interp-fun-p << obj )
.syne
.desc
The
.code interp-fun-p
function returns
.code t
if
.meta obj
is an interpreted function, otherwise it returns
.codn nil .

.coNP Function @ special-var-p
.synb
.mets (special-var-p << obj )
.syne
.desc
The
.code special-var-p
function returns
.code t
if
.meta obj
is a symbol marked for special variable binding, otherwise it returns
.codn nil .
Symbols are marked special by
.code defvar
and
.codn defparm .

.coNP Function @ special-operator-p
.synb
.mets (special-operator-p << obj )
.syne
.desc
The
.code special-operator-p
function returns
.code t
if
.meta obj
is a symbol which names a special operator, otherwise it returns
.codn nil .

.SS* Object Type

In \*(TL, objects obey the following type hierarchy. In this type hierarchy,
the internal nodes denote abstract types: no object is an instance of
an abstract type. Nodes in square brackets indicate an internal structure
in the type graph, visible to programs, and angle
brackets indicate a plurality of types which are not listed by name:

.cblk
  t ----+--- [cobj types] ---+--- hash
        |                    |
        |                    +--- stream
        |                    |
        |                    +--- random-state
        |                    |
        |                    +--- struct-type
        |                    |
        |                    +--- <structures>
        |                    |
        |                    +... <others>
        |
        |
        +--- sequence ---+--- string ---+--- str
        |                |              |
        |                |              +--- lstr
        |                |              |
        |                |              +--- lit
        |                |
        |                +--- list ---+--- null
        |                |            |
        |                |            +--- cons
        |                |            |
        |                |            +--- lcons
        |                |
        |                +--- vec
        |
        +--- number ---+--- float
        |              |
        |              +--- integer ---+--- fixnum
        |                              |
        |                              +--- bignum
        |
        +--- sym
        |
        +--- env
        |
        +--- range
        |
        +--- pkg
        |
        +--- fun
.cble

In addition to the above hierarchy, the following relationships also exist:

.cblk
  t ---+--- atom --- <any type other than cons> --- nil
       |
       +--- cons ---+--- lcons --- nil
                    |
                    +--- nil

  sym --- null
.cble

That is to say, the types are exhaustively partitioned into atoms and conses;
an object is either a
.code cons
or else it isn't, in which case it is the abstract
type
.codn atom .

The
.code cons
type is odd in that it is both an abstract type,
serving as a supertype for the type
.code lcons
and it is also a concrete type in that regular conses are of
this type.

The type
.code nil
is an abstract type which is empty. That is to say, no object is of
type
.codn nil .
This type is considered the abstract subtype of every other type,
including itself.

The type
.code nil
is not to be confused with the type
.code null
which is the type of the
.code nil
symbol.

Lastly, because the type of
.code nil
is the type
.code null
and
.code nil
is also a symbol, the
.code null
type is a subtype of
.codn sym .

.coNP Function @ typeof
.synb
.mets (typeof << value )
.syne
.desc
The
.code typeof
function returns a symbol representing the type of
.metn value .

The core types are identified by the following symbols:

.coIP cons
Cons cell.

.coIP str
String.

.coIP lit
Literal string embedded in the \*(TX executable image.

.coIP chr
Character.

.coIP fixnum
Fixnum integer: an integer that fits into the value word, not having to
be heap allocated.

.coIP bignum
A bignum integer: arbitrary precision integer that is heap-allocated.

.coIP float
Floating-point number.

.coIP sym
Symbol.

.coIP pkg
Symbol package.

.coIP fun
Function.

.coIP vec
Vector.

.coIP lcons
Lazy cons.

.coIP range
Range object.

.coIP lstr
Lazy string.

.coIP env
Function/variable binding environment.

.coIP hash
Hash table.

.coIP stream
I/O stream of any kind.

.coIP struct-type
A structure type: the type of any one of the values which represents
a structure type.
.PP

There are more kinds of objects, such as user-defined structures.

.coNP Function @ subtypep
.synb
.mets (subtypep < left-type-symbol << right-type-symbol )
.syne
.desc
The
.code subtypep
function tests whether
.meta left-type-symbol
and
.meta right-type-symbol
name a pair of types, such that the left type is a subtype of the right
type.

Each type is a subtype of itself. Most other type relationships can be inferred
from the type hierarchy diagrams given in the introduction to this section.

In addition, there are inheritance relationships among structures. If
.meta left-type-symbol
and
.meta right-type-symbol
both name structure types, then
.code subtypep
yields true if the types are the same struct type, or if the right
type is a direct or indirect supertype of the left.

.coNP Function @ typep
.synb
.mets (typep < object << type-symbol )
.syne
.desc
The
.code typep
function tests whether the type of
.meta object
is a subtype of the type named by
.metn type-symbol .

The following equivalence holds:

.cblk
  (typep a b) --> (subtypep (typeof a) b)
.cble

.coNP Macro @ typecase
.synb
.mets (typecase < test-form >> {( type-sym << clause-form *)}*)
.syne
.desc
The
.code typecase
macro evaluates
.meta test-form
and then successively tests its type against each clause.

Each clause consists of a type symbol
.meta type-sym
and zero or more
.metn clause-form -s.

The first clause whose
.meta type-sym
is a supertype of the type of
.metn test-form 's
value is considered to be the matching clause.
That clause's
.metn clause-form -s
are evaluated, and the value of the last form is returned.

If there is no matching clause, or there are no clauses present,
or the matching clause has no
.metn clause-form -s,
then
.code nil
is returned.

Note: since
.code t
is the supertype of every type, a clause whose
.meta type-sym
is the symbol
.code t
always matches.  If such a clause is placed as the last clause of a
.codn typecase ,
it provides a fallback case, whose forms are evaluated if none of the
previous clauses match.

.SS* Object Equivalence

.coNP Functions @ identity and @ use
.synb
.mets (identity << value )
.mets (use << value )
.syne
.desc
The
.code identity
function returns its argument.

The
.code use
function is a synonym.

.TP* Notes:
The
.code identity
function is useful as a functional argument, when a transformation
function is required, but no transformation is actually desired.
In this role, the
.code use
synonym leads to readable code. For instance:
.cblk
  ;; construct a function which returns its integer argument
  ;; if it is odd, otherwise it returns its successor.
  ;; "If it's odd, use it, otherwise take its successor".

  [iff oddp use succ]

  ;; Applications of the function:

  [[iff oddp use succ] 3] -> 3  ;; use applied to 3

  [[iff oddp use succ] 2] -> 3  ;; succ applied to 2
.cble

.coNP Functions @, null @ not and @ false
.synb
.mets (null << value )
.mets (not << value )
.mets (false << value )
.syne
.desc
The
.codn null ,
.code not
and
.code false
functions are synonyms.  They tests whether
.meta value
is
the object
.codn nil .
They return
.code t
if this is the case,
.code nil
otherwise.

.TP* Examples:
.cblk
  (null '()) -> t
  (null nil) -> t
  (null ()) -> t
  (false t) -> nil

  (if (null x) (format t "x is nil!"))

  (let ((list '(b c d)))
    (if (not (memq 'a list))
      (format t "list ~s does not contain the symbol a\en")))
.cble

.coNP Functions @ true and @ have
.synb
.mets (true << value )
.mets (have << value )
.syne
.desc
The
.code true
function is the complement of the
.codn null ,
.code not
and
.code false
functions. The
.code have
function is a synonym for
.codn true .

It return
.code t
if the
.meta value
is any object other than
.codn nil .
If
.meta value
is
.codn nil ,
it returns
.codn nil .

Note: programs should avoid explicitly testing values with true.
For instance
.code "(if x ...)"
should be favored over
.codn "(if (true x) ...)" .
However, the latter is useful with the
.code ifa
macro because
.cblk
.meti (ifa (true << expr ) ...)
.cble
binds the
.code it
variable to the value of
.metn expr ,
no matter what kind of form
.meta expr
is, which is not true in the
.cblk
.meti (ifa < expr ...)
.cble
form.

.TP* Example:
.cblk
   ;; Compute indices where the list '(1 nil 2 nil 3)
   ;; has true values:
   [where '(1 nil 2 nil 3) true] -> (1 3)
.cble

.coNP Functions @, eq @ eql and @ equal
.synb
.mets (eq < left-obj << right-obj )
.mets (eql < left-obj << right-obj )
.mets (equal < left-obj << right-obj )
.syne
.desc
The principal equality test functions
.codn eq ,
.code eql
and
.code equal
test whether two objects are equivalent, using different criteria. They return
.code t
if the objects are equivalent, and
.code nil
otherwise.

The
.code eq
function uses the strictest equivalence test, called implementation
equality.  The eq function returns
.code t
if, and only if,
.meta left-obj
and
.meta right-obj
are actually the same object. The
.code eq
test is is implemented
by comparing the raw bit pattern of the value, whether or not it is
an immediate value or a pointer to a heaped object.
Two character values are
.code eq
if they are the same character, and two fixnum integers
are
.code eq
if they have the same value.  All other object representations are actually
pointers, and are
.code eq
if, and only, if they point to the same object in memory.
So, for instance, two bignum integers might not be
.code eq
even if they have the same numeric
value, two lists might not be
.code eq
even if all their corresponding elements are
.code eq
and two strings might not be eq even if they hold identical text.

The
.code eql
function is slightly less strict than
.codn eq .
The difference between
.code eql
and
.code eq
is that if
.meta left-obj
and
.meta right-obj
are numbers which are of the same kind and have the same numeric value,
.code eql
returns
.metn t ,
even if they are different objects.
Note that an integers and a floating-point number are not
.code eql
even if one has a value which converts to the other: thus,
.code "(eql 0.0 0)"
yields
.codn nil ;
the comparison operation which finds these numbers equal is the
.codn "(= 0.0 0)" .
The
.code eql
function also specially treats range objects. Two distinct range objects are
.code eql
if their corresponding
.meta from
and
.meta to
fields are
.codn eql .
For all other object types,
.code eql
behaves like
.codn eq .

The
.code equal
function is less strict still than
.codn eql .
In general, it recurses into some kinds of aggregate objects to perform a
structural equivalence check.  For struct types, it also supports customization
via equality substitution.  See the Equality Substitution section under
Structures.

Firstly, if
.meta left-obj
and
.meta right-obj
are
.code eql
then they are also
.codn equal ,
though of course the converse isn't necessarily the case.

If two objects are both cons cells, then they are equal if their
.code car
fields are
.code equal
and their
.code cdr
fields are
.codn equal .

If two objects are vectors, they are
.code equal
if they have the same length, and
their corresponding elements are
.codn equal .

If two objects are strings, they are equal if they are textually identical.

If two objects are functions, they are
.code equal
if they have
.code equal
environments,
and if they have
the same code.  Two compiled functions are considered to have
the same code if and only if they are pointers to the same function.
Two interpreted functions are considered to have the same
code if their list
structure is
.codn equal .

Two hashes are
.code equal
if they use the same equality (both are
.codn :equal-based ,
or both are the default
.codn :eql-based ),
if their associated user data elements are equal (see the function
.codn get-hash-userdata ),
if their sets of keys are identical, and if the data items associated with
corresponding keys from each respective hash are
.code equal
objects.

Two ranges are
.code equal
if their corresponding
.meta to
and
.meta from
fields are equal.

For some aggregate objects, there is no special semantics.  Two arguments
which are symbols, packages, or streams are
.code equal
if and only if they are the same object.

Certain object types have a custom
.code equal
function.

.coNP Function @ less
.synb
.mets (less < left-obj << right-obj )
.mets (less < obj << obj *)
.syne
.desc
The
.code less
function, when called with two arguments, determines whether
.meta left-obj
compares less than
.meta right-obj
in a generic way which handles arguments of various types.

The argument syntax of
.code less
is generalized. It can accept one argument, in which case it unconditionally
returns
.code t
regardless of that argument's value. If more than two arguments are
given, then
.code less
generalizes in a way which can be described by the following equivalence
pattern, with the understanding that each argument expression
is evaluated exactly once:

.cblk
  (less a b c) <--> (and (less a b) (less b c))
  (less a b c d) <--> (and (less a b) (less b c) (less c d))
.cble

The
.code less
function is used as the default for the
.meta lessfun
argument of the functions
.code sort
and
.codn merge ,
as well as the
.meta testfun
argument of the
.code pos-min
and
.codn find-min .

The
.code less
function is capable of comparing numbers, characters, symbols, strings,
as well as lists and vectors of these.

If both arguments are the same object so that
.cblk
.meti (eq < left-obj << right-obj )
.cble
holds true, then the function returns
.code nil
regardless of the type of
.metn left-obj ,
even if the function doesn't handle comparing different instances
of that type. In other words, no object is less than itself, no matter
what it is.

If both arguments are numbers or characters, they are compared as if using the
.code <
function.

If both arguments are strings, they are compared as if using the
.code string-lt
function.

If both arguments are symbols, then their names are compared in
their place, as if by the
.code string-lt
function.

If both arguments are conses, then they are compared as follows:
.RS
.IP 1.
The
.code less
function is recursively applied to the
.code car
fields of both arguments. If it yields true, then
.meta left-obj
is deemed to be less than
.metn right-obj .
.IP 2.
Otherwise, if the
.code car
fields are unequal under
the
.code equal
function,
.code less
returns
.codn nil .
.IP 3.
If the
.code car
fields are
.code equal
then
.code less
is recursively applied to the
.code cdr
fields of the arguments, and the result of that comparison is returned.
.RE

.IP
This logic performs a lexicographic comparison on ordinary lists such
that for instance
.code "(1 1)"
is less than
.code "(1 1 1)"
but not less than
.code "(1 0)"
or
.codn (1) .

Note that the empty
.code nil
list nil compared to a cons is handled by type-based precedence, described
below.

If the arguments are vectors, they are compared lexicographically, similar
to strings. Corresponding elements, starting with element 0, of the
vectors are compared until an index position is found where the vectors
differ. If this differing position is beyond the end of one of the two vectors,
then the shorter vector is considered to be lesser. Otherwise, the result
of
.code less
is the outcome of comparing those differing elements themselves
with
.codn less .

If the two arguments are of the above types, but of mutually different types,
then
.code less
resolves the situation based on the following precedence: numbers and
characters are less than strings, which are less than symbols,
which are less than conses, which are less than vectors.

Note that since
.code nil
is a symbol, it is ranked lower than a cons. This interpretation ensures
correct behavior when
.code nil
is regarded as an empty list, since the empty list is lexicographically prior to
a nonempty list.

If either argument is a structure for which the
.code equal
method is defined, the method is invoked on that argument, and the
value returned is used in place of that argument for performing
the comparison.  Structures with no
.code equal
method cannot participate in a comparison, resulting in an error.
See the Equality Substitution section under Structures.

Finally, if either of the arguments has a type other than the above
types, the situation is an error.

.coNP Function @ greater
.synb
.mets (greater < left-obj << right-obj )
.mets (greater < obj << obj *)
.syne
.desc
The
.code
greater
function is equivalent to
.code less
with the arguments reversed. That is to say, the following
equivalences hold:

.cblk
  (greater a <--> (less a) <--> t
  (greater a b) <--> (less b a)
  (greater a b c ...) <--> (less ... c b a)
.cble

The
.code greater
function is used as the default for the
.meta testfun
argument of the
.code pos-max
and
.code find-max
functions.

.coNP Functions @ lequal and @ gequal
.synb
.mets (lequal < obj << obj *)
.mets (gequal < obj << obj *)
.syne
.desc
The functions
.code lequal
and
.code gequal
are similar to
.code less
and
.code greater
respectively, but differ in the following respect:
when called with two arguments which compare true under the
.code equal
function, the
.code lequal
and
.code gequal
functions return
.codn t .

When called with only one argument, both functions return
.code t
and both functions generalize to three or more arguments
in the same way as do
.code less
and
.codn greater .

.SS* List Manipulation
.coNP Function @ cons
.synb
.mets (cons < car-value << cdr-value )
.syne
.desc
The
.code cons
function allocates, initializes and returns a single cons cell.
A cons cell has two fields called
.code car
and
.codn cdr ,
which are accessed by
functions of the same name, or by the functions
.code first
and
.codn rest ,
which are synonyms for these.

Lists are made up of conses. A (proper) list is either the symbol
.code nil
denoting an empty list, or a cons cell which holds the first item of
the list in its
.codn car ,
and the list of the remaining items in
.codn cdr .
The expression
.code "(cons 1 nil)"
allocates and returns a single cons cell which denotes the one-element
list
.codn (1) .
The
.code cdr
is
.codn nil ,
so there are no additional items.

A cons cell whose
.code cdr
is an atom other than
.code nil
is printed with the dotted
pair notation. For example the cell produced by
.code "(cons 1 2)"
is denoted
.codn "(1 . 2)" .
The notation
.code "(1 . nil)"
is perfectly valid as input, but the cell which it denotes
will print back as
.codn (1) .
The notations are equivalent.

The dotted pair notation can be used regardless of what type
of object is the cons cell's
.codn cdr .
so that for instance
.code "(a . (b c))"
denotes the cons cell whose
.code car
is the symbol a
.code a
and whose
.code cdr
is the list
.codn "(b c)" .
This is exactly the same thing as
.codn "(a b c)" .
In other words
.code "(a b ... l m . (n o ... w . (x y z)))"
is exactly the same as
.codn "(a b ... l m n o ... w x y z)" .

Every list, and more generally cons cell tree structure, can be written
in a "fully dotted" notation, such that there are as many dots as there
are cells. For instance the cons structure of the nested list
.code "(1 (2) (3 4 (5)))"
can be made more explicit using
.codn "(1 . ((2 . nil) . ((3 . (4 . ((5 . nil) . nil))) . nil))))" .
The structure contains eight conses, and so there are eight dots
in the fully dotted notation.

The number of conses in a linear list like
.code "(1 2 3)"
is simply the number of items, so that list in particular is
made of three conses. Additional nestings require additional conses,
so for instance
.code "(1 2 (3))"
requires four conses. A visual way to count the conses from the printed
representation is to count the atoms, then add the count of open parentheses,
and finally subtract one.

A list terminated by an atom other than
.code nil
is called an improper
list, and the dot notation is extended to cover improper lists.
For instance
.code "(1 2 . 3)"
is an improper list of two elements,
terminated by
.codn 3 ,
and can be constructed using
.codn "(cons 1 (cons 2 3))" .
The fully dotted notation for this list is
.codn "(1 . (2 . 3))" .

.coNP Function @ atom
.synb
.mets (atom << value )
.syne
.desc
The
.code atom
function tests whether
.meta value
is an atom. It returns
.code t
if this is the
case,
.code nil
otherwise.  All values which are not cons cells are atoms.

.code "(atom x)"
is equivalent to
.codn "(not (consp x))" .

.TP* Examples:
.cblk
  (atom 3) -> t
  (atom (cons 1 2)) -> nil
  (atom "abc") -> t
  (atom '(3)) -> nil
.cble

.coNP Function @ consp
.synb
.mets (consp << value )
.syne
.desc
The
.code consp
function tests whether
.meta value
is a cons.  It returns
.code t
if this is the
case,
.code nil
otherwise.

.code "(consp x)"
is equivalent to
.codn "(not (atom x))" .

Non-empty lists test positive under
.code consp
because a list is represented as a reference to the first cons in a chain of
one or more conses.

Note that a lazy cons is a cons and satisfies the
.code consp
test.  See the function
.code make-lazy-cons
and the macro
.codn lcons .

.TP* Examples:
.cblk
  (consp 3) -> nil
  (consp (cons 1 2)) -> t
  (consp "abc") -> nil
  (consp '(3)) -> t
.cble

.coNP Accessors @ car and @ first
.synb
.mets (car << object )
.mets (first << object )
.mets (set (car << object ) << new-value )
.mets (set (first << object ) << new-value )
.syne
.desc
The functions
.code car
and
.code first
are synonyms.

If
.meta object
is a cons cell, these functions retrieve the
.code car
field of that cons cell.
.code "(car (cons 1 2))"
yields
.codn 1 .

For programming convenience,
.meta object
may be of several other kinds in addition to conses.

.code "(car nil)"
is allowed, and returns
.codn nil .

.meta object
may also be a vector or a string. If it is an empty vector or
string, then
.code nil
is returned. Otherwise the first character of the string or
first element of the vector is returned.

A
.code car
form denotes a valid place when
.meta object
is accessible via
.codn car ,
isn't the object
.codn nil ,
and is modifiable.

A
.code car
form supports deletion. The following equivalence
then applies:

.cblk
  (del (car place)) <--> (pop place)
.cble

This implies that deletion requires the argument of the
.code car
form to be a place, rather than the whole form itself.
In this situation, the argument place may have a value
which is
.codn nil ,
because
.code pop
is defined on an empty list.

The abstract concept behind deleting a
.code car
is that physically deleting this field from a cons,
thereby breaking it in half, would result in just the
.code cdr
remaining. Though fragmenting a cons in this manner is impossible,
deletion simulates it by replacing the place which previously held the
cons, with that cons'
.code cdr
field. This semantics happens to coincide with deleting the first element
of a list by a
.code pop
operation.

.coNP Accessors @ cdr and @ rest
.synb
.mets (cdr << object )
.mets (rest << object )
.mets (set (cdr << object ) << new-value )
.mets (set (rest << object ) << new-value )
.syne
.desc
The functions
.code cdr
and
.code rest
are synonyms.

If
.meta object
is a cons cell, these functions retrieve the
.code cdr
field of that cons cell.
.code "(cdr (cons 1 2))"
yields
.codn 2 .

For programming convenience,
.meta object
may be of several other kinds in addition to conses.

.code "(cdr nil)"
is allowed, and returns
.codn nil .

.meta object
may also be a vector or a string. If it is a non-empty string or vector
containing at least two items, then the remaining part of the object is
returned, with the first element removed. For example
.cblk
(cdr "abc")
.cble
yields
.strn "bc" .
If
.meta object
is is a one-element vector or string, or an empty vector or string,
then
.code nil
is returned. Thus
.cblk
(cdr "a")
.cble
and
.cblk
(cdr "")
.cble
both result in
.codn nil .

The invocation syntax of a
.code cdr
or
.code rest
form is a syntactic place. The place is semantically valid when
.meta object
is accessible via
.codn cdr ,
isn't the object
.codn nil ,
and is modifiable.

A
.code cdr
place supports deletion, according to the following near equivalence:

.cblk
  (del (cdr place)) <--> (prog1 (cdr place)
                                (set place (car place)))
.cble

Of course,
.code place
is evaluated only once.

Note that this is symmetric with the delete semantics of
.code car
in that the cons stored in
.code place
goes away, as does the
.code cdr
field, leaving just the
.codn car ,
which takes the place of the original cons.

.TP*
Example:

Walk every element of the list
.code "(1 2 3)"
using a
.code for
loop:

.cblk
    (for ((i '(1 2 3))) (i) ((set i (cdr i)))
      (print (car i) *stdout*)
      (print #\enewline *stdout*))
.cble

The variable
.code i
marches over the cons cells which make up the "backbone"
of the list. The elements are retrieved using the
.code car
function.
Advancing to the next cell is achieved using
.codn "(cdr i)" .
If
.code i
is the
last cell in a (proper) list,
.code "(cdr i)"
yields
.code nil
and so
.code i
becomes
.codn nil ,
the loop guard expression
.code i
fails and the loop terminates.

.coNP Functions @ rplaca and @ rplacd
.synb
.mets (rplaca < cons << new-car-value )
.mets (rplacd < cons << new-cdr-value )
.syne
.desc
The
.code rplaca
and
.code rplacd
functions assign new values into the
.code car
and
.code cdr
fields of the cell
.metn cons .

Note that, except for the difference in return value,
.code "(rplaca x y)"
is the same as the more generic
.codn "(set (car x) y)" ,
and likewise
.code "(rplacd x y)"
can be written as
.codn "(set (cdr x) y)" .

It is an error if
.meta cons
is not a cons or lazy cons. In particular,
whereas
.code "(car nil)"
is correct,
.code "(rplaca nil ...)"
is erroneous.

The
.code rplaca
and
.code rplacd
functions return
.metn cons .
Note: \*(TX versions 89 and earlier, these functions returned the new value.
The behavior was undocumented.

The
.meta cons
argument does not have to be a cons cell. Both functions support meaningful
semantics for vectors and strings.  If
.meta cons
is a string, it must be modifiable.

The
.code rplaca
function replaces the first element of a vector or first character
of a string. The vector or string must be at least one element long.

The
.code rplacd
function replaces the suffix of a vector or string after the first element
with a new suffix. The
.meta new-cdr-value
must be a sequence, and if the suffix of a string is being replaced,
it must be a sequence of characters. The suffix here refers to the portion of
the vector or string after the first element.

It is permissible to use
.code rplacd
on an empty string or vector. In this case,
.meta new-cdr-value
specifies the contents of the entire string or vector, as if the operation
were done on a non-empty vector or string, followed by the deletion of the
first element.

.coNP Accessors @, second @, third @, fourth @, fifth @, sixth @, seventh @, eighth @ ninth and @ tenth
.synb
.mets (first << object )
.mets (second << object )
.mets (third << object )
.mets (fourth << object )
.mets (fifth << object )
.mets (sixth << object )
.mets (seventh << object )
.mets (eighth << object )
.mets (ninth << object )
.mets (tenth << object )
.mets (set (first << object ) << new-value )
.mets (set (second << object ) << new-value )
.mets ...
.mets (set (tenth << object ) << new-value )
.syne
.desc
Used as functions, these accessors retrieve the elements of a sequence by
position.  If the sequence is shorter than implied by the position, these
functions return
.codn nil .

When used as syntactic places, these accessors denote the storage locations
by position. The location must exist, otherwise an error exception results.
The places support deletion.


.TP* Examples:
.cblk
  (third '(1 2)) -> nil
  (second "ab") -> #\eb
  (third '(1 2 . 3)) -> **error, improper list*

  (let ((x (copy "abcd")))
    (inc (third x))
    x) -> "abce"
.cble

.coNP Functions @, append @ nconc and @ append*
.synb
.mets (append <> [ list * << last-arg ])
.mets (nconc <> [ list * << last-arg ])
.mets (append* <> [ list * << last-arg ])
.syne
.desc
The
.code append
function creates a new list which is a catenation of the
.meta list
arguments. All arguments are optional;
.code (append)
produces the empty list.

If a single argument is specified, then
.code append
simply returns the value of that
argument. It may be any kind of object.

If N arguments are specified, where N > 1, then the first N-1 arguments must be
proper lists. Copies of these lists are catenated together. The last argument
N, shown in the above syntax as
.metn last-arg ,
may be any kind of object. It is
installed into the
.code cdr
field of the last cons cell of the resulting list.
Thus, if argument N is also a list, it is catenated onto the resulting list,
but without being copied. Argument N may be an atom other than
.codn nil ;
in that case
.code append
produces an improper list.

The
.code nconc
function works like
.codn append ,
but avoids consing. It destructively
manipulates (that is to say, mutates) incoming lists to catenate them, and so
must be used with care.

The
.code append*
function works like
.codn append ,
but returns a lazy list which produces
the catenation of the lists on demand.  If some of the arguments are
themselves lazy lists which are infinite, then
.code append*
can return immediately,
whereas append will get caught in an infinite loop trying to produce a
catenation and eventually exhaust available memory. (However, the last
argument to append may be an infinite lazy list, because append does not
traverse the last argument.)

.TP* Examples:
.cblk
  ;; An atom is returned.
  (append 3) -> 3

  ;; A list is also just returned: no copying takes place.
  ;; The eq function can verify that the same object emerges
  ;; from append that went in.
  (let ((list '(1 2 3)))
    (eq (append list) list)) -> t

  (append '(1 2 3) '(4 5 6) 7) -> '(1 2 3 4 5 6 . 7))

  ;; the (4 5 6) tail of the resulting list is the original
  ;; (4 5 6) object, shared with that list.

  (append '(1 2 3) '(4 5 6)) -> '(1 2 3 4 5 6)

  (append nil) -> nil

  ;; (1 2 3) is copied: it is not the last argument
  (append '(1 2 3) nil) -> (1 2 3)

  ;; empty lists disappear
  (append nil '(1 2 3) nil '(4 5 6)) -> (1 2 3 4 5 6)
  (append nil nil nil) -> nil

  ;; atoms and improper lists other than in the last position
  ;; are erroneous
  (append '(a . b) 3 '(1 2 3)) -> **error**
.cble

.coNP Functions @ revappend and @ nreconc
.synb
.mets (revappend < list1 << list2 )
.mets (nreconc < list1 << list2 )
.syne
.desc
The
.code revappend
function returns a list consisting of
.code list2
appended to a reversed copy of
.metn list1 .
The returned object shares structure
with
.metn list2 ,
which is unmodified.

The
.code nreconc
function behaves similarly, except
that the the returned object may share
structure with not only
.meta list2
but also
.metn list1 ,
which is modified.

.coNP Function @ list
.synb
.mets (list << value *)
.syne
.desc
The
.code list
function creates a new list, whose elements are the
argument values.

.TP* Examples:
.cblk
  (list) -> nil
  (list 1) -> (1)
  (list 'a 'b) -> (a b)
.cble

.coNP Function @ list*
.synb
.mets >> ( list* << value *)
.syne
.desc
The
.code list*
function is a generalization of cons. If called with exactly
two arguments, it behaves exactly like cons:
.code "(list* x y)"
is identical to
.codn "(cons x y)" .
If three or more arguments are specified,
the leading arguments specify additional atoms to be consed to the
front of the list. So for instance
.code "(list* 1 2 3)"
is the same as
.code "(cons 1 (cons 2 3))"
and produces the improper list
.codn "(1 2 . 3)" .
Generalizing in the other direction,
.code list*
can be called with just
one argument, in which case it returns that argument, and
can also be called with no arguments in which case it returns
.codn nil .

.TP* Examples:
.cblk
  (list*) -> nil
  (list* 1) -> 1
  (list* 'a 'b) -> (a . b)
  (list* 'a 'b 'c) -> (a b . c)
.cble

.TP* "Dialect Note:"
Note that unlike in some other Lisp dialects, the effect
of
.code "(list* 1 2 x)"
can also be obtained using
.codn "(list 1 2 . x)" .
However,
.code "(list* 1 2 (func 3))"
cannot be rewritten as
.code "(list 1 2 . (func 3))"
because the latter is equivalent to
.codn "(list 1 2 func 3)" .

.coNP Function @ sub-list
.synb
.mets (sub-list < list >> [ from <> [ to ]])
.syne
.desc
This function is like the
.code sub
function, except that it operates
strictly on lists.

For a description of the arguments and semantics, refer to the
.code sub
function.

.coNP Function @ replace-list
.synb
.mets (replace-list < list < item-sequence >> [ from <> [ to ]])
.syne
.desc
The
.code replace-list
function is like the replace function, except that the first
argument must be a list.

For a description of the arguments, semantics and return value, refer to the
.code replace
function.

.coNP Functions @ listp and @ proper-list-p
.synb
.mets (listp << value )
.mets (proper-list-p << value )
.syne
.desc
The
.code listp
and
.code proper-list-p
functions test, respectively, whether
.meta value
is a list, or a proper list, and return
.code t
or
.code nil
accordingly.

The
.code listp
test is weaker, and executes without having to traverse
the object.
.code "(listp x)"
is equivalent to
.codn "(or (null x) (consp x))" .
The empty list
.code nil
is a list, and a cons cell is a list.

The
.code proper-list-p
function returns
.code t
only for proper lists.  A proper list is
either
.codn nil ,
or a cons whose
.code cdr
is a proper list.
.code proper-list-p
traverses the
list, and its execution will not terminate if the list is circular.

Dialect Note: in \*(TX 137 and older,
.code proper-list-p
is called
.codn proper-listp .
The name was changed for adherence to conventions and compatibility with other
Lisp dialects, like Common Lisp. However, the function continues to be
available under the old name. Code that must run on \*(TX 137 and older
installations should use
.codn proper-listp ,
but its use going forward is deprecated.

.coNP Function @ length-list
.synb
.mets (length-list << list )
.syne
.desc
The
.code length-list
function returns the length of
.metn list ,
which may be
a proper or improper list. The length of a list is the number of conses in that
list.

.coNP Function @ copy-list
.synb
.mets (copy-list << list )
.syne
.desc
The
.code copy-list
function which returns a list similar to
.metn list ,
but with
a newly allocated cons cell structure.

If
.meta list
is an atom, it is simply returned.

Otherwise,
.meta list
is a cons cell, and
.code copy-list
returns the same object as the expression
.cblk
.meti (cons (car << list ) (copy-list (cdr << list ))).
.cble

Note that the object
.cblk
.meti (car << list )
.cble
is not deeply copied, but only
propagated by reference into the new list.
.code copy-list
produces
a new list structure out of the same items that are in
.metn list .

.TP* "Dialect Note:"
Common Lisp does not allow the argument to be an atom, except
for the empty list
.codn nil .

.coNP Function @ copy-cons
.synb
.mets (copy-cons << cons )
.syne
.desc
This function creates a fresh cons cell, whose
.code car
and
.code cdr
fields are copied from
.codn cons .

.coNP Functions @ reverse and @ nreverse
.synb
.mets (reverse << list )
.mets (nreverse << list )
.syne
.desc
Description:

The functions
.code reverse
and
.code nreverse
produce an object which contains
the same items as proper list
.metn list ,
but in reverse order.
If
.meta list
is
.codn nil ,
then both functions return
.codn nil .

The
.code reverse
function is non-destructive: it creates a new list.

The
.code nreverse
function creates the structure of the reversed list out of the
cons cells of the input list, thereby destructively altering it (if it contains
more than one element). How
.code nreverse
uses the material from the original list
is unspecified. It may rearrange the cons cells into a reverse order, or it may
keep the structure intact, but transfer the
.code car
values among cons cells into
reverse order.  Other approaches are possible.

.coNP Function @ ldiff
.synb
.mets (ldiff < list << sublist )
.syne
.desc
The values
.meta list
and
.meta sublist
are proper lists.

The
.code ldiff
function determines whether
.meta sublist
is a structural suffix of
.meta list
(meaning that it actually is a suffix, and is not merely equal to one).

This is true if
.meta list
and
.meta sublist
are the same object, or else,
recursively, if
.meta sublist
is a suffix of
.cblk
.meti (cdr << list ).
.cble

The object
.code nil
is the sublist of every list, including itself.

The ldiff function returns a new list consisting of the elements of
the prefix of
.meta list
which come before the
.meta sublist
suffix. The elements
are in the same order as in
.metn list .
If
.meta sublist
is not a suffix of
.metn list ,
then a copy of
.meta list
is returned.

These functions also work more generally on sequences.
The
.meta list
and
.meta sublist
arguments may be strings or vectors. In this case, the suffixing
matching behavior is relaxed to one of structural equivalence.
See the relevant examples below.

.TP* Examples:
.cblk
  ;;; unspecified: the compiler could make
  ;;; '(2 3) a suffix of '(1 2 3),
  ;;; or they could be separate objects.
  (ldiff '(1 2 3) '(2 3)) -> either (1) or (1 2 3)

  ;; b is the (1 2) suffix of a, so the ldiff is (1)
  (let ((a '(1 2 3)) (b (cdr a)))
    (ldiff a b))
  -> (1)

  ;; string and vector behavior
  (ldiff "abc" "bc") -> "a"

  (ldiff "abc" nil) -> "abc"

  (ldiff #(1 2 3) #(3)) -> #(1 2)

  ;; mixtures do not have above behavior
  (ldiff #(1 2 3) '(3)) -> #(1 2 3)

  (ldiff '(1 2 3) #(3)) -> #(1 2 3)

  (ldiff "abc" #(#\eb #\ec)) -> "abc"
.cble

.coNP Function @ last
.synb
.mets (last << seq )
.syne
.desc
If
.meta seq
is a nonempty proper or improper list, the
.code last
function
returns the last cons cell in the list: that cons cell whose
.code cdr
field is a terminating atom.

If
.meta seq
is
.codn nil ,
then
.code nil
is returned.

If
.meta seq
is a non-list sequence, then a one-element suffix of
.code seq
is returned, or an empty suffix if
.code seq
is an empty sequence.

.coNP Accessor @ nthcdr
.synb
.mets (nthcdr < index << list )
.mets (set (nthcdr < index << list ) << new-value )
.syne
.desc
The
.code nthcdr
function retrieves the n-th cons cell of a list, indexed from zero.
The
.meta index
parameter must be a non-negative integer. If
.meta index
specifies a nonexistent cons beyond the end of the list,
then
.code nthcdr
yields nil.
The following equivalences hold:

.cblk
  (nthcdr 0 list) <--> list
  (nthcdr 1 list) <--> (cdr list)
  (nthcdr 2 list) <--> (cddr list)
.cble

An
.code nthcdr
place designates the storage location which holds the n-th cell,
as indicated by the value of
.metn index .
Indices beyond the last cell of
.meta list
do not designate a valid place.
If
.meta list
is itself a place, then the zeroth index is permitted and the
resulting place denotes
.metn list .
Storing a value to
.cblk
.meti (nthcdr < 0 << list)
.cble
overwrites
.metn list .
Otherwise if
.meta list
isn't a syntactic place, then the zeroth index does not designate a valid
place;
.meta index
must have a positive value. A
.code nthcdr
place does not support deletion.

.TP* "Dialect Note:"
In Common Lisp,
.code nthcdr
is only a function, not an accessor;
.code nthcdr
forms do not denote places.

.coNP Accessors @, caar @, cadr @, cdar @, cddr ... @ cdddddr
.synb
.mets (caar << object )
.mets (cadr << object )
.mets (cdar << object )
.mets (cddr << object )
.mets ...
.mets (cdddr << object )
.mets (set (caar << object ) << new-value )
.mets (set (cadr << object ) << new-value )
.mets ...
.syne
.desc
The
.I a-d accessors
provide a shorthand notation for accessing two to five
levels deep into a cons-cell-based tree structure. For instance, the
the equivalent of the nested function call expression
.cblk
.meti (car (car (cdr << object )))
.cble
can be achieved using the single function call
.cblk
.meti (caadr << object ).
.cble
The symbol names of the a-d accessors are a generalization of the words
"car" and "cdr". They encode the pattern of
.code car
and
.code cdr
traversal of the structure using a sequence of the the letters
.code a
and
.code d
placed between
.code c
and
.codn r .
The traversal is encoded in right-to-left order, so that
.code cadr
indicates a traversal of the
.code cdr
link, followed by the
.codn car .
This order corresponds to the nested function call notation, which also
encodes the traversal right-to-left. The following diagram illustrates
the straightforward relationship:
.cblk
  (cdr (car (cdr x)))
    ^    ^    ^
    |   /     |
    |  /     /
    | / ____/
    || /
  (cdadr x)
.cble

\*(TL provides all possible a-d accessors up to five levels deep, from
.code caar
all the way through
.codn cdddddr .

Expressions involving a-d accessors are places. For example,
.code "(caddr x)"
denotes the same place as
.codn "(car (cddr x))" ,
and
.code "(cdadr x)"
denotes the same place as
.codn "(cdr (cadr x))" .

The a-d accessor places support deletion, with semantics derived from
the deletion semantics of the
.code car
and
.code cdr
places. For example,
.code "(del (caddr x))"
means the same as
.codn "(del (car (cddr x)))" .

.coNP Functions @ flatten and @ flatten*
.synb
.mets (flatten << list )
.mets (flatten* << list )
.syne
.desc
The
.code flatten
function produces a list whose elements are all of the
.cod2 non- nil
atoms contained in the structure of
.metn list .

The
.code flatten*
function
works like
.code flatten
except that it produces a lazy list. It can be used to lazily flatten an
infinite lazy structure.

.TP* Examples:
.cblk
  (flatten '(1 2 () (3 4))) -> (1 2 3 4)

  ;; equivalent to previous, since
  ;; nil is the same thing as ()
  (flatten '(1 2 nil (3 4))) -> (1 2 3 4)

  (flatten nil) -> nil

  (flatten '(((()) ()))) -> nil
.cble

.coNP Functions @ flatcar and @ flatcar*
.synb
.mets (flatcar << tree )
.mets (flatcar* << tree )
.syne
.desc
The
.code flatcar
function produces a list of all the atoms contained in the
tree structure
.metn tree ,
in the order in which they appear, when the structure is traversed
left to right.

This list includes those
.code nil
atoms which appear in
.code car
fields.

The list excludes
.code nil
atoms which appear in
.code cdr
fields.

The
.code flatcar*
function
works like
.code flatcar
except that it produces a lazy list. It can be used to lazily flatten an
infinite lazy structure.

.TP* Examples:
.cblk
  (flatcar '(1 2 () (3 4))) -> (1 2 nil 3 4)

  (flatcar '(a (b . c) d (e) (((f)) . g) (nil . z) nil . h))

  --> (a b c d e f g nil z nil h)
.cble

.coNP Function @ tree-find
.synb
.mets (tree-find < obj < tree << test-function )
.syne
.desc
The
.code tree-find
function searches
.meta tree
for an occurrence of
.metn obj .
Tree can be
any atom, or a cons. If
.meta tree
it is a cons, it is understood to be a proper
list whose elements are also trees.

The equivalence test is performed by
.meta test-function
which must take two
arguments, and has conventions similar to
.codn eq ,
.code eql
or
.codn equal .

.code tree-find
works as follows.  If
.meta tree
is equivalent to
.meta obj
under
.metn test-function ,
then
.code t
is returned to announce a successful finding.
If this test fails, and
.meta tree
is an atom,
.code nil
is returned immediately to
indicate that the find failed.  Otherwise,
.meta tree
is taken to be a proper list,
and tree-find is recursively applied to each element of the list in turn, using
the same
.meta obj
and
.meta test-function
arguments, stopping at the first element
which returns a
.cod2 non- nil
value.

.coNP Functions @, memq @ memql and @ memqual
.synb
.mets (memq < object << list )
.mets (memql < object << list )
.mets (memqual < object << list )
.syne
.desc
The
.codn memq ,
.code memql
and
.code memqual
functions search
.meta list
for a member
which is, respectively,
.codn eq ,
.code eql
or
.code equal
to
.metn object .
(See the
.codn eq ,
.code eql
and
.code equal
functions above.)

If no such element found,
.code nil
is returned.

Otherwise, that suffix of
.meta list
is returned whose first element
is the matching object.

.coNP Functions @ member and @ member-if
.synb
.mets (member < key < sequence >> [ testfun <> [ keyfun ]])
.mets (member-if < predfun < sequence <> [ keyfun ])
.syne
.desc
The
.code member
and
.code member-if
functions search through
.meta sequence
for an item which
matches a key, or satisfies a predicate function, respectively.

The
.meta keyfun
argument specifies a function which is applied to the elements
of the sequence to produce the comparison key. If this argument is omitted,
then the untransformed elements of the sequence themselves are examined.

The
.code member
function's
.meta testfun
argument specifies the test function which is
used to compare the comparison keys taken from the sequence to the search key.
If this argument is omitted, then the
.code equal
function is used.
If
.code member
does not find a matching element, it returns
.codn nil .
Otherwise it
returns the suffix of
.meta sequence
which begins with the matching element.

The
.code member-if
function's
.meta predfun
argument specifies a predicate function
which is applied to the successive comparison keys pulled from the sequence
by applying the key function to successive elements.  If no match is found,
then
.code nil
is returned, otherwise what is returned is the suffix of
.meta sequence
which begins with the matching element.

.coNP Functions @, rmemq @, rmemql @, rmemqual @ rmember and @ rmember-if
.synb
.mets (rmemq < object << list )
.mets (rmemql < object << list )
.mets (rmemqual < object << list )
.mets (rmember < key < sequence >> [ testfun <> [ keyfun ]])
.mets (rmember-if < predfun < sequence <> [ keyfun ])
.syne
.desc
These functions are counterparts to
.codn memq ,
.codn memql ,
.codn memqual ,
.code member
and
.code member-if
which look for the right-most
element which matches
.metn object ,
rather than for the left-most element.

.coNP Functions @ conses and @ conses*
.synb
.mets (conses << list )
.mets (conses* << list )
.syne
.desc
These functions return a list whose elements are the conses which make
up
.metn list .
The
.code conses*
function does this in a lazy way, avoiding the
computation of the entire list: it returns a lazy list of the conses of
.metn list .
The
.code conses
function computes the entire list before returning.

The input
.meta list
may be proper or improper.

The first cons of
.meta list
is that
.meta list
itself. The second cons is the rest
of the list, or
.cblk
.meti (cdr << list ).
.cble
The third cons is
.cblk
.meti (cdr (cdr << list ))
.cble
and so on.

.TP* Example:
.cblk
  (conses '(1 2 3)) -> ((1 2 3) (2 3) (3))
.cble

.TP* "Dialect Note:"

These functions are useful for simulating the
.code maplist
function found in other dialects like Common Lisp.

\*(TL's
.code "(conses x)"
can be expressed in Common Lisp as
.codn "(maplist #'identity x)" .

Conversely, the Common Lisp operation
.code "(maplist function list)"
can be computed in \*(TL as
.codn "(mapcar function (conses list))" .

More generally, the Common Lisp operation

.cblk
  (maplist function list0 list1 ... listn)
.cble

can be expressed as:

.cblk
  (mapcar function (conses list0)
                   (conses list1) ... (conses listn))
.cble

.SS* Association Lists

Association lists are ordinary lists formed according to a special convention.
Firstly, any empty list is a valid association list. A non-empty association
list contains only cons cells as the key elements. These cons cells are
understood to represent key/value associations, hence the name "association
list".

.coNP Function @ assoc
.synb
.mets (assoc < key << alist )
.syne
.desc
The
.code assoc
function searches an association list
.meta alist
for a cons cell whose
car field is equivalent to
.meta key
(with equality determined by the equal
function). The first such cons is returned. If no such cons is found,
.code nil
is returned.

.coNP Function @ assql
.synb
.mets (assql < key << alist )
.syne
.desc
The
.code assql
function is just like
.codn assoc ,
except that the equality test
is determined using the
.code eql
function rather than
.codn equal .

.coNP Function @ acons
.synb
.mets (acons < car < cdr << alist )
.syne
.desc
The
.code acons
function constructs a new alist by consing a new cons to the
front of
.metn alist .
The following equivalence holds:

.cblk
  (acons car cdr alist) <--> (cons (cons car cdr) alist)
.cble

.coNP Function @ acons-new
.synb
.mets (acons-new < car < cdr << alist )
.syne
.desc
The
.code acons-new
function searches
.metn alist ,
as if using the assoc function,
for an existing cell which matches the key provided by the car argument.
If such a cell exists, then its cdr field is overwritten with the
.meta cdr
argument, and then the
.meta alist
is returned. If no such cell exists, then
a new list is returned by adding a new cell to the input list consisting
of the
.meta car
and
.meta cdr
values, as if by the
.code acons
function.

.coNP Function @ aconsql-new
.synb
.mets (aconsql-new < car < cdr << alist )
.syne
.desc
This function is like
.codn acons-new ,
except that the
.code
eql
function is used
for equality testing. Thus, the list is searched for an existing cell
as if using the
.code assql
function rather than
.codn assoc .

.coNP Function @ alist-remove
.synb
.mets (alist-remove < alist << keys )
.syne
.desc
The
.code alist-remove
function takes association list
.meta alist
and produces a
duplicate from which cells matching the specified keys have been removed. The
.meta keys
argument is a list of the keys not to appear in the output list.

.coNP Function @ alist-nremove
.synb
.mets (alist-nremove < alist << keys )
.syne
.desc
The
.code alist-nremove
function is like
.codn alist-remove ,
but potentially destructive.
The input list
.meta alist
may be destroyed and its structural material re-used to
form the output list. The application should not retain references to the input
list.

.coNP Function @ copy-alist
.synb
.mets (copy-alist << alist )
.syne
.desc
The
.code copy-alist
function duplicates
.codn alist .
Unlike
.codn copy-list ,
which only duplicates list structure,
.code copy-alist
also duplicates each cons
cell of the input alist. That is to say, each element of the output list
is produced as if by the
.code copy-cons
function applied to the corresponding
element of the input list.

.SS* Property Lists
.coNP Function @ prop
.synb
.mets (prop < plist << key )
.syne
.desc
A property list a flat list of even length consisting of interleaved
pairs of property names (usually symbols) and their values (arbitrary
objects). An example property list is (:a 1 :b "two") which contains
two properties, :a having value 1, and :b having value "two".

The
.code prop
function searches property list
.meta plist
for key
.metn key .
If the key is found, then the value next to it is returned. Otherwise
.code nil
is returned.

It is ambiguous whether
.code nil
is returned due to the property not being
found, or due to the property being present with a
.code nil
value.

.SS* List Sorting
.coNP Function @ merge
.synb
.mets (merge < seq1 < seq2 >> [ lessfun <> [ keyfun ]])
.syne
.desc
The
.code merge
function merges two sorted sequences
.meta seq1
and
.meta seq2
into a single
sorted sequence. The semantics and defaulting behavior of the
.meta lessfun
and
.meta keyfun
arguments are the same as those of the sort function.

The sequence which is returned is of the same kind as
.metn seq1 .

This function is destructive of any inputs that are lists. If the output
is a list, it is formed out of the structure of the input lists.

.coNP Function @ multi-sort
.synb
.mets (multi-sort < columns < less-funcs <> [ key-funcs ])
.syne
.desc
The
.code multi-sort
function regards a list of lists to be the columns of a
database. The corresponding elements from each list constitute a record.
These records are to be sorted, producing a new list of lists.

The
.meta columns
argument supplies the list of lists which comprise the columns of
the database. The lists should ideally be of the same length. If the lists are
of different lengths, then the shortest list is taken to be the length of the
database. Excess elements in the longer lists are ignored, and do not appear in
the sorted output.

The
.meta less-funcs
argument supplies a list of comparison functions which are
applied to the columns. Successive functions correspond to successive
columns. If
.meta less-funcs
is an empty list, then the sorted database will
emerge in the original order. If
.meta less-funcs
contains exactly one function,
then the rows of the database is sorted according to the first column. The
remaining columns simply follow their row. If
.meta less-funcs
contains more than
one function, then additional columns are taken into consideration if the items
in the previous columns compare
.codn equal .
For instance if two elements from column
one compare
.codn equal ,
then the corresponding second column elements are compared
using the second column comparison function.

The optional
.meta key-funcs
argument supplies transformation functions through
which column entries are converted to comparison keys, similarly to the single
key function used in the sort function and others.  If there are more key
functions than less functions, the excess key functions are ignored.

.SS* Lazy Lists and Lazy Evaluation
.coNP Function @ make-lazy-cons
.synb
.mets (make-lazy-cons << function )
.syne
.desc
The function
.code make-lazy-cons
makes a special kind of cons cell called a lazy
cons, or lcons.  Lazy conses are useful for implementing lazy lists.

Lazy lists are lists which are not allocated all at once. Rather,
their elements materialize when they are accessed, like
magic stepping stones appearing under one's feet out of thin air.

A lazy cons has
.code car
and
.code cdr
fields like a regular cons, and those
fields are initialized to
.code nil
when the lazy cons is created. A lazy cons also
has an update function, the one which is provided as the
.meta function
argument to
.codn make-lazy-cons .

When either the
.code car
and
.code cdr
fields of a cons are accessed for the first time,
the function is automatically invoked first. That function has the opportunity
to initialize the
.code car
and
.code cdr
fields. Once the function is called, it is removed
from the lazy cons: the lazy cons no longer has an update function.

To continue a lazy list, the function can make another call to
.code make-lazy-cons
and install the resulting cons as the
.code cdr
of the lazy cons.

.TP* Example:

.cblk
  ;;; lazy list of integers between min and max
  (defun integer-range (min max)
    (let ((counter min))
      ;; min is greater than max; just return empty list,
      ;; otherwise return a lazy list
      (if (> min max)
        nil
        (make-lazy-cons
          (lambda (lcons)
            ;; install next number into car
            (rplaca lcons counter)
            ;; now deal wit cdr field
            (cond
              ;; max reached, terminate list with nil!
              ((eql counter max)
               (rplacd lcons nil))
              ;; max not reached: increment counter
              ;; and extend with another lazy cons
              (t
                (inc counter)
                (rplacd lcons (make-lazy-cons
                                (lcons-fun lcons))))))))))
.cble

.coNP Function @ lconsp
.synb
.mets (lconsp << value )
.syne
.desc
The
.code lconsp
function returns
.code t
if
.meta value
is a lazy cons cell. Otherwise
it returns
.codn nil ,
even if
.meta value
is an ordinary cons cell.

.coNP Function @ lcons-fun
.synb
.mets (lcons-fun << lazy-cons )
.syne
.desc
The
.code lcons-fun
function retrieves the update function of a lazy cons.
Once a lazy cons has been accessed, it no longer has an update function
and
.code lcons-fun
returns
.codn nil .
While the update function of a lazy cons is
executing, it is still accessible. This allows the update function
to retrieve a reference to itself and propagate itself into
another lazy cons (as in the example under
.codn make-lazy-cons ).

.coNP Macro @ lcons
.synb
.mets (lcons < car-expression << cdr-expression )
.syne
.desc
The
.code lcons
macro simplifies the construction of structures based on lazy conses.
Syntactically, it resembles the
.code cons
function. However, the arguments are expressions rather than values.
The macro generates code which, when evaluated, immediately produces
a lazy cons. The expressions
.meta car-expression
and
.meta cdr-expression
are not immediately evaluated. Rather, when either the
.code car
or
.code cdr
field of the lazy cons cell is accessed, these expressions are both
evaluated at that time, in the order that they appear in the
.code lcons
expression, and in the original lexical scope in which that
expression was evaluated. The return values of these expressions
are used, respectively, to initialize the corresponding fields
of the lazy cons.

Note: the
.code lcons
macro may be understood in terms of the following reference
implementation, as a syntactic sugar combining the
.code make-lazy-cons
constructor with a lexical closure provided by a
.code lambda
function:

.cblk
  (defmacro lcons (car-form cdr-form)
    (let ((lc (gensym)))
       ^(make-lazy-cons (lambda (,lc)
                          (rplaca ,lc ,car-form)
                          (rplacd ,lc ,cdr-form)))))
.cble

.TP* Example:

.cblk
  ;; Given the following function ...

  (defun fib-generator (a b)
    (lcons a (fib-generator b (+ a b))))

  ;; ... the following function call generates the Fibonacci
  ;; sequence as an infinite lazy list.

  (fib-generator 1 1) -> (1 1 2 3 5 8 13 ...)
.cble

.coNP Functions @ lazy-stream-cons and @ get-lines
.synb
.mets (lazy-stream-cons << stream )
.mets (get-lines <> [ stream ])
.syne
.desc
The
.code lazy-stream-cons
and
.code get-lines
functions are synonyms, except that the
.meta stream
argument is optional in
.code get-lines
and defaults to
.codn *stdin* .
Thus, the following
description of
.code lazy-stream-cons
also applies to
.codn get-lines .

The
.code lazy-stream-cons
returns a lazy cons which generates a lazy list based on
reading lines of text from input stream
.metn stream ,
which form the elements of
the list. The
.code get-line
function is called on demand to add elements to the
list.

The
.code lazy-stream-cons
function itself makes the first call to
.code get-line
on the stream. If this returns
.codn nil ,
then the stream is closed and
.code nil
is
returned. Otherwise, a lazy cons is returned whose update function will install
that line into the
.code car
field of the lazy cons, and continue the lazy list
by making another call to
.codn lazy-stream-cons ,
installing the result into the
.code cdr
field.

.code lazy-stream-cons
inspects the real-time property of a stream
as if by the
.code real-time-stream-p
function. This determines which of two
styles of lazy list are returned. For an ordinary (non-real-time) stream,
the lazy list treats the end-of-file condition accurately: an empty
file turns into the empty list
.codn nil ,
a one line file into a one-element
list which contains that line and so on. This accuracy requires one
line of lookahead which is not acceptable in real-time streams, and
so a different type of lazy list is used, which generates an extra
.code nil
item after the last line. Under this type of lazy list, an empty input stream
translates to the list
.codn (nil) ;
a one-line stream translates to
.cblk
("line" nil)
.cble
and so forth.

.coNP Macro @ delay
.synb
.mets (delay << expression )
.syne
.desc
The delay operator arranges for the delayed (or "lazy") evaluation of
.metn expression .
This means that the expression is not evaluated immediately.
Rather, the delay expression produces a promise object.

The promise object can later be passed to the
.code force
function (described
later in this document). The force function will trigger the evaluation
of the expression and retrieve the value.

The expression is evaluated in the original scope, no matter where
the
.code force
takes place.

The expression is evaluated at most once, by the first call to
.codn force .
Additional calls to
.code force
only retrieve a cached value.

.TP* Example:

.cblk
  ;; list is popped only once: the value is computed
  ;; just once when force is called on a given promise
  ;; for the first time.

  (defun get-it (promise)
    (format t "*list* is ~s\en" *list*)
    (format t "item is ~s\en" (force promise))
    (format t "item is ~s\en" (force promise))
    (format t "*list* is ~s\en" *list*))

  (defvar *list* '(1 2 3))

  (get-it (delay (pop *list*)))

  Output:

  *list* is (1 2 3)
  item is 1
  item is 1
  *list* is (2 3)
.cble

.coNP Accessor @ force
.synb
.mets (force << promise )
.mets (set (force << promise ) << new-value )
.syne
.desc
The
.code force
function accepts a promise object produced by the
.code delay
macro.
The first time
.code force
is invoked, the
.meta expression
which was wrapped inside
.meta promise
by the
.code delay
macro is evaluated (in its original lexical environment, regardless of where in
the program the
.code force
call takes place). The value of
.meta expression
is
cached inside
.meta promise
and returned, becoming the return value of the
.code force
function call.  If the
.code force
function is invoked additional times on
the same promise, the cached value is retrieved.

A
.code force
form is a syntactic place, denoting the value cache location within
.metn promise .

Storing a value in a
.code force
place causes future accesses to the
.meta promise
to return that value.

If the promise had not yet been forced, then
storing a value into it prevents that from ever happening. The
delayed
.meta expression
will never be evaluated.

If, while a promise is being forced, the evaluation of
.meta expression
itself causes an assignment to the promise, it is not specified whether
the promise will take on the value of
.meta expression
or the assigned value.

.coNP Function @ promisep
.synb
.mets (promisep << object )
.syne
.desc
The
.code promisep
function returns
.code t
if
.meta object
is a promise object: an object created by the
.code delay
macro.  Otherwise it returns
.codn nil .

Note: promise objects are conses. The
.code typeof
function applied to a promise returns
.codn cons .

.coNP Macro @ mlet
.synb
.mets (mlet >> ({ sym | >> ( sym << init-form )}*) << body-form *)
.syne
.desc
The
.code mlet
macro ("magic let" or "mutual let") implements a variable binding construct
similar to
.code let
and
.codn let* .

Under
.codn mlet ,
the scope of the bindings of the
.meta sym
variables extends over the
.metn init-form -s,
as well as the
.metn body-form -s.

Unlike the
.code let*
construct, each
.meta init-form
has each
.meta sym
in scope. That is to say, an
.meta init-form
can refer not only to previous variables, but also to later variables
as well as to its own variable.

The variables are not initialized until their values are accessed for
the first time. Any
.meta sym
whose value is not accessed is not initialized.

Furthermore, the evaluation of each
.meta init-form
does not take place until the time when its value is needed
to initialize the associated
.metn sym .
This evaluation takes place once. If a given
.meta sym
is not accessed during the evaluation of the
.code mlet
construct, then its
.meta init-form
is never evaluated.

The bound variables may be assigned. If, before initialization, a variable is
updated in such a way that its prior value is not needed, it is unspecified
whether initialization takes place, and thus whether its
.meta init-form
is evaluated.

Direct circular references are erroneous and are diagnosed. This takes
place when the macro-expanded form is evaluated, not during the
expansion of
.codn mlet .

.TP* Examples:

.cblk
  ;; Dependent calculations in arbitrary order
  (mlet ((x (+ y 3))
         (z (+ x 1))
         (y 4))
    (+ z 4))  -->  12

  ;; Error: circular reference:
  ;; x depends on y, y on z, but z on x again.
  (mlet ((x (+ y 1))
         (y (+ z 1))
         (z (+ x 1)))
    z)

  ;; Okay: lazy circular reference because lcons is used
  (mlet ((list (lcons 1 list)))
    list)  -->  (1 1 1 1 1 ...) ;; circular list
.cble

In the last example, the
.code list
variable is accessed for the first time in the body of the 
.code mlet
form. This causes the evaluation of the
.code lcons
form. This form evaluates its arguments lazily, which means that it
is not a problem that
.code list
is not yet initialized. The form produces a lazy cons, which is then used
to initialize
.code list.
When the
.code car
or
.code cdr
fields of the lazy cons are accessed, the
.code list
expression in the
.code lcons
argument is accessed. By that time, the variable is initialized
and holds the lazy cons itself, which creates the circular reference,
and a circular list.

.coNP Functions @, generate @ giterate and @ ginterate
.synb
.mets (generate < while-fun << gen-fun )
.mets (giterate < while-fun < gen-fun <> [ value ])
.mets (ginterate < while-fun < gen-fun <> [ value ])
.syne
.desc
The
.code generate
function produces a lazy list which dynamically produces items
according to the following logic.

The arguments to
.code generate
are functions which do not take any arguments.  The
return value of generate is a lazy list.

When the lazy list is accessed, for instance with the functions car and cdr, it
produces items on demand. Prior to producing each item,
.meta while-fun
is
called. If it returns a true Boolean value (any value other than
.codn nil ),
then
the
.meta gen-fun
function is called, and its return value is incorporated as
the next item of the lazy list. But if
.meta while-fun
yields
.codn nil ,
then the lazy list immediately terminates.

Prior to returning the lazy list, generate invokes the
.meta while-fun
one time.
If
.code while-fun
yields
.codn nil ,
then
.code generate
returns the empty list
.code nil
instead of a lazy list. Otherwise, it instantiates a lazy list, and invokes the
.code gen-func
to populate it with the first item.

The
.code giterate
function is similar to
.codn generate ,
except that
.meta while-fun
and
.meta gen-fun
are functions of one argument rather than functions of
no arguments. The optional
.meta value
argument defaults to
.code nil
and is threaded through the function calls. That is to say, the lazy
list returned is
.cblk
.meti >> ( value >> [ gen-fun << value ] >> [ gen-fun >> [ gen-fun << value ]] ...).
.cble

The lazy list terminates when a value fails to satisfy
.metn while-fun .
That is to say, prior to generating each value, the lazy list tests
the value using
.metn while-fun .
If that function returns
.codn nil ,
then the item is not added, and the sequence terminates.

Note:
.code giterate
could be written in terms of
.code generate
like this:

.cblk
  (defun giterate (w g v)
     (generate (lambda () [w v])
               (lambda () (prog1 v (set v [g v])))))
.cble

The
.code ginterate
function is a variant of
.code giterate
which includes the test-failing item in the generated sequence.
That is to say
.code ginterate
generates the next value and adds it to the lazy list.
The value is then tested using
.metn while-fun .
If that function returns
.codn nil ,
then the list is terminated, and no more items are produced.

.TP* Example:

.cblk
  (giterate (op > 5) (op + 1) 0) -> (0 1 2 3 4)
  (ginterate (op > 5) (op + 1) 0) -> (0 1 2 3 4 5)
.cble

.coNP Function @ expand-right
.synb
.mets (expand-right < gen-fun << value )
.syne
.desc
The
.code expand-right
function is a complement to
.codn reduce-right ,
with lazy semantics.

The
.meta gen-fun
parameter is a function, which must accept a single argument,
and return either a cons pair
or
.codn nil .

The
.meta value
parameter is any value.

The first call to
.meta gen-fun
receives
.metn value .

The return value is interpreted as follows. If
.meta gen-fun
returns a cons cell pair
.cblk
.meti >> ( elem . << next )
.cble
then
.meta elem
specifies the element to be added to the lazy list,
and
.meta next
specifies the value to be passed to the next call
to
.metn gen-fun .
If
.meta gen-fun
returns
.code nil
then the lazy list ends.

.TP* Examples:

.cblk
  ;; Count down from 5 to 1 using explicit lambda
  ;; for gen-fun:

  (expand-right
    (lambda (item)
      (if (zerop item) nil
        (cons item (pred item))))
    5)
  --> (5 4 3 2 1)

  ;; Using functional combinators:
  [expand-right [iff zerop nilf [callf cons identity pred]] 5]
  --> (5 4 3 2 1)

  ;; Include zero:
  [expand-right
    [iff null
       nilf
       [callf cons identity [iff zerop nilf pred]]] 5]
  --> (5 4 3 2 1 0)
.cble

.coNP Functions @ expand-left and @ nexpand-left
.synb
.mets (expand-left < gen-fun << value )
.mets (nexpand-left < gen-fun << value )
.syne
.desc
The
.code expand-left
function is a companion to
.codn expand-right .

Unlike
.codn expand-right ,
it has eager semantics: it calls
.code gen-fun
repeatedly and accumulates an output list, not returning
until
.code gen-fun
returns
.codn nil .

The semantics is as follows.
.code expand-left
initializes an empty accumulation list. Then
.meta gen-fun
is called, with
.meta value
as its argument.

If
.meta gen-fun
it returns a cons cell, then the
.code car
of that cons cell is pushed onto the accumulation list,
and the procedure is repeated:
.meta gen-fun
is called again, with
.code cdr
taking the place of
.meta value.

If
.meta gen-fun
returns
.codn nil ,
then the accumulation list is returned.

If the expression
.code "(expand-right f v)"
produces a terminating list, then the following equivalence holds:

.cblk
  (expand-left f v) <--> (reverse (expand-right f v))
.cble

Of course, the equivalence cannot hold for arguments to
.code expand-left
which produce an infinite list.

The
.code nexpand-left
function is a destructive version of
.codn expand-left .

The list returned by
.code nexpand-left
is composed of the cons cells returned by
.code gen-fun
whereas the list returned by
.code expand-left
is composed of freshly allocated cons cells.

.coNP Function @ repeat
.synb
.mets (repeat < list <> [ count ])
.syne
.desc
If
.meta list
is empty, then repeat returns an empty list.

If
.meta count
is omitted, the
.code repeat
function produces an infinite lazy list
formed by catenating together copies of
.metn list .

If
.meta count
is specified and is zero or negative, then an empty list is
returned.

Otherwise a list is returned consisting of
.meta count
repetitions of
.meta list
catenated together.

.coNP Function @ pad
.synb
.mets (pad < sequence < object <> [ count ])
.syne
.desc
The
.code pad
function produces a lazy list which consists of all of the
elements of
.meta sequence
followed by repetitions of
.metn object .

If
.meta count
is omitted, then the repetition of
.meta object
is infinite. Otherwise the specified number of repetitions
occur.

Note that
.meta sequence
may be a lazy list which is infinite. In that case, the repetitions
of
.meta object
will never occur.

.coNP Function @ weave
.synb
.mets (weave <> { sequence }*)
.syne
.desc
The
.code weave
function interleaves elements from the sequences given as arguments.

If called with no arguments, it returns the empty list.

If called with a single sequence, it returns the elements of that sequence
as a new lazy list.

When called with two or more sequences,
.code
weave
returns a lazy list which draws elements from the sequences in a round-robin
fashion, repeatedly scanning the sequences from left to right, and
taking an item from each one, removing it from the sequence.
Whenever a sequence runs out of items, it is deleted; the weaving then
continues with the remaining sequences. The weaved sequence terminates
when all sequences are eliminated. (If at least one of the sequences
is an infinite lazy list, then the weaved sequence is infinite.)

.TP* Examples:

.cblk
  ;; Weave negative integers with positive ones:
  (weave (range 1) (range -1 : -1)) -> (1 -1 2 -2 3 -3 ...)

  (weave "abcd" (range 1 3) '(x x x x x x x))
  --> (#\ea 1 x #\eb 2 x #\ec 3 x #\ed x x x x)
.cble

.coNP Macros @ gen and @ gun
.synb
.mets (gen < while-expression << produce-item-expression )
.mets (gun << produce-item-expression )
.syne
.desc
The
.code gen
macro operator produces a lazy list, in a manner similar to the
.code generate
function. Whereas the
.code generate
function takes functional arguments,
the
.code gen
operator takes two expressions, which is often more convenient.

The return value of
.code gen
is a lazy list. When the lazy list is accessed, for
instance with the functions
.code car
and
.codn cdr ,
it produces items on demand. Prior to
producing each item, the
.meta while-expression
is evaluated, in its original
lexical scope.  If the expression yields a
.cod2 non- nil
value, then
.meta produce-item-expression
is evaluated, and its return value is incorporated as
the next item of the lazy list. If the expression yields
.codn nil ,
then the lazy list immediately terminates.

The
.code gen
operator itself immediately evaluates
.meta while-expression
before
producing the lazy list. If the expression yields
.codn nil ,
then the operator
returns the empty list
.codn nil .
Otherwise, it instantiates the lazy list and
invokes the
.meta produce-item-expression
to force the first item.

The
.code gun
macro similarly creates a lazy list according to the following
rules. Each successive item of the lazy list is obtained as a result of
evaluating
.metn produce-item-expression .
However, when
.meta produce-item-expression
yields
.codn nil ,
then the list terminates (without adding that
.code nil
as an item).

Note 1: the form
.code gun
can be implemented as a macro-expanding to
an instance of the
.code gen
operator, like this:

.cblk
  (defmacro gun (expr)
    (let ((var (gensym)))
      ^(let (,var)
         (gen (set ,var ,expr)
              ,var))))
.cble

This exploits the fact that the
.code set
operator returns the value that is
assigned, so the set expression is tested as a condition by
.codn gen ,
while having the side effect of storing the next item temporarily
in a hidden variable.

In turn,
.code gen
can be implemented as a macro expanding to some
.code lambda
functions which are passed to the
.code generate
function:

.cblk
  (defmacro gen (while-expr produce-expr)
    ^(generate (lambda () ,while-expr) (lambda () ,produce-expr)))
.cble

Note 2:
.code gen
can be considered as an acronym for Generate, testing Expression
before Next item, whereas
.code gun
stands for Generate Until Null.

.TP* Example:

.cblk
  ;; Make a lazy list of integers up to 1000
  ;; access and print the first three.
  (let* ((counter 0)
         (list (gen (< counter 1000) (inc counter))))
    (format t "~s ~s ~s\en" (pop list) (pop list) (pop list)))

  Output:
  1 2 3
.cble

.coNP Functions @ range and @ range*
.synb
.mets (range >> [ from >> [ to <> [ step ]]])
.mets (range* >> [ from >> [ to <> [ step ]]])
.syne
.desc
The
.code range
and
.code range*
functions generate a lazy sequence of integers, with a
fixed step between successive values.

The difference between
.code range
and
.code range*
is that
.code range*
excludes the endpoint.
For instance
.code "(range 0 3)"
generates the list
.codn "(0 1 2 3)" ,
whereas
.code "(range* 0 3)"
generates
.codn "(0 1 2)" .

All arguments are optional. If the
.meta step
argument is omitted, then it defaults
to
.codn 1 :
each value in the sequence is greater than the previous one by
.codn 1 .
Positive or negative step sizes are allowed. There is no check for a step size
of zero, or for a step direction which cannot meet the endpoint.

The
.meta to
argument specifies the endpoint value, which, if it occurs in the
sequence, is excluded from it by the
.code range*
function, but included by the range
function. If
.meta to
is missing, or specified as
.codn nil ,
then there is no endpoint,
and the sequence which is generated is infinite, regardless of
.metn step .

If
.meta from
is omitted, then the sequence begins at zero, otherwise
.meta from
must be an integer which specifies the initial value.

The sequence stops if it reaches the endpoint value (which is included in the
case of
.codn range ,
and excluded in the case of
.codn range *).
However, a sequence with a stepsize greater than
.code 1
or less than
.code -1
might step over the endpoint value, and
therefore never attain it. In this situation, the sequence also stops, and the
excess value which surpasses the endpoint is excluded from the sequence.

.SS* Ranges
.coNP Function @ rcons
.synb
.mets (rcons < from << to )
.syne
.desc
The
.code rcons
function constructs a range object which holds the values
.meta from
and
.metn to .

Though range objects are effectively binary cells like conses, they are atoms.
They also aren't considered sequences, nor are they structures.

Range objects are used for indicating numeric ranges, such as substrings of
lists, arrays and strings. The dotdot notation serves as a syntactic sugar for
.codn rcons .
The syntax
.code a..b
denotes the expression
.codn "(rcons a b)" .

Note that ranges are immutable, meaning that it is not possible to
replace the values in a range.

.coNP Function @ rangep
.synb
.mets (rangep << value )
.syne
.desc
The
.code rangep
function returns
.code t
if
.meta value
is a range. Otherwise it returns
.codn nil .

.coNP Functions @ from and @ to
.synb
.mets (from << range )
.mets (to << range )
.syne
.desc
The
.code from
and
.code to
functions retrieve, respectively, the from and to fields
of a range.

Note that these functions are not accessors, which is because
ranges are immutable.

.SS* Characters and Strings
.coNP Function @ mkstring
.synb
.mets (mkstring < length << char )
.syne
.desc
The
.code mkstring
function constructs a string object of a length specified
by the
.meta length
parameter.  Every position in the string is initialized
with
.metn char ,
which must be a character value.

.coNP Function @ copy-str
.synb
.mets (copy-str << string )
.syne
.desc
The
.code copy-str
function constructs a new string whose contents are identical
to
.metn string .

If
.meta string
is a lazy string, then a lazy string is constructed with the
same attributes as
.metn string .
The new lazy string has its own copy of the prefix portion of
.meta string
which has been forced so far. The unforced list and separator
string are shared between
.meta string
and the newly constructed lazy string.

.coNP Function @ upcase-str
.synb
.mets (upcase-str << string )
.syne
.desc
The
.code upcase-str
function produces a copy of
.meta string
such that all lower-case
characters of the English alphabet are mapped to their upper case counterparts.

.coNP Function @ downcase-str
.synb
.mets (downcase-str << string )
.syne
.desc
The
.code downcase-str
function produces a copy of
.meta string
such that
all upper case characters of the English alphabet are mapped to their
lower case counterparts.

.coNP Function @ string-extend
.synb
.mets (string-extend < string << tail )
.syne
.desc
The
.code string-extend
function destructively increases the length of
.metn string ,
which must be an ordinary dynamic string.  It is an error to invoke this
function on a literal string or a lazy string.

The
.meta tail
argument can be a character, string or integer. If it is a string or
character, it specifies material which is to be added to the end of the string:
either a single character or a sequence of characters. If it is an integer, it
specifies the number of characters to be added to the string.

If
.meta tail
is an integer, the newly added characters have indeterminate contents.
The string appears to be the original one because of an internal terminating
null character remains in place, but the characters beyond the terminating zero
are indeterminate.

.coNP Function @ stringp
.synb
.mets (stringp << obj )
.syne
.desc
The
.code stringp
function returns t if
.meta obj
is one of the several
kinds of strings. Otherwise it returns
.codn nil .

.coNP Function @ length-str
.synb
.mets (length-str << string )
.syne
.desc
The
.code length-str
function returns the length
.meta string
in characters.  The argument must be a string.

.coNP Function @ search-str
.synb
.mets (search-str < haystack < needle >> [ start <> [ from-end ]])
.syne
.desc
The
.code search-str
function finds an occurrence of the string
.meta needle
inside
the
.meta haystack
string and returns its position. If no such occurrence exists,
it returns
.codn nil .

If a
.meta start
argument is not specified, it defaults to zero. If it is
a non-negative integer, it specifies the starting character position for
the search.  Negative values of
.meta start
indicate positions from the end of the
string, such that
.code -1
is the last character of the string.

If the
.meta from-end
argument is specified and is not
.codn nil ,
it means
that the search is conducted right-to-left. If multiple matches are possible,
it will find the rightmost one rather than the leftmost one.

.coNP Function @ search-str-tree
.synb
.mets (search-str-tree < haystack < tree >> [ start <> [ from-end ]])
.syne
.desc
The
.code search-str-tree
function is similar to
.codn search-str ,
except that instead of
searching
.meta haystack
for the occurrence of a single needle string, it searches
for the occurrence of numerous strings at the same time.  These search strings
are specified, via the
.meta tree
argument, as an arbitrarily structured tree whose
leaves are strings.

The function finds the earliest possible match, in the given search direction,
from among all of the needle strings.

If
.meta tree
is a single string, the semantics is equivalent to
.codn search-str .

.coNP Function @ match-str
.synb
.mets (match-str < bigstring < littlestring <> [ start ])
.syne
.desc
Without the
.meta start
argument, the
.code match-str
function determines whether
.meta littlestring
is a prefix of
.metn bigstring ,
returning a
.code t
or
.code nil
indication.

If the
.meta start
argument is specified, and is a non-negative integer, then the
function tests whether
.meta littlestring
matches a prefix of that portion of
.meta bigstring
which starts at the given position.

If the
.meta start
argument is a negative integer, then
.code match-str
determines
whether
.meta littlestring
is a suffix of
.metn bigstring ,
ending on that position
of bigstring, where
.code -1
denotes the last character of
.metn bigstring ,
.code -2
the second last one and so on.

If
.meta start
is
.codn -1 ,
then this corresponds to testing whether
.meta littlestring
is a suffix of
.metn bigstring .

.coNP Function @ match-str-tree
.synb
.mets (match-str-tree < bigstring < tree <> [ start ])
.syne
.desc
The
.code match-str-tree
function is a generalization of match-str which matches
multiple test strings against
.meta bigstring
at the same time. The value
reported is the longest match from among any of the strings.

The strings are specified as an arbitrarily shaped tree structure which has
strings at the leaves.

If
.meta tree
is a single string atom, then the function behaves
exactly like match-str.

.coNP Function @ sub-str
.synb
.mets (sub-str < string >> [ from <> [ to ]])
.syne
.desc
The
.code sub-str
function is like the more generic function
.codn sub ,
except that it
operates only on strings.  For a description of the arguments and semantics,
refer to the
.code sub
function.

.coNP Function @ replace-str
.synb
.mets (replace-str < string < item-sequence >> [ from <> [ to ]])
.syne
.desc
The
.code replace-str
function is like the
.code replace
function, except that the first
argument must be a string.

For a description of the arguments, semantics and return value, refer to the
.code replace
function.

.coNP Function @ cat-str
.synb
.mets (cat-str < string-list <> [ sep-string ])
.syne
.desc
The
.code cat-str
function catenates a list of strings given by
.meta string-list
into a
single string.  The optional
.meta sep-string
argument specifies a separator string
which is interposed between the catenated strings.

.coNP Function @ split-str
.synb
.mets (split-str < string << sep )
.syne
.desc
The
.code split-str
function breaks the
.meta string
into pieces, returning a list
thereof. The
.meta sep
argument must be either a string or a regular expression.
It specifies the separator character sequence within
.metn string .

All non-overlapping matches for
.meta sep
within
.meta string
are identified in left
to right order, and are removed from
.metn string .
The string is broken into pieces
according to the gaps left behind by the removed separators, and a list
of the remaining pieces is returned.

If
.meta sep
is the empty string, then the separator pieces removed from the
string are considered to be the empty strings between its
characters. In this case, if
.meta string
is of length one or zero, then it is considered to have no such pieces, and a
list of one element is returned containing the original string.

If a match for
.meta sep
is not found in the string at all, then the string is not
split at all: a list of one element is returned containing the original
string.

If
.meta sep
matches the entire string, then a list of two empty strings is
returned, except in the case that the original string is empty, in which case a
list of one element is returned, containing the empty string.

Whenever two adjacent matches for
.meta sep
occur, they are considered separate
cuts with an empty piece between them.

This operation is nondestructive:
.meta string
is not modified in any way.

Note: To split a string into pieces of length one such that an empty string
produces
.code nil
rather than
.codn ("") ,
use the
.cblk
.meti (tok-str < string #/./)
.cble
pattern.

.coNP Function @ split-str-set
.synb
.mets (split-str-set < string << set )
.syne
.desc
The
.code split-str-set
function breaks the
.meta string
into pieces, returning a list
thereof. The
.meta set
argument must be a string. It specifies a set of
characters.  All occurrences of any of these characters within
.meta string
are
identified, and are removed from
.metn string .
The string is broken into pieces
according to the gaps left behind by the removed separators.

Adjacent occurrences of characters from
.meta set
within
.meta string
are considered to
be separate gaps which come between empty strings.

This operation is nondestructive:
.meta string
is not modified in any way.

.coNP Functions @ tok-str and @ tok-where
.synb
.mets (tok-str < string < regex <> [ keep-between ])
.mets (tok-where < string << regex )
.syne
.desc
The
.code tok-str
function searches
.meta string
for tokens, which are defined as
substrings of
.meta string
which match the regular expression
.meta regex
in the
longest possible way, and do not overlap. These tokens are extracted from the
string and returned as a list.

Whenever
.meta regex
matches an empty string, then an empty token is returned, and
the search for another token within
.meta string
resumes after advancing by one
character position. So for instance,
.cblk
(tok-str "abc" #/a?/)
.cble
returns the
.cblk
("a" "" "" "").
.cble
After the token
.str "a"
is extracted from a non-empty match
for the regex, the regex is considered to match three more times: before the
.strn "b" ,
between
.str "b"
and
.strn "c" ,
and after the
.strn "c" .

If the
.meta keep-between
argument is specified, and is not
.codn nil ,
then the behavior
of
.code tok-str
changes in the following way. The pieces of
.meta string
which are
skipped by the search for tokens are included in the output. If no token is
found in
.metn string ,
then a list of one element is returned, containing
.metn string .
Generally, if N tokens are found, then the returned list consists of 2N + 1
elements. The first element of the list is the (possibly empty) substring which
had to be skipped to find the first token. Then the token follows. The next
element is the next skipped substring and so on. The last element is the
substring of
.meta string
between the last token and the end.

The
.code tok-where
function works similarly to
.codn tok-str ,
but instead of returning
the extracted tokens themselves, it returns a list of the character position
ranges within
.meta string
where matches for
.meta regex
occur. The ranges
are pairs of numbers, represented as cons cells, where the first number
of the pair gives the starting character position, and the second number
is one position past the end of the match.  If a match is empty, then the
two numbers are equal.

The tok-where function does not support the
.meta keep-between
parameter.

.coNP Function @ list-str
.synb
.mets (list-str << string )
.syne
.desc
The
.code list-str
function converts a string into a list of characters.

.coNP Function @ trim-str
.synb
.mets (trim-str << string )
.syne
.desc
The
.code trim-str
function produces a copy of
.meta string
from which leading and
trailing whitespace is removed. Whitespace consists of spaces, tabs,
carriage returns, linefeeds, vertical tabs and form feeds.

.coNP Function @ chrp
.synb
.mets (chrp << obj )
.syne
.desc
Returns
.code t
if
.meta obj
is a character, otherwise nil.

.coNP Function @ chr-isalnum
.synb
.mets (chr-isalnum << char )
.syne
.desc
Returns
.code t
if
.meta char
is an alpha-numeric character, otherwise nil. Alpha-numeric
means one of the upper or lower case letters of the English alphabet found in
ASCII, or an ASCII digit. This function is not affected by locale.

.coNP Function @ chr-isalpha
.synb
.mets (chr-isalpha << char )
.syne
.desc
Returns
.code t
if
.meta char
is an alphabetic character, otherwise
.codn nil .
Alphabetic
means one of the upper or lower case letters of the English alphabet found in
ASCII. This function is not affected by locale.

.coNP Function @ chr-isascii
.synb
.mets (chr-isalpha << char )
.syne
.desc
This function returns
.code t
if the code of character
.meta char
is in the range 0 to 127 inclusive. For characters outside of this range, it
returns
.codn nil .

.coNP Function @ chr-iscntrl
.synb
.mets (chr-iscntrl << char )
.syne
.desc
This function returns
.code t
if the character
.meta char
is a character whose code
ranges from 0 to 31, or is 127. In other words, any non-printable ASCII
character. For other characters, it returns
.codn nil .

.coNP Functions @ chr-isdigit and @ chr-digit
.synb
.mets (chr-isdigit << char )
.mets (chr-digit << char )
.syne
.desc
If
.meta char
is is an ASCII decimal digit character,
.code chr-isdigit
returns the value
.code t
and
.code chr-digit
returns the integer value corresponding to that digit character,
a value in the range 0 to 9.  Otherwise, both functions return
.codn nil .

.coNP Function @ chr-isgraph
.synb
.mets (chr-isgraph << char )
.syne
.desc
This function returns
.code t
if
.meta char
is a non-space printable ASCII character.
It returns nil if it is a space or control character.

It also returns nil for non-ASCII characters: Unicode characters with a code
above 127.

.coNP Function @ chr-islower
.synb
.mets (chr-islower << char )
.syne
.desc
This function returns
.code t
if
.meta char
is an ASCII lower case letter. Otherwise it returns
.codn nil .

.coNP Function @ chr-isprint
.synb
.mets (chr-isprint << char )
.syne
.desc
This function returns
.code t
if
.meta char
is an ASCII character which is not a
control character.  It also returns
.code nil
for all non-ASCII characters: Unicode
characters with a code above 127.

.coNP Function @ chr-ispunct
.synb
.mets (chr-ispunct << char )
.syne
.desc
This function returns
.code t
if
.meta char
is an ASCII character which is not a
control character.  It also returns nil for all non-ASCII characters: Unicode
characters with a code above 127.

.coNP Function @ chr-isspace
.synb
.mets (chr-isspace << char )
.syne
.desc
This function returns
.code t
if
.meta char
is an ASCII whitespace character: any of the
characters in the set
.codn #\espace ,
.codn #\etab ,
.codn #\elinefeed ,
.codn #\enewline ,
.codn #\ereturn ,
.code #\evtab
and
.codn #\epage .
For all other characters, it returns
.codn nil .

.coNP Function @ chr-isblank
.synb
.mets (chr-isblank << char )
.syne
.desc
This function returns
.code t
if
.meta char
is a space or tab: the character
.code #\espace
or
.codn #\etab .
For all other characters, it returns
.codn nil .

.coNP Function @ chr-isunisp
.synb
.mets (chr-isunisp << char )
.syne
.desc
This function returns
.code t
if
.meta char
is a Unicode whitespace character. This the case for
all the characters for which
.code chr-isspace
returns
.codn t .
It also returns
.code t
for these additional characters:
.codn #\exa0 ,
.codn #\ex1680 ,
.codn #\ex180e ,
.codn #\ex2000 ,
.codn #\ex2001 ,
.codn #\ex2002 ,
.codn #\ex2003 ,
.codn #\ex2004 ,
.codn #\ex2005 ,
.codn #\ex2006 ,
.codn #\ex2007 ,
.codn #\ex2008 ,
.codn #\ex2009 ,
.codn #\ex200a ,
.codn #\ex2028 ,
.codn #\ex2029 ,
.codn #\ex205f ,
and
.codn #\ex3000 .
For all other characters, it returns
.codn nil .

.coNP Function @ chr-isupper
.synb
.mets (chr-isupper < char )
.syne
.desc
This function returns
.code t
if
.meta char
is an ASCII upper case letter. Otherwise it returns
.codn nil .

.coNP Function @ chr-isxdigit and @ chr-xdigit
.synb
.mets (chr-isxdigit << char )
.mets (chr-xdigit << char )
.syne
.desc
If
.meta char
is a hexadecimal digit character,
.code chr-isxdigit
returns the value
.code t
and
.code chr-xdigit
returns the integer value corresponding to that digit character,
a value in the range 0 to 15.  Otherwise, both functions returns
.codn nil .

A hexadecimal digit is one of the ASCII
digit characters
.code 0
through
.codn 9 ,
or else one of the letters
.code A
through
.code F
or their lower-case equivalents
.code a
through
.code f
denoting the values 10 to 15.

.coNP Function @ chr-toupper
.synb
.mets (chr-toupper << char )
.syne
.desc
If character
.meta char
is a lower case ASCII letter character, this function
returns the upper case equivalent character. If it is some other
character, then it just returns
.metn char .

.coNP Function @ chr-tolower
.synb
.mets (chr-tolower << char )
.syne
.desc
If character
.meta char
is an upper case ASCII letter character, this function
returns the lower case equivalent character. If it is some other
character, then it just returns
.metn char .

.coNP Functions @ int-chr and @ chr-int
.synb
.mets (int-chr << char )
.mets (chr-int << num )
.syne
.desc
The argument
.meta char
must be a character. The
.code num-chr
function returns that
character's Unicode code point value as an integer.

The argument
.meta num
must be a fixnum integer in the range
.code 0
to
.codn #\ex10FFFF .
The argument is taken to be a Unicode code point value and the
corresponding character object is returned.

Note: these functions are also known by the obsolescent names
.code num-chr
and
.codn chr-num .

.coNP Accessor @ chr-str
.synb
.mets (chr-str < str << idx )
.mets (set (chr-str < str << idx ) << new-value )
.syne
.desc
The
.code chr-str
function performs random access on string
.meta str
to retrieve
the character whose position is given by integer
.metn idx ,
which must
be within range of the string.

The index value 0 corresponds to the first (leftmost) character of the string
and so non-negative values up to one less than the length are possible.

Negative index values are also allowed, such that -1 corresponds to the
last (rightmost) character of the string, and so negative values down to
the additive inverse of the string length are possible.

An empty string cannot be indexed. A string of length one supports index 0 and
index -1. A string of length two is indexed left to right by the values 0 and
1, and from right to left by -1 and -2.

If the element
.meta idx
of string
.meta str
exists, and the string is modifiable, then the
.code chr-str
form denotes a place.

A
.code chr-str
place
supports deletion. When a deletion takes place,
then the character at
.meta idx
is removed from the string. Any characters
after that position move by one position
to close the gap, and the length of the string
decreases by one.

.TP* Notes:

Direct use of
.code chr-str
is equivalent to the DWIM bracket notation except
that
.code str
must be a string. The following relation holds:

.cblk
  (chr-str s i) --> [s i]
.cble

since
.codn "[s i] <--> (ref s i)" ,
this also holds:

.cblk
  (chr-str s i) --> (ref s i)
.cble

However, note the following difference. When the expression
.code "[s i]"
is used as a place, then the subexpression
.code s
must be a place. When
.code "(chr-str s i)"
is used as a place,
.code s
need not be a place.

.coNP Function @ chr-str-set
.synb
.mets (chr-str-set < str < idx << char )
.syne
.desc
The
.code chr-str
function performs random access on string
.meta str
to overwrite
the character whose position is given by integer
.metn idx ,
which must
be within range of the string. The character at
.meta idx
is overwritten
with character
.metn char .

The
.meta idx
argument works exactly as in
.codn chr-str .

The
.meta str
argument must be a modifiable string.

.TP* Notes:

Direct use of
.code chr-str
is equivalent to the DWIM bracket notation except
that
.meta str
must be a string. The following relation holds:

.cblk
  (chr-str-set s i c) --> (set [s i] c)
.cble

since
.codn "(set [s i] c) <--> (refset s i c)" ,
this also holds:

.cblk
  (chr-str s i) --> (refset s i c)
.cble

.coNP Function @ span-str
.synb
.mets (span-str < str << set )
.syne
.desc
The
.code span-str
function determines the longest prefix of string
.meta str
which
consists only of the characters in string
.metn set ,
in any combination.

.coNP Function @ compl-span-str
.synb
.mets (compl-span-str < str << set )
.syne
.desc
The
.code compl-span-str
function determines the longest prefix of string
.meta str
which
consists only of the characters which do not appear in
.metn set ,
in any combination.

.coNP Function @ break-str
.synb
.mets (break-str < str << set )
.syne
.desc
The
.code break-str
function returns an integer which represents the position of the
first character in string
.meta str
which appears in string
.metn set .

If there is no such character, then
.code nil
is returned.

.SS* Lazy Strings
Lazy strings are objects that were developed for the \*(TX pattern matching
language, and are exposed via \*(TL. Lazy strings behave much like strings,
and can be substituted for strings. However, unlike regular strings, which
exist in their entirety, first to last character, from the moment they are
created, lazy strings do not exist all at once, but are created on demand.  If
character at index N of a lazy string is accessed, then characters 0 through N
of that string are forced into existence. However, characters at indices
beyond N need not necessarily exist.

A lazy string dynamically grows by acquiring new text from a list of strings
which is attached to that lazy string object.  When the lazy string is accessed
beyond the end of its hitherto materialized prefix, it takes enough strings
from the list in order to materialize the index. If the list doesn't have
enough material, then the access fails, just like an access beyond the end of a
regular string.  A lazy string always takes whole strings from the attached
list.

Lazy string growth is achieved via the
.code lazy-str-force-upto
function which
forces a string to exist up to a given character position. This function is
used internally to handle various situations.

The
.code lazy-str-force
function forces the entire string to materialize.  If the
string is connected to an infinite lazy list, this will exhaust all memory.

Lazy strings are specially recognized in many of the regular string functions,
which do the right thing with lazy strings. For instance when
.code sub-str
is invoked on a lazy string, a special version of the
.code sub-str
logic is
used which handles various lazy string cases, and can potentially return
another lazy string. Taking a
.code sub-str
of a lazy string from a given character position
to the end does not force the entire lazy string to exist,
and in fact the operation will work on a lazy string that is infinite.

Furthermore, special lazy string functions are provided which allow programs to
be written carefully to take better advantage of lazy strings. What carefully
means is code that avoids unnecessarily forcing the lazy string.  For instance,
in many situations it is necessary to obtain the length of a string, only to
test it for equality or inequality with some number. But it is not necessary to
compute the length of a string in order to know that it is greater than some
value.

.coNP Function @ lazy-str
.synb
.mets (lazy-str < string-list >> [ terminator <> [ limit-count ]])
.syne
.desc
The
.code lazy-str
function constructs a lazy string which draws material from
.meta string-list
which is a list of strings.

If the optional
.meta terminator
argument is given, then it specifies a string
which is appended to every string from
.metn string-list ,
before that string is
incorporated into the lazy string. If
.meta terminator
is not given,
then it defaults to the string
.strn "\en" ,
and so the strings from
.meta string-list
are effectively treated as lines which get terminated by newlines
as they accumulate into the growing prefix of the lazy string.
To avoid the use of a terminator string, a null string
.meta terminator
argument
must be explicitly passed. In that case, the lazy string grows simply
by catenating elements from
.metn string-list .

If the
.meta limit-count
argument is specified, it must be a positive integer.  It
expresses a maximum limit on how many elements will be consumed from
.meta string-list
in order to feed the lazy string. Once that many elements are
drawn, the string ends, even if the list has not been exhausted.

.coNP Function @ lazy-stringp
.synb
.mets (lazy-stringp << obj )
.syne
.desc
The
.code lazy-stringp
function returns
.code t
if
.meta obj
is a lazy
string. Otherwise it returns
.codn nil .

.coNP Function @ lazy-str-force-upto
.synb
.mets (lazy-str-force-upto < lazy-str << index )
.syne
.desc
The
.code lazy-str-force-upto
function tries to instantiate the lazy string such that
the position given by
.meta index
materializes. The
.meta index
is a character
position, exactly as used in the
.code chr-str
function.

Some positions beyond
.meta index
may also materialize, as a side effect.

If the string is already materialized through to at least
.metn index ,
or if it is
possible to materialize the string that far, then the value
.code t
is returned to indicate success.

If there is insufficient material to force the lazy string through to the
.meta index
position, then nil is returned.

It is an error if the
.meta lazy-str
argument isn't a lazy string.

.coNP Function @ lazy-str-force
.synb
.mets (lazy-str-force << lazy-str )
.syne
.desc
The
.meta lazy-str
argument must be a lazy string. The lazy string is forced
to fully materialize.

The return value is an ordinary, non-lazy string equivalent to the fully
materialized lazy string.

.coNP Function @ lazy-str-get-trailing-list
.synb
.mets (lazy-str-get-trailing-list < string << index )
.syne
.desc
The
.code lazy-str-get-trailing-list
function can be considered, in some way, an inverse operation to
the production of the lazy string from its associated list.

First,
.meta string
is forced up through the position
.metn index .
That is the only extent to which
.meta string
is modified by this function.

Next, the suffix of the materialized part of the lazy string starting at
position
.metn index ,
is split into pieces on occurrences of the
terminator character (which had been given as the
.meta terminator
argument in the
.code lazy-str
constructor, and defaults to newline).   If the
.meta index
position is beyond the part of the string which can be materialized
(in adherence with the lazy string's
.meta limit-count
constructor parameter), then the list of pieces is considered
to be empty.

Finally, a list is returned consisting of the pieces produced by the split,
to which is appended the remaining list of the string which has not yet been
forced to materialize.

.coNP Functions @, length-str-> @, length-str->= @ length-str-< and @ length-str-<=
.synb
.mets (length-str-> < string << len )
.mets (length-str->= < string << len )
.mets (length-str-< < string << len )
.mets (length-str-<= < string << len )
.syne
.desc
These functions compare the lengths of two strings. The following
equivalences hold, as far as the resulting value is concerned:

.cblk
  (length-str-> s l) <--> (> (length-str s) l)
  (length-str->= s l) <--> (>= (length-str s) l)
  (length-str-< s l) <--> (< (length-str s) l)
  (length-str-<= s l) <--> (<= (length-str s) l)
.cble

The difference between the functions and the equivalent forms is that if the
string is lazy, the
.code length-str
function will fully force it in order to
calculate and return its length.

These functions only force a string up to position
.metn len ,
so they are not
only more efficient, but on infinitely long lazy strings they are usable.

.code length-str
cannot compute the length of a lazy string with an unbounded
length; it will exhaust all memory trying to force the string.

These functions can be used to test such as string whether it is longer
or shorter than a given length, without forcing the string beyond
that length.

.coNP Function @ cmp-str
.synb
.mets (cmp-str < left-string << right-string )
.syne
.desc
The
.code cmp-str
function returns a negative integer if
.meta left-string
is lexicographically prior to
.metn right-string ,
and a positive integer
if the reverse situation is the case. Otherwise the strings are equal
and zero is returned.

If either or both of the strings are lazy, then they are only forced to the
minimum extent necessary for the function to reach a conclusion and return the
appropriate value, since there is no need to look beyond the first character
position in which they differ.

The lexicographic ordering is naive, based on the character code point
values in Unicode taken as integers, without regard for locale-specific
collation orders.

.coNP Functions @, str= @, str< @, str> @ str>= and @ str<=
.synb
.mets (str= < left-string << right-string )
.mets (str< < left-string << right-string )
.mets (str> < left-string << right-string )
.mets (str<= < left-string << right-string )
.mets (str>= < left-string << right-string )
.syne
.desc
These functions compare
.meta left-string
and
.meta right-string
lexicographically,
as if by the
.code cmp-str
function.

The
.code str=
function returns
.code t
if the two strings are exactly the same, character
for character, otherwise it returns
.codn nil .

The
.code str<
function returns
.code t
if
.meta left-string
is lexicographically before
.metn right-string ,
otherwise nil.

The
.code str>
function returns
.code t
if
.meta left-string
is lexicographically after
.metn right-string ,
otherwise
.codn nil .

The
.code str<
function returns
.code t
if
.meta left-string
is lexicographically before
.metn right-string ,
or if they are exactly the same, otherwise
.codn nil .

The
.code str<
function returns
.code t
if
.meta left-string
is lexicographically after
.metn right-string ,
or if they are exactly the same, otherwise
.codn nil .

.coNP Function @ string-lt
.synb
.mets (string-lt < left-str << right-str )
.syne
.desc
The
.code string-lt
is a deprecated alias for
.codn str< .

.SS* Vectors
.coNP Function @ vector
.synb
.mets (vector < length <> [ initval ])
.syne
.desc
The
.code vector
function creates and returns a vector object of the specified
length.  The elements of the vector are initialized to
.metn initval ,
or to nil if
.meta initval
is omitted.

.coNP Function @ vec
.synb
.mets (vec << arg *)
.syne
.desc
The
.code vec
function creates a vector out of its arguments.

.coNP Function @ vectorp
.synb
.mets (vectorp << obj )
.syne
.desc
The
.code vectorp
function returns t if
.meta obj
is a vector, otherwise it returns
.codn nil .

.coNP Function @ vec-set-length
.synb
.mets (vec-set-length < vec << len )
.syne
.desc
The
.code vec-set-length
modifies the length of
.metn vec ,
making it longer or
shorter. If the vector is made longer, then the newly added elements
are initialized to nil. The
.meta len
argument must be nonnegative.

The return value is
.metn vec .

.coNP Accessor @ vecref
.synb
.mets (vecref < vec << idx )
.mets (set (vecref < vec << idx ) << new-value )
.syne
.desc
The
.code vecref
function performs indexing into a vector. It retrieves
an element of
.meta vec
at position
.metn idx ,
counted from zero.
The
.meta idx
value must range from 0 to one less than the
length of the vector. The specified element is returned.

If the element
.meta idx
of vector
.meta vec
exists, then the
.code vecref
form denotes a place.

A
.code vecref
place
supports deletion. When a deletion takes place,
then if
.meta idx
denotes the last element in the vector, the
vector's length is decreased by one, so that
the vector no longer has that element.
Otherwise, if
.meta idx
isn't the last element, then each elements
values at a higher index than
.meta idx
shifts by one one element position to the
adjacent lower index. Then, the length of the
vector is decreased by one, so that the last
element position disappears.

.coNP Function @ vec-push
.synb
.mets (vec-push < vec << elem )
.syne
.desc
The
.code vec-push
function extends the length of a vector
.meta vec
by one element, and
sets the new element to the value
.metn elem .

The previous length of the vector (which is also the position of
.metn elem )
is returned.

This function performs similarly to the generic function
.codn ref ,
except that the
first argument must be a vector.

.coNP Function @ length-vec
.synb
.mets (length-vec << vec )
.syne
.desc
The
.code length-vec
function returns the length of vector
.metn vec .
It performs
similarly to the generic
.code length
function, except that the argument must
be a vector.

.coNP Function @ size-vec
.synb
.mets (size-vec << vec )
.syne
.desc
The
.code size-vec
function returns the number of elements for which storage
is reserved in the vector
.metn vec .

.TP* Notes:

The
.code length
of the vector can be extended up to this size without any memory
allocation operations having to be performed.

.coNP Function @ vec-list
.synb
.mets (vec-list << list )
.syne
.desc
This function returns a vector which contains all of the same elements
and in the same order as list
.metn list .

Note: this function is also known by the obsolescent name
.codn vector-list .

.coNP Function @ list-vec
.synb
.mets (list-vec << vec )
.syne
.desc
The
.code list-vec
function returns a list of the elements of vector
.metn vec .

Note: this function is also known by the obsolescent name
.codn list-vector .

.coNP Function @ copy-vec
.synb
.mets (copy-vec << vec )
.syne
.desc
The
.code copy-vec
function returns a new vector object of the same length
as
.meta vec
and containing the same elements in the same order.

.coNP Function @ sub-vec
.synb
.mets (sub-vec < vec >> [ from <> [ to ]])
.syne
.desc
The
.code sub-vec
function is like the more generic function
.codn sub ,
except that it
operates only on vectors.

For a description of the arguments and semantics, refer to the
.code sub
function.

.coNP Function @ replace-vec
.synb
.mets (replace-vec < vec < item-sequence >> [ from <> [ to ]])
.syne
.desc
The
.code replace-vec
is like the
.code replace
function, except that the first argument
must be a vector.

For a description of the arguments, semantics and return value, refer to the
.code replace
function.

.coNP Function @ cat-vec
.synb
.mets (cat-vec << vec-list )
.syne
.desc
The
.meta vec-list
argument is a list of vectors. The
.code cat-vec
function
produces a catenation of the vectors listed in
.metn vec-list .
It returns
a single large vector formed by catenating those vectors together in
order.

.SS* Structures

\*(TX supports a structure data type. Structures are objects which
hold multiple storage locations called slots, which are named by symbols.
Structures can be related to each other by inheritance.

The type of a structure is itself an object, of type
.codn struct-type .

When the program defines a new structure type, it does so by creating a new
.code struct-type
instance, with properties which describe the new structure type: its
name, its list of slots, its initialization and "boa constructor" functions,
and the structure type it inherits from (the "super").

The
.code
struct-type
object is then used to generate instances.

Structures instances are not only containers which hold named slots, but they
also indicate their struct type. Two structures which have the same number of
slots having the same names are not necessarily of the same type.

Structure types and structures may be created and manipulated using
a programming interface based on functions.

For more convenient and clutter-free expression of structure-based
program code, macros are also provided.

Furthermore, concise and expressive slot access syntax is provided courtesy of
the referencing dot syntax, a syntactic sugar for the
.code qref
macro.

Structure types have a name, which is a symbol. The
.code typeof
function, when applied to a any struct type, returns the symbol
.codn struct-type .
When
.code typeof
is applied to a struct instance, it returns the name of
the struct type. Effectively, struct names are types.

The consequences are unspecified if an existing struct name is re-used for a
different struct type, or an existing type name is used for a struct type.

.NP* Static Slots

Structure slots can be of two kinds: they can be the ordinary instance slots or
they can be static slots.  The instances of a given structure type have their
own instance of a given instance slot. However, they all share a single
instance of a static slot.

Static slots are allocated in a global area associated with a structure type
and are initialized when the structure type is created. They are useful for
efficiently representing properties which have the same value for all instances
of a struct. These properties don't have to occupy space in each instance, and
time doesn't have to be wasted initializing them each time a new instance is
created.  Static slots are also useful for struct-specific global variables.
Lastly, static slots are also useful for holding methods and functions.
Although structures can have methods and functions in their instances, usually,
all structures of the same type share the same functions. The
.code defstruct
macro supports a special syntax for defining methods and struct-specific
functions at the same time when a new structure type is defined.
The
.code defmeth
macro can be used for adding new methods and functions to an existing
structure and its descendants.

Static slots may be assigned just like instance slots. Changing a static
slot, of course, changes that slot in every structure of the same type.

Static slots are not listed in the
.code #S(...)
notation when a structure is printed. When the structure notation is
read from a stream, if static slots are present, they will be processed
and their values stored in the static locations they represent, thus
changing their values for all instances.

Static slots are inherited just like instance slots. However, when one
structure type inherits a static slot from another, that structure type
has its own storage location for that slot.

The slot type can be overridden. A structure type deriving from another
type can introduce slots which have the same names as the supertype,
but are of a different kind: an instance slot in the supertype
can be replaced by a static slot in the derived type or vice versa.

A structure type is associated with a static initialization function
which may be used to store initial values into static slots. This function
is invoked once in a type's life time, when the type is created.
The function is also inherited by derived struct types and invoked when
they are created.

If a newly introduced (that is to say, non-inherited) static slot isn't
initialized by the static initialization function, its value defaults to
.codn nil .
If an inherited slot isn't initialized by its supertype's initialization
function, then its initial value in the new type is a copy of the current
value of the supertype's corresponding slot.

.NP* Functors

A structure object can be invoked as a function, if it supports an "anonymous"
method. An anonymous method is one whose name is the
.code lambda
symbol. When arguments are applied to an object
.codn s ,
the object and those arguments are passed to the
.code lambda
method. If there is no such method, the call is erroneous.

That is to say, the following equivalences apply, except that
.code s
is evaluated only once:

.cblk
  (call s args ...)  <-->  s.(lambda args ...)

  [s args ...]  <-->  [s.lambda s args ...]

  (mapcar s list)  <-->  (mapcar (meth s lambda) list)
.cble

.NP* Equality Substitution

Normally, two struct values are not considered the same under the
.code equal
function unless they are the same object.

However, if a method named
.code equal
is defined for a structure type, via a static slot, then instances of
that structure type support
.IR "equality substitution" .

The
.code equal
method must take exactly one argument: the structure object.
Moreover, the method must never return
.codn nil .

When a struct which supports equality substitution is compared using
.codn equal ,
.code less
or
.codn greater ,
its
.code equal
method is invoked, and the return value is used in place of that
structure for the purposes of the comparison.

The same applies when an struct is hashed using the
.code hash-equal
function, or implicitly by an
.code :equal-hash
hash tables.

Note: if an
.code equal
method is defined or redefined with different semantics for a struct
type whose instances have already been inserted as keys in an
.code :equal-based
hash table, searches for those keys will not work reliably.

.coNP Macro @ defstruct
.synb
.mets (defstruct >> { name | >> ( name << arg *)} < super
.mets \ \  << slot-specifier *)
.syne
.desc
The
.code defstruct
macro defines a new structure type and registers it under
.metn name ,
which must be a bindable symbol, according to the
.code bindable
function. Likewise, the name of every
.meta slot
must also be a bindable symbol.

The
.meta super
argument must either be
.code nil
or a symbol which names an existing struct type.
The newly defined struct type will inherit all slots,
as well as initialization behaviors from this type.

The
.code defstruct
macro is implemented using the
.code make-struct-type
function, which is more general. The macro analyzes the
.code defstruct
argument syntax, and synthesizes arguments which are then
used to call the function. Some remarks in the description of
.code defstruct
only apply to structure types defined using that macro.

Slots are specified using zero or more
.IR "slot specifiers" .
Slot specifiers come in the following variety:
.RS
.meIP < name
The simplest slot specifier is just a name, which must be a bindable
symbol, as defined by the
.code bindable
function. This form is a short form for the
.cblk
.meti (:instance < name nil)
.cble
syntax.
.meIP >> ( symbol << init-form )
This syntax is a short form for the
.cblk
.meti (:instance < name << init-form )
.cble
syntax.
.meIP (:instance < name << init-form )
This syntax specifies an instance slot called
.meta name
whose initial value is obtained by evaluating
.meta init-form
whenever a new instance of the structure is created.
This evaluation takes place in the original lexical environment in which the
.code defstruct
form occurs.
.meIP (:static < name << init-form )
This syntax specifies a static slot called
.meta name
whose initial value is obtained by evaluating
.meta init-form
once, during the evaluation of the
.code defstruct
form in which it occurs.
.meIP (:method < name <> ( param +) << body-form *)
This syntax creates a static slot called
.meta name
which is initialized with an anonymous function.
The anonymous function is created during the
evaluation of the
.code defstruct
form. The function takes the arguments specified
by the
.meta param
symbols, and its body consists of the
.metn body-form -s.
There must be at least one
.metn param .
When the function is invoked as a method, as intended,
the leftmost
.meta param
receives the structure instance.
The
.metn body-form -s
are evaluated in a context in which a block named
.meta name
is visible. Consequently,
.code return-from
may be used to terminate the execution of a method
and return a value.
Methods are invoked
using the
.code "instance.(name arg ...)"
syntax, which implicitly inserts the instance into the argument list.
.meIP (:function < name <> ( param *) << body-form *)
This syntax creates a static slot called
.meta name
which is initialized with an anonymous function.
The anonymous function is created during the
evaluation of the
.code defstruct
form. The function takes the arguments specified
by the
.meta param
symbols, and its body consists of the
.metn body-form -s.
This specifier differs from
.code :method
only in one respect: there may be zero
parameters. A structure function defined this way is
intended to be used as a utility function which doesn't
receive the structure instance as an argument.
The
.metn body-form -s
are evaluated in a context in which a block named
.meta name
is visible. Consequently,
.code return-from
may be used to terminate the execution of the function
and return a value.
Such functions are called using the
.code "instance.[name arg ...]"
syntax which doesn't insert the instance into
the argument list.
.meIP (:init <> ( param ) << body-form *)
The
.code :init
specifier doesn't describe a slot. Rather, it specifies code
which is executed when a structure is instantiated, after
the slot initializations specific to the structure type
are performed. The code consists of
.metn body-form -s
which are evaluated in order in a lexical scope in
which the variable
.meta param
is bound to the structure object.

The
.code :init
specifier may not appear more than once in a given
.code defstruct
form.

When an object with one or more levels of inheritance
is instantiated, the
.code :init
code of a base structure type, if any, is executed
before any initializations specific to a derived
structure type.

The
.code :init
initializations are executed before any other
slot initializations. The argument values passed to the
.code new
or
.code lnew
operator or the
.code make-struct
function are not yet stored in the object's slots,
and are not accessible. Initialization code which needs
these values to be stable can be defined with
.codn :postinit .

Initializers in base structures must be careful about assumptions about slot
kinds, because derived structures can alter static slots to instance slots or
vice versa. To avoid an unwanted initialization being applied to the
wrong kind of slot, initialization code can be made conditional on the
outcome of
.code static-slot-p
applied to the slot.
(Code generated by
.code defstruct
for initializing instance slots performs this kind of check).

The
.metn body-form -s
of an
.code :init
specifier are not surrounded by an implicit
.codn block .
.meIP (:postinit <> ( param ) << body-form *)
The
.code :postinit
specifier is very similar to
.codn :init .
There are two differences. The first difference
is that
.codn body-form -s
are evaluated after other initializations have taken
place. The argument material from the
.codn make-struct ,
.code new
or
.code lnew
invocation has already been processed and stored
into slots.
The second difference is that
.code :postinit
actions registered at different levels of the type's
inheritance hierarchy are invoked in the opposite
order compared to
.code :init
action. The
.code :postinit
specific to a derived struct type is called before
the
.code :postinit
of its base type.
.meIP (:fini <> ( param ) << body-form *)
The
.code :fini
specifier doesn't describe a slot. Rather, it specifies
a finalization function which is associated with the
structure instance, as if by use of the
.code finalize
function. This finalization registration takes place
as the first step when an instance of the structure
is created, before the slots are initialized and
the
.code :init
code, if any, has been executed. The registration
takes place as if by the evaluation of the form
.cblk
.meti (finalize < obj (lambda <> ( param ) << body-form ...) t)
.cble
where
.meta obj
denotes the structure instance. Note the
.code t
argument which requests reverse order of registration, ensuring that if an
object has multiple finalizers registered at different levels of inheritance
hierarchy, the finalizers specified for a derived structure type are called
before inherited finalizers.

The
.metn body-form -s
of a
.code :fini
specifier are not surrounded by an implicit
.codn block .

Note that an object's finalizers can be called explicitly with
.codn call-finalizers .
.RE
.IP
The
.code with-objects
macro arranges for finalizers to be called on objects when the execution
of a scope terminates by any means.

The slot names given in a
.code defstruct
must all be unique among themselves, but they
may match the names of existing slots in the
.meta super
base type.

A given structure type can have only one slot under a given
symbolic name.  If a newly specified  slot matches the name of an existing slot
in the
.meta super
type or that type's chain of ancestors, it is called a
.IR "repeated slot" .

A repeated slot inherits initialization forms from all of its ancestors.

The kind of the repeated slot (static or instance) is not inherited; it
is established by the
.code defstruct
and may be different from the type of the same-named slot in the
supertype or its ancestors.

A repeated slot only inherits the initializations which correspond to
its kind. If a repeated slot is introduced as a static slot, then
all of the static initializations in the ancestry chain are performed
on that slot, which takes place during the evaluation of the
.code defstruct
form. If that slot is an instance slot in any of the
ancestor structure types, their initializations do not apply and are not
evaluated.

If a repeated slot is introduced as an instance slot then none of the static
initializations in the ancestry chain are performed on it; none of the forms
are evaluated. Those initializations target a static slot, which the derived
type doesn't have.  When an instance of the structure is created, then the
instance initializations are performed on that slot from all of the ancestor
structure types in which that slot is also an instance slot.

The initialization for slots which are specified using the
.code :method
or
.code :function
specifiers is re-ordered with regard to
.code :static
slots. Regardless of their placement in the
.code defstruct
form,
.code :method
and
.code :function
slots are initialized before
.code :static
slots. This ordering is useful, because it means that when the initialization
expression for a given static slot constructs an instance of the struct type,
any instance initialization code executing for that instance can use
all functions and methods of the struct type.
However, note the static slots which follow that slot in the
.code defstruct
syntax are not yet initialized. If it is necessary for a structure's
initialization code to have access to all static slots, even when the
structure is instantiated during the initialization of a static slot,
a possible solution may be to use lazy instantiation using the
.code lnew
operator, rather than ordinary eager instantiation via
.codn new .
It is also necessary to ensure that that the instance isn't accessed until all
static initializations are complete, since access to the instance slots of a
lazily instantiated structure triggers its initialization.

The structure name is specified using two forms, plain
.meta name
or the syntax
.cblk
.meti >> ( name << arg *)
.cble
If the second form is used, then the structure type will support
"boa construction", where "boa" stands for "by order of arguments".
The
.metn arg -s
specify the list of slot names which are to be initialized in the
by-order-of-arguments style. For instance, if three slot names
are given, then those slots can be optionally initialized by giving three
arguments in the
.code new
macro or the
.code make-struct
function.

Slots are first initialized according to their
.metn init-form -s,
regardless of whether they are involved in boa construction

A slot initialized in this style still has a
.meta init-form
which is processed independently of the existence of, and prior to,
boa construction.

The boa constructor syntax can specify optional parameters, delimited
by a colon, similarly to the
.code lambda
syntax. However, the optional parameters may not be arbitrary symbols;
they must be symbols which name
slots. Moreover, the
.cblk
.meti >> ( name < init-form <> [ present-p ])
.cble
optional parameter syntax isn't supported.

When boa construction is invoked with optional arguments missing,
the default values for those arguments come from the
.metn init-form -s
in the remaining
.code defstruct
syntax.

.TP* Examples:
.cblk
  (defvar *counter* 0)

  ;; New struct type foo with no super type:
  ;; Slots a and b initialize to nil.
  ;; Slot c is initialized by value of (inc *counter*).
  (defstruct foo nil (a b (c (inc *counter*))))

  (new foo) -> #S(foo a nil b nil c 1)
  (new foo) -> #S(foo a nil b nil c 2)

  ;; New struct bar inheriting from foo.
  (defstruct bar foo (c 0) (d 100))

  (new bar) -> #S(bar a nil b nil c 0 d 100)
  (new bar) -> #S(bar a nil b nil c 0 d 100)

  ;; counter was still incremented during
  ;; construction of d:
  *counter* -> 4

  ;; override slots with new arguments
  (new foo a "str" c 17) -> #S(foo a "str" b nil c 17)

  *counter* -> 5

  ;; boa initialization
  (defstruct (point x : y) nil (x 0) (y 0))

  (new point) -> #S(point x 0 y 0)
  (new (point 1 1)) -> #S(point x 1 y 1)

  ;; property list style initialization
  ;; can always be used:
  (new point x 4 y 5) -> #S(point x 4 y 5)

  ;; boa applies last:
  (new (point 1 1) x 4 y 5) -> #S(point x 1 y 1)

  ;; boa with optional argument omitted:
  (new (point 1)) -> #S(point x 1 y 0)

  ;; boa with optional argument omitted and
  ;; with property list style initialization:
  (new (point 1) x 5 y 5) -> #S(point x 1 y 5)
.cble

.coNP Macro @ defmeth
.synb
.mets (defmeth < type-name < name < param-list << body-form *)
.syne
.desc
The
.code defmeth
macro installs a function into the static slot named by the symbol
.meta name
in the struct type indicated by
.metn type-name .

If the structure type doesn't already have such a static slot, it is
first added, as if by the
.code static-slot-ensure
function, subject to the same checks.

If the function has at least one argument, it can be used as a method. In that
situation, the leftmost argument passes the structure instance on which the
method is being invoked.

The function takes the arguments specified
by the
.meta param-list
symbols, and its body consists of the
.metn body-form -s.

The
.metn body-form -s
are placed into a
.code block
named
.codn name .

A method named
.code lambda
allows a structure to be used as if it were a function. When arguments
are applied to the structure as if it were a function, the
.code lambda
method is invoked with those arguments, with the object itself inserted
into the leftmost argument position.

If
.code defmeth
is used to redefine an existing method, the semantics can be inferred
from that of
.codn static-slot-ensure .
In particular, the method will be imposed into all subtypes which do not
override the method using an instance slot, overwriting any subtype-specific
methods stored in static slots of the same name. These subtype methods
have to be individually reinstated, if they are required.

.coNP Macros @ new and @ lnew
.synb
.mets (new >> { name | >> ( name << arg *)} >> { slot << init-form }*)
.mets (lnew >> { name | >> ( name << arg *)} >> { slot << init-form }*)
.syne
.desc
The
.code new
macro creates a new instance of the structure type named by
.metn name .

If the structure supports "boa construction", then, optionally, the
arguments may be given using the syntax
.cblk
.meti >> ( name << arg *)
.cble
instead of
.metn name .

Slot values may also be specified by the
.meta slot
and
.meta init-form
arguments.

Note: the evaluation order in
.code new
is surprising: namely,
.metn init-form -s
are evaluated before
.metn arg -s
if both are present.

When the object is constructed, all default initializations take place
first. If the object's structure type has a supertype, then the supertype
initializations take place. Then the type's initializations take
place, followed by the
.meta slot
.meta init-form
overrides from the
.code new
macro, and lastly the "boa constructor" overrides.

If any of the initializations abandon the evaluation of
.code new
by a non-local exit such as an exception throw, the object's
finalizers, if any, are invoked.

The macro
.code lnew
differs from new in that it specifies the construction of a
lazy struct, as if by the
.code make-lazy-struct
function.
When
.code lnew
is used to construct an instance, a lazy struct is returned
immediately, without evaluating any of the the
.meta arg
and
.meta init-form
expressions.
The expressions are evaluated when any of the object's
instance slots is accessed for the first time. At that time,
these expressions are evaluated (in the same order as under
.codn new )
and initialization proceeds in the same way.

If any of the initializations abandon the delayed initializations steps
arranged by
.code lnew
by a non-local exit such as an exception throw, the object's
finalizers, if any, are invoked.

.coNP Macro @ with-slots
.synb
.mets (with-slots >> ({ slot | >> ( sym << slot )}*) < struct-expr
.mets \ \  << body-form *)
.syne
.desc
The
.code with-slots
binds lexical macros to serve as aliases for the slots of a structure.

The
.meta struct-expr
argument is expected to be an expression which evaluates to a struct
object. It is evaluated once, and its value is retained. The aliases are then
established to the slots of the resulting struct value.

The aliases are specified as zero or more expressions which consist of either
a single symbol
.meta slot
or a
.cblk
.meti >> ( sym << slot )
.cble
pair. The simple form binds a macro named
.meta slot
to a slot also named
.metn slot .
The pair form binds a macro named
.meta sym
to a slot named
.metn slot .

The lexical aliases are syntactic places: assigning to an alias causes
the value to be stored into the slot which it denotes.

After evaluating
.meta struct-expr
the
.code with-slots
macro arranges for the evaluation of
.metn body-form -s
in the lexical scope in which the aliases are visible.

.TP* "Dialect Notes:"

The intent of the
.code with-slots
macro is to help reduce the verbosity of code which makes multiple
references to the same slot. Use of
.code with-slots
is less necessary in \*(TL than other Lisp dialects
thanks to the dot operator for accessing struct slots.

Lexical aliases to struct places can also be
arranged with considerable convenience using the
.code placelet
operator. However,
.code placelet
will not bind multiple aliases to multiple slots of the same object
such that the expression which produces the object is evaluated only
once.

.TP* Example:
.cblk
  (defstruct point nil x y)

  ;; Here, with-slots introduces verbosity because
  ;; each slot is accessed only once. The function
  ;; is equivalent to:
  ;;
  ;; (defun point-delta (p0 p1)
  ;;   (new point x (- p1.x p0.x) y (- p1.y p0.y)))
  ;;
  ;; Also contrast with the use of placelet:
  ;;
  ;; (defun point-delta (p0 p1)
  ;;   (placelet ((x0 p0.x) (y0 p0.y)
  ;;              (x1 p1.x) (y1 p1.y))
  ;;     (new point x (- x1 x0) y (- y1 y0)))))

  (defun point-delta (p0 p1)
    (with-slots ((x0 x) (y0 y)) p0
      (with-slots ((x1 x) (y1 y)) p1
        (new point x (- x1 x0) y (- y1 y0)))))


.cble

.coNP Macro @ qref
.synb
.mets (qref < object-form
.mets \ \  >> { slot | >> ( slot << arg *) | >> [ slot << arg *]}+)
.syne
.desc
The
.code qref
macro performs structure slot access.  Structure slot access is more
conveniently expressed using the referencing dot notation, which works
by translating to qref
.code qref
syntax, according to the following equivalence:

.cblk
  a.b.c.d <--> (qref a b c d)  ;; a b c d must not be numbers
.cble

(See the Referencing Dot section under Additional Syntax.)

The leftmost argument of
.code qref
is an expression which is evaluated. This argument is followed by one or more
reference designators.
If there are two or more designators, the following equivalence applies:

.cblk
  (qref obj d1 d2 ...)  <---> (qref (qref obj d1) d2 ...)
.cble

That is to say,
.code qref
is applied to the object and a single designator. This must yield
an object, which to which the next designator is applied as if by
another
.code qref
operation, and so forth.

Thus,
.code qref
can be understood entirely in terms of the semantics of the
binary form
.cblk
.meti (qref < object-form << designator )
.cble

Designators come in three forms: a lone symbol, an ordinary compound expression
consisting of a symbol followed by arguments, or a DWIM expression
consisting of a symbol followed by arguments.

A lone symbol designator indicates the slot of that name. That is to say, the
following equivalence applies:

.cblk
  (qref o n)  <-->  (slot o 'n)
.cble

Where
.code slot
is the structure slot accessor function. Because
.code slot
is an accessor, this form denotes the slot as a syntactic place;
slots can be modified via assignment to the
.code qref
form and the referencing dot syntax.

A compound designator indicates that the named slot is a function,
and arguments are to be applied to it. The following equivalence applies
in this case, except that
.code o
is evaluated only once:

.cblk
  (qref o (n arg ...)) <--> (call (slot o 'n) o arg ...)
.cble

A DWIM designator indicates that the named slot is a function or an
indexable or callable object. The following equivalence applies:

.cblk
  (qref obj [name arg ...])  <-->  [(slot obj 'name) arg ...]
.cble

.TP* Example:

.cblk
  (defstruct foo nil
    (array (vec 1 2 3))
    (increment (lambda (self index delta)
                 (inc [self.array index] delta))))

  (defvarl s (new foo))

  ;; access third element of s.array:
  s.[array 2]  -->  3

  ;; increment first element of array by 42
  s.(increment 0 42)  -->  43

  ;; access array member
  s.array  -->  #(43 2 3)
.cble

Note how
.code increment
behaves much like a single-argument-dispatch object-oriented method.
Firstly, the syntax
.cblk
s.(increment 0 42)
.cble
effectively selects the
.code increment
function which is particular to the
.code s
object.  Secondly, the object is passed to the selected function as the
leftmost argument, so that the function has access to the object.

.coNP Macro @ meth
.synb
.mets (meth < struct << slot )
.syne
.desc
The
.code meth
macro binds
.meta struct
as the leftmost argument of the function stored in
.metn slot ,
returning a function which takes the remaining arguments.
That is to say, it returns a function
.meta f
such that
.cblk
.meti >> ( f < arg ... )
.cble
calls
.cblk
.meti >> ( struct.slot < struct < arg ... )
.cble
except that
.meta struct
is evaluated only once.

The argument
.meta struct
must be an expression which evaluates to a struct.
The
.meta slot
argument is not evaluated, and must be a symbol denoting a slot.
The syntax can be understood as a translation to a call of the
.code method
function:

.cblk
  (meth a b)  <-->  (method a 'b)
.cble

The
.code meth
macro allows indirection upon a method-like function stored
in a function slot.

.TP* Example:

.cblk
  ;; struct for counting atoms eq to key
  (defstruct (counter key) nil
    key
    (count 0)
    (:method increment (self key)
      (if (eq self.key key)
        (inc self.count))))

  ;; pass all atoms in tree to func
  (defun map-tree (tree func)
    (if (atom tree)
      [func tree]
      (progn (map-tree (car tree) func)
             (map-tree (cdr tree) func))))

  ;; count occurrences of symbol a
  ;; using increment method of counter,
  ;; passed as func argument to map-tree.
  (let ((c (new (counter 'a)))
        (tr '(a (b (a a)) c a d)))
    (map-tree tr (meth c increment))
    c)
  --> #S(counter key a count 4
                 increment #<function: type 0>)
.cble

.coNP Macro @ umeth
.synb
.mets (umeth << slot )
.syne
.desc
The
.code umeth
macro binds the symbol
.meta slot
to a function and returns that function.

When that function is called, it expects at least one argument.
The leftmost argument must be an object of struct type.

The slot named
.meta slot
is retrieved from that object, and is expected to be a function.
That function is called with the same arguments.

The syntax can be understood as a translation to a call of the
.code umethod
function:

.cblk
  (umeth s)  <-->  (umethod 's)
.cble

The macro merely provides the syntactic sugar of not having to quote the
symbol.

.TP* Example:

.cblk
   ;; seal and dog are variables which hold structures of
   ;; different types. Both have a method called bark.

   (let ((bark-fun (umeth bark)))
     [bark-fun dog]     ;; same effect as dog.(bark)
     [bark-fun seal])   ;; same effect as seal.(bark)
.cble

The
.code u
in
.code umeth
stands for "unbound". The function produced by
.code umeth
is not bound to any specific object; it binds to an object whenever it is
invoked by retrieving the actual method from the object's slot at call time.

.coNP Macro @ usl
.synb
.mets (usl << slot )
.syne
.desc
The
.code usl
macro binds the symbol
.meta slot
to a function and returns that function.

When that function is called, it expects exactly one argument.
That argument must be an object of struct type.
The slot named
.meta slot
is retrieved from that object and returned.

The name
.code usl
stands for "unbound slot". The term "unbound" refers to the returned
function not being bound to a particular object. The binding of the
slot to an object takes place whenever the function is called.

.coNP Function @ make-struct-type
.synb
.mets (make-struct-type < name < super < static-slots < slots
.mets \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \  < static-initfun < initfun << boactor )
.mets \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \  < boactor << postinitfun )
.syne
.desc
The
.code make-struct-type
function creates a new struct type.

The
.meta name
argument must be a bindable symbol, according to the
.code bindable
function. It specifies the name property of the struct
type as well as the name under which the struct type
is globally registered.

The
.meta super
argument indicates the supertype for the struct type.
It must be either a value of type
.codn struct-type ,
a symbol which names a struct type, or else
.codn nil ,
indicating that the newly created struct type has no supertype.

The
.meta static-slots
argument is a list of symbol which specify static slots.
The symbols must be bindable and the list must not contain duplicates.

The
.meta slots
argument is a list of symbols which specifies the instance slots.
The symbols must be bindable and there must not be any duplicates
within the list, or against entries in the
.meta static-slots
list.

The new struct type's effective list of slots is formed by appending
together
.meta static-slots
and
.metn slots ,
and then appending that to the list of the supertype's slots, and
de-duplicating the resulting list as if by the
.code uniq
function. Thus, any slots which are already present in the supertype are
removed. If the structure has no supertype, then the list of supertype
slots is taken to be empty. When a structure is instantiated, it shall have all
the slots specified in the effective list of slots. Each instance slot
shall be initialized to the value
.codn nil ,
prior to the invocation of
.meta initfun
and
.metn boactor .

The
.meta static-initfun
argument either specifies an initialization function, or is
.codn nil ,
which is equivalent to specifying a function which does nothing.

Prior to the invocation of
.metn static-initfun ,
each new static slot shall be initialized to the value
.code nil
and each inherited static slot shall be initialized to
the current value which the corresponding static slot
holds in the supertype.

If specified,
.meta static-initfun
function must
accept one argument. When the structure type is created (before
the
.code make-struct-type
function returns) all of the
.meta static-initfun
functions in the chain of supertype ancestry are invoked, in
order of inheritance. Each is passed the structure type as an argument. The
purpose is to initialize the static slots.

The
.meta initfun
argument either specifies an initialization function, or is
.codn nil ,
which is equivalent to specifying a function which does nothing.
If specified, this function must
accept one argument. When a structure is instantiated, every
.meta initfun
in its chain of supertype ancestry is invoked, in order of inheritance,
so that the root supertype's
.meta initfun
is called first and the structure's own specific
.meta initfun
is called last. These calls occur before the slots are initialized
from the
.meta arg
arguments
or the
.meta slot-init-plist
of
.codn make-struct .
Each function is passed the newly created structure
object, and may alter its slots.

The
.meta boactor
argument either specifies a by-order-of-arguments initialization
function ("boa constructor") or is
.codn nil ,
which is equivalent to specifying a constructor which does nothing.
If specified, it must be a function which takes at least one argument.
When a structure is instantiated, and boa arguments are given, the
.meta boactor
is invoked, with the structure as the leftmost argument, and
the boa arguments as additional arguments. This takes place
after the processing of
.meta initfun
functions, and after the processing of the
.meta slot-init-plist
specified in the
.code make-struct
call.  Note that the
.meta boactor
functions of the supertypes are not called, only the
.meta boactor
specific to the type being constructed.

The
.meta postinitfun
argument either specifies an initialization function, or is
.codn nil ,
which is equivalent to specifying a function which does nothing.
If specified, this function must accept one argument.
The
.meta postinitfun
function is similar to
.metn initfun .
The difference is that
.meta postinitfun
functions are called after all other initialization processing,
rather than before. Unlike
.meta initfun
functions, they are also called in the opposite
in order of inheritance, so that the structure type's
own specific
.meta postinitfun
is called first, and root supertype's
.meta initfun
is called last.

.coNP Function @ find-struct-type
.synb
.mets (find-struct-type << name )
.syne
.desc
The
.code find-struct-type
returns a
.code struct-type
object corresponding to the symbol
.metn name .

If no struct type is registered under
.metn name ,
then it returns
.codn nil .

.coNP Function @ struct-type-p
.synb
.mets (struct-type-p << obj )
.syne
.desc
The
.code struct-type-p
function returns t if
.meta obj
is a structure type, otherwise it returns
.codn nil .

.coNP Function @ super
.synb
.mets (super << type )
.syne
.desc
The
.code super
function returns the struct type object which is the
supertype of
.metn type ,
or returns
.code nil
if
.meta type
has no supertype.

The
.meta type
argument must be either a struct type object, a
a symbol which names a struct type (which is resolved to that type),
or else a structure instance (which is resolved to its structure type).

.coNP Function @ make-struct
.synb
.mets (make-struct < type < slot-init-plist << arg *)
.syne
.desc
The
.code make-struct
function returns a new object which is an instance of the
structure type
.metn type .

The
.meta type
argument must either be a
.code struct-type
object, or else a symbol which is the name of a structure.

The
.meta slot-init-plist
argument gives a list of slot initializations in the
style of a property list, as defined by the
.code prop
function. It may be empty, in which case
it has no effect. Otherwise, it specifies slot names
and their values. Each slot name which is given must
be a slot of the structure type. The corresponding value
will be stored into the slot of the newly created object. If a slot is
repeated, it is unspecified which value takes effect.

The optional
.metn arg -s
specify arguments to the structure type's boa constructor.
If the arguments are omitted, the boa constructor is not invoked.
Otherwise the boa constructor is invoked on the structure object
and those arguments.  The argument list must match the trailing parameters of
the boa constructor (the remaining parameters which follow the leftmost
argument which passes the structure to the boa constructor).

When a new structure is instantiated by
.codn make-struct ,
its slot values are first initialized by the structure type's registered
functions as described under
.codn make-struct-type .
Then, the
.meta slot-init-plist
is processed, if not empty, and finally, the
.metn arg -s
are processed, if present, and passed to the boa constructor.

If any of the initializations abandon the evaluation of
.code make-struct
by a non-local exit such as an exception throw, the object's
finalizers, if any, are invoked.

.coNP Function @ make-lazy-struct
.synb
.mets (make-lazy-struct < type << argfun )
.syne
.desc
The
.code make-lazy-struct
function returns a new object which is an instance of the
structure type
.metn type .

The
.meta type
argument must either be a
.code struct-type
object, or else a symbol which is the name of a structure.

The
.meta argfun
argument should be a function which can be called with no parameters
and returns a cons cell. More requirements are specified below.

The object returned by
.code make-lazy-struct
is a lazily-initialized struct instance, or
.IR "lazy struct" .

A lazy struct remains uninitialized until just before the first access
to any of its instance slots. Just before an instance slot is
accessed, initialization
takes place as follows. The
.meta argfun
function is invoked with no arguments. Its return value must be a cons
cell. The
.code car
of the cons cell is taken to be a property list, as defined by the
.code prop
function.  The
.code cdr
field is taken to be a list of arguments. These values are treated
as if they were, respectively, the
.meta slot-init-plist
and the boa constructor arguments given in a
.code make-struct
invocation. Initialization of the structure proceeds as described
in the description of
.codn make-struct .

.coNP Function @ copy-struct
.synb
.mets (copy-struct << struct-obj )
.syne
.desc
The
.code copy-struct
function creates and returns a new object which is a duplicate of
.metn struct-obj ,
which must be a structure.

The duplicate object is a structure of the same type as
.meta struct-obj
and has the same slot values.

The creation of a duplicate does not involve calling any of the
struct type's initialization functions.

Only instance slots participate in the duplication. Since
the original structure and copy are of the same structure type,
they already share static slots.

.coNP Accessor @ slot
.synb
.mets (slot < struct-obj << slot-name )
.mets (set (slot < struct-obj << slot-name ) << new-value )
.syne
.desc
The
.code slot
function retrieves a structure's slot. The
.meta struct-obj
argument must be a structure, and
.meta slot-name
must be a symbol which names a slot in that structure.

Because
.code slot
is an accessor, a
.code slot
form is a syntactic place which denotes the
slot's storage location.

A syntactic place expressed by
.code slot
does not support deletion.

.coNP Function @ slotset
.synb
.mets (slotset < struct-obj < slot-name << new-value )
.syne
.desc
The
.code slotset
function stores a value in a structure's slot.
 The
.meta struct-obj
argument must be a structure, and
.meta slot-name
must be a symbol which names a slot in that structure.

The
.meta new-value
argument specifies the value to be stored in the slot.

.coNP Function @ structp
.synb
.mets (structp << obj )
.syne
.desc
The
.code structp
function returns t if
.meta obj
is a structure, otherwise it returns
.codn nil .

.coNP Function @ struct-type
.synb
.mets (structp << struct-obj )
.syne
.desc
The
.code struct-type
function returns the structure type object which
defines the type of the structure object
.metn struct-obj .

.coNP Function @ clear-struct
.synb
.mets (clear-struct < struct-obj <> [ value ])
.syne
.desc
The
.code clear-struct
replaces all instance slots of
.meta struct-obj
with
.metn value ,
which defaults to
.code nil
if omitted.

Note that finalizers are not executed prior to replacing
the slot values.

.coNP Function @ reset-struct
.synb
.mets (reset-struct << struct-obj )
.syne
.desc
The
.code reset-struct
function reinitializes the structure object
.meta struct-obj
as if it were being newly created.
First, all the slots are set to
.code nil
as if by the
.code clear-struct
function. Then the slots are initialized by invoking the
initialization functions, in order of the supertype ancestry, just as would be
done for a new structure object created by
.code make-struct
with an empty
.meta slot-init-plist
and no boa arguments.

Note that finalizers registered against
.meta struct-obj
are not invoked, and remain registered.
If the structure has state which is cleaned up by
finalizers, it is advisable to invoke them using
.code call-finalizers
prior to using
.codn reset-struct ,
or to take other measures to deal with the
situation.

.coNP Function @ replace-struct
.synb
.mets (replace-struct < target-obj << source-obj )
.syne
.desc
The
.code replace-struct
function causes
.meta target-obj
to take on the attributes of
.meta source-obj
without changing its identity.

The type of
.code target-obj
is changed to that of
.codn source-obj .

All instance slots of
.code target-obj
are discarded, and it is given new slots,
which are copies of the instance slots of
.codn source-obj .

Because of the type change,
.code target-obj
implicitly loses all of its original static slots,
and acquires those of
.codn "source obj" .

Note that finalizers registered against
.meta target-obj
are not invoked, and remain registered.
If
.meta target-obj
has state which is cleaned up by
finalizers, it is advisable to invoke them using
.code call-finalizers
prior to using
.codn replace-struct ,
or to take other measures to handle the situation.

.coNP Function @ method
.synb
.mets (method < struct-obj << slot-name )
.syne
.desc
The
.code method
function retrieves a function from a structure's slot
and binds that function's left argument to the
structure.

The
.meta struct-obj
argument must be a structure, and
.meta slot-name
must be a symbol denoting a slot in that structure.
The slot must hold a function of at least one
argument.

The
.code method
function returns a function which, when invoked,
calls the function previously retrieved from the object's
slot, passing to that function
.meta struct-obj
as the leftmost argument, followed by the function's
own arguments.

Note: the
.code meth
macro is an alternative interface which is suitable if
the slot name isn't a computed value.

.coNP Function @ super-method
.synb
.mets (super-method < struct-obj << slot-name )
.syne
.desc
The
.code super-method
function retrieves a function from a static
slot belonging to the supertype of the structure type of
.metn struct-obj .

It then returns a function which binds
that function's left argument to the structure.

The
.meta struct-obj
argument must be a structure which has a supertype, and
.meta slot-name
must be a symbol denoting a static slot in that supertype.
The slot must hold a function of at least one
argument.

The
.code super-method
function returns a function which, when invoked,
calls the function previously retrieved from
the supertype's static slot, passing to that function
.meta struct-obj
as the leftmost argument, followed by the function's
own arguments.

.coNP Function @ umethod
.synb
.mets (umethod << slot-name )
.syne
.desc
The
.code umethod
returns a function which represents the set of all methods named by
the slot
.meta slot-name
in all structure types, including ones not yet defined.
The
.meta slot-name
argument must be a symbol.

This function must be called with at least one argument. The leftmost
argument must be an object of structure type, which has a slot named
.metn slot-name .
The function will retrieve the value of the slot from that object,
expecting it to be a function, and calls it, passing to it all of its
arguments.

Note: the
.code umethod
name stands for "unbound method". Unlike the
.code method
function,
.code umethod
doesn't return a method whose leftmost argument is already bound to
an object; the binding occurs at call time.

.coNP Function @ uslot
.synb
.mets (uslot << slot-name )
.syne
.desc
The
.code uslot
returns a function which represents all slots named
.meta slot-name
in all structure types, including ones not yet defined.
The
.meta slot-name
argument must be a symbol.

The returned function must be called with exactly one argument.
The argument must be a structure which has a slot named
.metn slot-name .
The function will retrieve the value of the slot from that object
and return it.

Note: the
.code uslot
name stands for "unbound slot". The returned function
isn't bound to a particular object. The binding of
.code slot-name
to a slot in the structure object occurs when the function is called.

.coNP Function @ slotp
.synb
.mets (slotp < type << name )
.syne
.desc
The
.code slotp
function returns
.code t
if name
.meta name
is a symbol which names a slot in the structure type
.metn type .
Otherwise it returns
.codn nil .

The
.meta type
argument must be a structure type, or else a symbol
which names a structure type.

.coNP Function @ static-slot-p
.synb
.mets (static-slot-p < type << name )
.syne
.desc
The
.code static-slot-p
function returns
.code t
if name
.meta name
is a symbol which names a slot in the structure type
.metn type ,
and if that slot is a static slot.
Otherwise it returns
.codn nil .

The
.meta type
argument must be a structure type, or else a symbol
which names a structure type.

.coNP Function @ static-slot
.synb
.mets (static-slot < type << name )
.syne
.desc
The
.code static-slot
function retrieves the value of the static slot
named by symbol
.meta name
of the structure type
.metn type .

The
.meta type
argument must be a structure type or a symbol which names a
structure type, and
.meta name
must be a static slot of this type.

.coNP Function @ static-slot-set
.synb
.mets (static-slot-set < type < name << new-value )
.syne
.desc
The
.code static-slot-set
function stores
.meta new-value
into the static slot named by symbol
.meta name
of the structure type
.metn type .

It returns
.metn new-value .

The
.meta type
argument must be a structure type or the name of a structure type, and
.meta name
must be a static slot of this type.

.coNP Function @ static-slot-ensure
.synb
.mets (static-slot-ensure < type < name < new-value <> [ no-error-p ])
.syne
.desc
The
.code static-slot-ensure
first ensures that the struct type
.meta type
and all struct types derived from it have a static slot called
.metn name .
The slot is added as a static slot to every eligible type which doesn't already
have an instance or static slot by that name.

Then,
.meta new-value
is stored into all of the
.meta name
static slots of
.meta type
and all its derived types.

If
.meta type
itself already has an instance slot called
.meta name
then an error is thrown, and the function has no effect.  If the same situation
is true of the subtypes of
.meta type
then the situation is ignored: for those subtypes, no static slot is added, and
.meta new-value
is not stored. If the
.meta no-error-p
argument is present, and its value is true, then
.meta type
is treated just like the subtypes: if it has a conflicting instance slot,
then the situation is ignored and the subtypes are processed anyway.

.coNP Function @ call-super-method
.synb
.mets (call-super-method < struct-obj < name << argument *)
.syne
.desc
The
.code call-super-method
retrieves the function stored in the slot
.meta name
of the supertype of
.meta struct-obj
and invokes it, passing to that function
.meta struct-obj
as the leftmost argument, followed by the given
.metn argument -s,
if any.

The
.meta struct-obj
argument must be of structure type. Moreover,
that structure type must be derived from another structure type,
and
.meta name
must name a static slot of that structure type.

The object retrieved from that static slot must be
callable as a function, and accept the arguments.

.coNP Function @ call-super-fun
.synb
.mets (call-super-fun < type < name << argument *)
.syne
.desc
The
.code call-super-method
retrieves the function stored in the slot
.meta name
of the supertype of
.meta type
and invokes it, passing to that function the given
.metn argument -s,
if any.

The
.meta type
argument must be a structure type. Moreover,
that structure type must be derived from another structure type,
and
.meta name
must name a static slot of that structure type.

The object retrieved from that static slot must be
callable as a function, and accept the arguments.

.coNP Macro @ with-objects
.synb
.mets (with-objects >> ({( sym << init-form )}*) << body-form *)
.syne
.desc
The
.code with-objects
macro provides a binding construct very similar to
.codn let* .

Each
.meta sym
must be a symbol suitable for use as a variable name.

Each
.meta init-form
is evaluated in sequence, and a binding is established for its
corresponding
.meta sym
which is initialized with the value of that form. The binding
is visible to subsequent
.metn init-form -s.

Additionally, the values of the
.metn init-form -s
are noted as they are produced.  When the
.code with-objects
form terminates, by any means, the
.code call-finalizers
function is invoked on each value which was returned by an
.meta init-form
and had been noted. These calls are performed in the
reverse order relative to the original evaluation of the forms.

After the variables are established and initialized, the
.metn body-form -s
are evaluated in the scope of the variables. The value of the
last form is returned, or else
.code nil
if there are no forms. The invocations of
.code call-finalizers
take place just before the value of the last form is returned.

.SS* Sequence Manipulation
.coNP Function @ seqp
.synb
.mets (seqp << object )
.syne
.desc
The function
.code seqp
returns
.code t
if
.meta object
is a sequence, otherwise
.codn nil .

A sequence is defined as a list, vector or string. The object
.code nil
denotes
the empty list and so is a sequence.

.coNP Function @ length
.synb
.mets (length << sequence )
.syne
.desc
The
.code length
function returns the number of items in
.metn sequence ,
and
returns it.
.meta sequence
may be a hash, in which case
.cblk
.meti (hash-count << sequence )
.cble
is returned.

.coNP Function @ empty
.synb
.mets (empty << sequence )
.syne
.desc
Returns
.code t
if
.cblk
.meti (length << sequence )
.cble
is zero, otherwise
.codn nil .

.coNP Function @ copy
.synb
.mets (copy << object )
.syne
.desc
The
.code copy
function duplicates objects of various supported types: sequences, hashes,
structures and random states.  If
.meta object
is
.codn nil ,
it
returns
.codn nil .
If
.meta object
is a list, it returns
.cblk
.meti (copy-list << object ).
.cble
If
.meta object
is a string, it returns
.cblk
.meti (copy-str << object ).
.cble
If
.meta object
is a vector, it returns
.cblk
.meti (copy-vec << object ).
.cble
If
.meta object
is a hash, it returns
.cblk
.meti (copy-hash << object ).
.cble
If
.meta object
is a structure, it returns
.cblk
.meti (copy-struct << object ).
.cble
Lastly, if
.meta object
is a random state, it returns
.cblk
.meti (make-random-state << object ).
.cble

Except in the case when
.meta sequence
is
.codn nil ,
.code copy
returns a value that
is distinct from (not
.code eq
to)
.metn sequence .
This is different from
the behavior of
.cblk
.meti >> [ sequence 0..t]
.cble
or
.cblk
.meti (sub < sequence 0 t)
.cble
which recognize
that they need not make a copy of
.metn sequence ,
and just return it.

Note however, that the elements of the returned sequence may be
eq to elements of the original sequence. In other words, copy is
a deeper copy than just duplicating the
.code sequence
value itself,
but it is not a deep copy.

.coNP Function @ sub
.synb
.mets (sub < sequence >> [ from <> [ to ]])
.syne
.desc
The
.code sub
function extracts a slice from input sequence
.metn sequence .
The slice is
a sequence of the same type as
.metn sequence .

If the
.meta from
argument is omitted, it defaults to
.codn 0 .
If the
.meta to
parameter is
omitted, it defaults to
.codn t .
Thus
.code "(sub a)"
means
.codn "(sub a 0 t)" .

The following equivalence holds between the
.code sub
function and
the DWIM-bracket syntax:

.cblk
  ;; from is not a list
  (sub seq from to) <--> [seq from..to]
.cble

The description of the
.code dwim
operator\(emin particular, the section
on Range Indexing\(emexplains the semantics of the range specification.

If the sequence is a list, the output sequence may share substructure
with the input sequence.

.coNP Function @ replace
.synb
.mets (replace < sequence < replacement-sequence >> [ from <> [ to ]])
.mets (replace < sequence < replacement-sequence << index-list )
.syne
.desc
The
.meta replace
function modifies
.meta sequence
in the ways described below.

The operation is destructive: it may work "in place" by modifying
the original sequence. The caller should retain the return value
and stop relying on the original input sequence.

The return value of
.code replace
is the modified
version of
.metn sequence .
This may be the same object as
.meta sequence
or it may be a newly allocated object.

Note that the form:

.cblk
  (set seq (replace seq new fr to))
.cble

has the same effect on the variable
.code seq
as the form:

.cblk
  (set [seq fr..to] new)
.cble

except that the former
.code set
form returns the entire modified sequence, whereas the latter
returns the value of the
.code new
argument.

The
.code replace
function has two invocation styles, distinguished by the
type of the third argument. If the third argument is a list or vector, then it
is deemed to be the
.meta index-list
parameter of the second form.
Otherwise, if the third argument is missing, or is not a list, then
it is deemed to be the
.meta from
argument of the first form.

The first form of the replace function replaces a contiguous subsequence of the
.meta sequence
with
.metn replacement-sequence .
The replaced subsequence may be empty,
in which case an insertion is performed. If
.meta replacement-sequence
is empty
(for example, the empty list
.codn nil ),
then a deletion is performed.

If the
.meta from
and
.meta to
arguments are omitted, their values default
to
.code 0
and
.code t
respectively.

The description of the dwim operator\(emin particular, the section
on Range Indexing\(emexplains the semantics of the range specification.

The second form of the replace function replaces a subsequence of
elements from
.meta sequence
given by
.metn index-list ,
with their counterparts
from
.metn replacement-sequence .
This form of the replace function does not insert
or delete; it simply overwrites elements. If
.meta replacement-sequence
and
.meta index-list
are of different lengths, then the shorter of the two determines
the maximum number of elements which are overwritten.
Furthermore, similar restrictions apply on
.meta index-list
as under the
select function. Namely, the replacement stops when an index value
in
.meta index-list
is encountered which is out of range for
.metn sequence .
furthermore, if
.meta sequence
is a list, then
.meta index-list
must
be monotonically increasing.

.coNP Function @ take
.synb
.mets (take < count << sequence )
.syne
.desc
The
.code take
function returns
.meta sequence
with all except the first
.meta count
items removed.

If
.meta sequence
is a list, then
.code take
returns a lazy list which produces the first
.meta count
items of sequence.

For other kinds of sequences, including lazy strings,
.code drop
works eagerly.

If
.meta count
exceeds the length of
.meta sequence
then a sequence is returned which has all the items.
This object may be
.meta sequence
itself, or a copy.

If
.meta count
is negative, it is treated as zero.

.coNP Functions @ take-while and @ take-until
.synb
.mets (take-while < predfun < sequence <> [ keyfun ])
.mets (take-until < predfun < sequence <> [ keyfun ])
.syne
.desc
The
.code take-while
and
.code take-until
functions return a prefix of
.meta sequence
whose items satisfy certain conditions.

The
.code take-while
function returns the longest prefix of
.meta sequence
whose elements, accessed through
.meta keyfun
satisfy the function
.metn predfun .

The
.meta keyfun
argument defaults to the identity function: the elements
of
.meta sequence
are examined themselves.

The
.code take-until
function returns the longest prefix of
.meta sequence
which consists of elements, accessed through
.metn keyfun ,
that do
.B not
satisfy
.meta predfun
followed by an element which does satisfy
.metn predfun .
If
.meta sequence
has no such prefix, then an empty sequence
is returned of the same kind as
.metn sequence .

If
.meta sequence
is a list, then these functions return a lazy list.

.coNP Function @ drop
.synb
.mets (drop < count << sequence )
.syne
.desc
The
.code drop
function returns
.meta sequence
with the first
.meta count
items removed.

If
.meta count
is negative, it is treated as zero.

If
.meta count
is zero, then
.meta sequence
is returned.

If
.meta count
exceeds the length of
.meta sequence
then an empty sequence is returned
of the same kind as
.metn sequence .

.coNP Functions @ drop-while and @ drop-until
.synb
.mets (drop-while < predfun < sequence <> [ keyfun ])
.mets (drop-until < predfun < sequence <> [ keyfun ])
.syne
.desc
The
.code drop-while
and
.code drop-until
functions return
.meta sequence
with a prefix of that sequence removed,
according to conditions involving
.meta predfun
and
.metn keyfun .


The
.code drop-while
function removes the longest prefix of
.meta sequence
whose elements, accessed through
.meta keyfun
satisfy the function
.metn predfun ,
and returns the remaining sequence.

The
.meta keyfun
argument defaults to the identity function: the elements
of
.meta sequence
are examined themselves.

The
.code drop-until
function removes the longest prefix of
.meta sequence
which consists of elements, accessed through
.metn keyfun ,
that do
.B not
satisfy
.meta predfun
followed by an element which does satisfy
.metn predfun .
A sequence of the remaining elements is
returned.

If
.meta sequence
has no such prefix, then a sequence
same as
.meta sequence
is returned, which may be
.meta sequence
itself or a copy.

.coNP Function @ butlast
.synb
.mets (butlast << sequence )
.syne
.desc
The
.code butlast
function returns the prefix of
.meta sequence
consisting of a copy of it, with the last item omitted.
If
.meta sequence
is empty, an empty sequence is returned.

Dialect note: the Common Lisp function
.code nbutlast
is not provided. The \*(TL
.code take
function provides the same functionality for lists (only with the
arguments reversed relative to
.codn nbutlast ),
and additionally provides lazy semantics, and works with vectors
and strings.

.coNP Function @ search
.synb
.mets (search < haystack < needle >> [ testfun <> [ keyfun ])
.syne
.desc
The
.code search
function determines whether the sequence
.meta needle
occurs as substring
within
.metn haystack ,
under the given comparison function
.meta testfun
and
key function
.metn keyfun .
If this is the case, then the zero-based position of
the leftmost occurrence of
.meta key
within
.meta haystack
is returned. Otherwise
.code nil
is returned to indicate that
.meta key
does not occur within
.metn haystack .
If
.meta key
is empty, then zero is always returned.

The arguments
.meta haystack
and
.meta needle
are sequences: lists, vectors
or strings, in any combination.

If
.meta needle
is not empty, then occurs at some position N within
.meta haystack
if
the first element of
.meta needle
matches the element at position N of
.metn haystack ,
the second element of
.meta needle
matches the element at position N+1 of
.meta haystack
and so forth, for all elements of
.metn needle .
A match between elements
is determined by passing each element through
.metn keyfun ,
and then comparing the resulting values using
.metn testfun .

If
.meta testfun
is supplied, it must be a function which can be
called with two arguments. If it is not supplied, it defaults to
.codn eql .

If
.meta keyfun
is supplied, it must be a function which can be called
with one argument. If it is not supplied, it defaults to
.codn identity .

.TP* Examples:

.cblk
  ;; fails because 3.0 doesn't match 3
  ;; under the default eql function
  [search #(1.0 3.0 4.0 7.0) '(3 4)] -> nil

  ;; occurrence found at position 1:
  ;; (3.0 4.0) matches (3 4) under =
  [search #(1.0 3.0 4.0 7.0) '(3 4) =] -> 1

  ;; "even odd odd odd even" pattern
  ;; matches at position 2
  [search #(1 1 2 3 5 7 8) '(2 1 1 1 2) : evenp] -> 2

  ;; Case insensitive string search
  [search "abcd" "CD" : chr-toupper] -> 2

  ;; Case insensitive string search
  ;; using vector of characters as key
  [search "abcd" #(#\eC #\eD) : chr-toupper] -> 2
.cble

.coNP Function @ rsearch
.synb
.mets (rsearch < haystack < needle >> [ testfun <> [ keyfun ])
.syne
.desc
The
.code rsearch
function is like
.code search
except that if
.meta needle
matches
.meta haystack
in multiple places,
.code rsearch
returns the right-most matching position rather than
the leftmost.

.coNP Functions @ ref and @ refset
.synb
.mets (ref < seq << index )
.mets (refset < seq < index << new-value )
.syne
.desc
The
.code ref
and
.code refset
functions perform array-like indexing into sequences.
The
.code ref
function retrieves an element of
.metn seq ,
whereas
.code refset
overwrites an
element of
.meta seq
with a new value.

The
.meta index
argument is based from zero, and negative values are permitted,
with a special meaning as described in the Range Indexing section under the
description of the
.code dwim
operator.

The
.code refset
function returns the new value.

The following equivalences hold between
.code ref
and
.codn refset ,
and the DWIM bracket syntax:

.cblk
  (ref seq idx) <--> [seq idx]

  (refset seq idx new) <--> (set [seq idx] new)
.cble

The difference is that
.code ref
and
.code refset
are first class functions which
can be used in functional programming as higher order functions, whereas the
bracket notation is syntactic sugar, and
.code set
is an operator, not a function.
Therefore the brackets cannot replace all uses of
.code ref
and
.codn refset .

.coNP Function @ update
.synb
.mets (update < sequence-or-hash << function )
.syne
.desc
The
.code update
function replaces each elements in a sequence, or each value
in a hash table, with the value of
.meta function
applied to that element
or value.

The sequence or hash table is returned.

.coNP Functions @, remq @ remql and @ remqual
.synb
.mets (remq < object << list )
.mets (remql < object << list )
.mets (remqual < object << list )
.syne
.desc
The
.codn remq ,
.code remql
and
.code remqual
functions produce a new list based on
.metn list ,
removing the items which are
.codn eq ,
.code eql
or
.code equal
to
.metn object .

The input
.meta list
is unmodified, but the returned list may share substructure
with it. If no items are removed, it is possible that the return value
is
.meta list
itself.

.coNP Functions @, remq @ remql* and @ remqual*
.synb
.mets (remq* < object << list )
.mets (remql* < object << list )
.mets (remqual* < object << list )
.syne
.desc
The
.codn remq* ,
.code remql*
and
.code remqual*
functions are lazy versions of
.codn remq ,
.code remql
and
.codn remqual .
Rather than computing the entire new list
prior to returning, these functions return a lazy list.

Caution: these functions can still get into infinite looping behavior.
For instance, in
.codn "(remql* 0 (repeat '(0)))" ,
.code remql
will keep consuming
the
.code 0
values coming out of the infinite list, looking for the first item that
does not have to be deleted, in order to instantiate the first lazy value.

.TP* Examples:
.cblk
  ;; Return a list of all the natural numbers, excluding 13,
  ;; then take the first 100 of these.
  ;; If remql is used, it will loop until memory is exhausted,
  ;; because (range 1) is an infinite list.

  [(remql* 13 (range 1)) 0..100]
.cble

.coNP Functions @, remove-if @, keep-if @ remove-if* and @ keep-if*
.synb
.mets (remove-if < predicate-function < list <> [ key-function ])
.mets (keep-if < predicate-function < list <> [ key-function ])
.mets (remove-if* < predicate-function < list <> [ key-function ])
.mets (keep-if* < predicate-function < list <> [ key-function ])
.syne
.desc
The
.code remove-if
function produces a list whose contents are those of
.meta list
but with those elements removed which satisfy
.metn predicate-function .
Those elements which are not removed appear in the same order.
The result list may share substructure with the input list,
and may even be the same list object if no items are removed.

The optional
.meta key-function
specifies how each element from the
.meta list
is transformed to an argument to
.metn predicate-function .
If this argument is omitted
then the predicate function is applied to the elements directly, a behavior
which is identical to
.meta key-function
being
.codn "(fun identity)" .

The
.code keep-if
function is exactly like
.codn remove-if ,
except the sense of
the predicate is inverted. The function
.code keep-if
retains those items
which
.code remove-if
will delete, and removes those that
.code remove-if
will preserve.

The
.code remove-if*
and
.code keep-if*
functions are like
.code remove-if
and
.codn keep-if ,
but produce lazy lists.

.TP* Examples:
.cblk
  ;; remove any element numerically equal to 3.
  (remove-if (op = 3) '(1 2 3 4 3.0 5)) -> (1 2 4 5)

  ;; remove those pairs whose first element begins with "abc"
  [remove-if (op equal [@1 0..3] "abc")
             '(("abcd" 4) ("defg" 5))
             car]
  -> (("defg" 5))

  ;; equivalent, without test function
  (remove-if (op equal [(car @1) 0..3] "abc")
             '(("abcd" 4) ("defg" 5)))
  -> (("defg" 5))
.cble

.coNP Functions @, countqual @ countql and @ countq
.synb
.mets (countq < object << list )
.mets (countql < object << list )
.mets (countqual < object << list )
.syne
.desc
The
.codn countq ,
.code countql
and
.code countqual
functions count the number of objects
in
.meta list
which are
.codn eq ,
.code eql
or
.code equal
to
.metn object ,
and return the count.

.coNP Function @ count-if
.synb
.mets (count-if < predicate-function < list <> [ key-function ])
.syne
.desc
The
.code count-if
function counts the number of elements of
.meta list
which satisfy
.meta predicate-function
and returns the count.

The optional
.meta key-function
specifies how each element from the
.meta list
is transformed to an argument to
.metn predicate-function .
If this argument is omitted
then the predicate function is applied to the elements directly, a behavior
which is identical to
.meta key-function
being
.codn "(fun identity)" .

.coNP Functions @, posq @ posql and @ posqual
.synb
.mets (posq < object << list )
.mets (posql < object << list )
.mets (posqual < object << list )
.syne
.desc
The
.codn posq ,
.code posql
and
.code posqual
functions return the zero-based position of the
first item in
.meta list
which is, respectively,
.codn eq ,
.code eql
or
.code equal
to
.metn object .

.coNP Functions @ pos and @ pos-if
.synb
.mets (pos < key < list >> [ testfun <> [ keyfun ]])
.mets (pos-if < predfun < list <> [ keyfun ])
.syne
.desc
The
.code pos
and
.code pos-if
functions search through
.meta list
for an item which matches
.metn key ,
or satisfies predicate function
.metn predfun ,
respectively.
They return the zero-based position of the matching item.

The
.meta keyfun
argument specifies a function which is applied to the elements
of
.meta list
to produce the comparison key. If this argument is omitted,
then the untransformed elements of
.meta list
are examined.

The
.code pos
function's
.meta testfun
argument specifies the test function which
is used to compare the comparison keys from
.meta list
to
.metn key .
If this argument is omitted, then the
.code equal
function is used.
The position of the first element
.meta list
whose comparison key (as
retrieved by
.metn keyfun )
matches the search (under
.metn testfun )
is
returned. If no such element is found,
.code nil
is returned.

The
.code pos-if
function's
.meta predfun
argument specifies a predicate function
which is applied to the successive comparison keys taken from
.meta list
by applying
.meta keyfun
to successive elements. The position of
the first element for which
.meta predfun
yields true is returned. If
no such element is found,
.code nil
is returned.

.coNP Functions @, rposq @, rposql @, rposqual @ rpos and @ rpos-if
.synb
.mets (rposq < object << list )
.mets (rposql < object << list )
.mets (rposqual < object << list )
.mets (rpos < key < list >> [ testfun <> [ keyfun ]])
.mets (rpos-if < predfun < list <> [ keyfun ])
.syne
.desc
These functions are counterparts of
.codn rposq ,
.codn rposql ,
.codn rposqual ,
.code rpos
and
.code rpos-if
which report position of the right-most matching item,
rather than the left-most.

.coNP Functions @ pos-max and @ pos-min
.synb
.mets (pos-max < sequence >> [ testfun <> [ keyfun ]])
.mets (pos-min < sequence >> [ testfun <> [ keyfun ]])
.syne
.desc
The
.code pos-min
and
.code pos-max
functions implement exactly the same algorithm; they
differ only in their defaulting behavior with regard to the
.meta testfun
argument.  If
.meta testfun
is not given, then the pos-max function defaults
.meta testfun
to the
.code greater
function, whereas
.code pos-min
defaults it to the
.code less
function.

If
.meta sequence
is empty, both functions return
.codn nil .

Without a
.meta testfun
argument, the
.code pos-max
function finds the zero-based
position index of the numerically maximum value occurring in
.metn sequence ,
whereas
.code pos-min
without a
.meta testfun
argument finds the index of the minimum
value.

If a
.meta testfun
argument is given, the two functions are equivalent.
The
.meta testfun
function must be callable with two arguments.
If
.meta testfun
behaves like a greater-than comparison, then
.code pos-max
and
.code pos-min
return the index of the maximum element. If
.meta testfun
behaves like a
.code less-than
comparison, then the functions return
the index of the minimum element.

The
.meta keyfun
argument defaults to the
.code identity
function. Each element
from
.meta sequence
is passed through this one-argument function, and
the resulting value is used in its place.

.coNP Function @ where
.synb
.mets (where < function << object )
.syne
.desc
If
.meta object
is a sequence, the
.code where
function returns
a list of the numeric indices of those of its elements which satisfy
.metn function .
The numeric indices appear in increasing order.

If
.meta object
is a hash, the
.code where
function returns an unordered list
of keys which have values which satisfy
.metn function .

.meta function
must be a function that can be called with one argument.
For each element of
.metn object ,
.meta function
is called with that element
as an argument.  If a
.cod2 non- nil
value is returned, then the zero-based index of
that element is added to a list. Finally, the list is returned.

.coNP Function @ select
.synb
.mets (select < object >> { index-list <> | function })
.syne
.desc
The
.code select
function returns an object, of the same kind as
.metn object ,
which consists of those elements of
.meta object
which are identified by
the indices in
.metn index-list ,
which may be a list or a vector.

If
.meta function
is given instead of
.metn index-list ,
then
.meta function
is invoked with
.meta object
as its argument. The return value is then taken as
if it were the
.meta index-list
argument .

If
.meta object
is a sequence, then
.meta index-list
consists of numeric
indices.  The
.code select
function stops processing
.meta object
upon encountering an
index inside
.meta index-list
which is out of range. (Rationale: without
this strict behavior,
.code select
would not be able to terminate if
.meta index-list
is infinite.)

If
.meta object
is a list, then
.meta index-list
must contain monotonically increasing
numeric values, even if no value is out of range, since the
.code select
function
makes a single pass through the list based on the assumption that indices
are ordered. (Rationale: optimization.)

If
.meta object
is a hash, then
.meta index-list
is a list of keys. A new hash is
returned which contains those elements of
.meta object
whose keys appear
in
.metn index-list .
All of
.meta index-list
is processed, even if it contains
keys which are not in
.metn object .

.coNP Function @ in
.synb
.mets (in < sequence < key >> [ testfun <> [ keyfun ]])
.mets (in < hash << key )
.syne
.desc
The
.code in
function tests whether
.meta key
is found inside
.meta sequence
or
.metn hash .

If the
.meta testfun
argument is specified, it specifies the function
which is used to comparison keys from the sequence
to
.metn key .
Otherwise the
.code equal
function is used.

If the
.meta keyfun
argument is specified, it specifies a function which
is applied to the elements of
.meta sequence
to produce the comparison keys. Without this
argument, the elements themselves are taken
as the comparison keys.

If the object being searched is a hash, then the
.meta keyfun
and
.meta testfun
arguments are ignored.

The
.code in
function returns
.code t
if it finds
.meta key
in
.meta sequence
or
.metn hash ,
otherwise
.codn nil .

.coNP Function @ partition
.synb
.mets (partition < sequence >> { index-list >> | index <> | function })
.syne
.desc
If
.meta sequence
is empty, then
.code partition
returns an empty list, and the
second argument is ignored; if it is
.metn function ,
it is not called.

Otherwise,
.code partition
returns a lazy list of partitions of
.metn sequence .
Partitions are consecutive, non-overlapping, non-empty sub-strings of
.metn sequence ,
of the same kind as
.metn sequence ,
such that if these sub-strings are catenated together in their order
of appearance, a sequence
.code equal
to the original is produced.

If the second argument is of the form
.metn index-list ,
it shall be a sequence of
strictly non-decreasing, integers. First, any leading negative or zero values
in this sequence are dropped. The
.code partition
function then divides
.meta sequence
according to the
indices in index list. The first partition begins with the first element of
.metn sequence .
The second partition begins at the first position in
.metn index-list ,
and so on. Indices beyond the length of the sequence are ignored.

If
.meta index-list
is empty then a one-element list containing the entire
.meta sequence
is returned.

If the second argument is a function, then this function is applied
to
.metn sequence ,
and the return value of this call is then used in place of the
second argument, which must be an
.meta index
or
.metn index-list .

If the second argument is an atom other than a function, it is assumed to be
an integer index, and is turned into an
.meta index-list
of one element.

.TP* Examples:
.cblk
  (partition '(1 2 3) 1) -> ((1) (2 3))

  ;; split the string where there is a "b"
  (partition "abcbcbd" (op where (op eql #\eb))) -> ("a" "bc"
                                                    "bc" "bd")
.cble

.coNP Functions @ split and @ split*
.synb
.mets (split < sequence >> { index-list >> | index <> | function })
.mets (split* < sequence >> { index-list >> | index <> | function })
.syne
.desc
If
.meta sequence
is empty, then both
.code split
and
.code split*
return an empty list, and the
second argument is ignored; if it is
.metn function ,
it is not called.

Otherwise,
.code split
returns a lazy list of pieces of
.metn sequence :
consecutive, non-overlapping, possibly empty sub-strings of
.metn sequence ,
of the same kind as
.metn sequence .
A catenation of these pieces in the order they appear would produce
a sequence that is
.code equal
to the original sequence.

The
.code split*
function differs from
.code split
in that the elements indicated by the split indices are removed.

If the second argument is of the form
.metn index-list ,
it shall be a sequence of increasing integers.
The
.code split
function divides
.meta sequence
according to the
indices in index list. The first piece always begins with the first
element of
.metn sequence .
Each subsequent piece begins with the position indicated by
an element of
.metn index-list .
Negative indices are ignored. Repeated values give rise to empty
pieces.
If
.meta index-list
includes index zero,
then an empty first piece is generated.
If
.meta index-list
includes an index greater than or equal to the length of
.meta sequence
(equivalently, an index beyond the last element of the sequence)
then an additional empty last piece is generated.

If
.meta index-list
is empty then a one-element list containing the entire
.meta sequence
is returned.

If the second argument is a function, then this function is applied
to
.metn sequence ,
and the return value of this call is then used in place of the
second argument, which must be an
.meta index
or
.metn index-list .

If the second argument is an atom other than a function, it is assumed to be
an integer index, and is turned into an
.meta index-list
of one element.

.TP* Examples:
.cblk
  (split '(1 2 3) 1) -> ((1) (2 3))

  (split "abc" 0) -> ("" "abc")
  (split "abc" 3) -> ("abc" "")
  (split "abc" 1) -> ("a" "bc")
  (split "abc" '(0 1 2 3)) -> ("" "a" "b" "c" "")
  (split "abc" '(1 2)) -> ("a" "b" "c")

  (split "abc" '(-1 1 2 15)) -> ("a" "b" "c")

  ;; triple split at makes two additional empty pieces
  (split "abc" '(1 1 1)) -> ("a" "" "" "bc")

  (split* "abc" 0) -> ("" "bc") ;; "a" is removed
  (split* "abc" '(0 1 2)) -> ("" "" "" "") ;; all characters removed
.cble

.coNP Function @ partition*
.synb
.mets (partition* < sequence >> { index-list >> | index <> | function })
.syne
.desc
If
.meta sequence
is empty, then
.code partition*
returns an empty list, and the
second argument is ignored; if it is
.metn function ,
it is not called.

If the second argument is of the form
.metn index-list ,
which is a sequence
of strictly increasing non-negative integers, then
.code partition*
produces a
lazy list of pieces taken from
.metn sequence .
The pieces are formed by
deleting from
.meta sequence
the elements at the positions given
in
.metn index-list .
The pieces are the non-empty sub-strings between
the deleted elements.

If
.meta index-list
is empty then a one-element list containing the entire
.meta sequence
is returned.

If the second argument is a function, then this function is applied
to
.metn sequence ,
and the return value of this call is then used in place of the
second argument, which must be an
.meta index
or
.metn index-list .

If the second argument is an atom other than a function, it is assumed to be
an integer index, and is turned into an
.meta index-list
of one element.

.TP* Examples:
.cblk
  (partition* '(1 2 3 4 5) '(0 2 4)) -> ((1) (3) (5))

  (partition* "abcd" '(0 3)) -> "bc"

  (partition* "abcd" '(0 1 2 3)) -> nil
.cble

.coNP Functions @ find and @ find-if
.synb
.mets (find < key < sequence >> [ testfun <> [ keyfun ]])
.mets (find-if < predfun < sequence <> [ keyfun ])
.syne
.desc
The
.code find
and
.code find-if
functions search through a sequence for an item which
matches a key, or satisfies a predicate function, respectively.

The
.meta keyfun
argument specifies a function which is applied to the elements
of
.meta sequence
to produce the comparison key. If this argument is omitted,
then the untransformed elements of the
.meta sequence
are searched.

The
.code find
function's
.meta testfun
argument specifies the test function which
is used to compare the comparison keys from
.meta sequence
to the search key.
If this argument is omitted, then the
.code equal
function is used.
The first element from the list whose comparison key (as retrieved by
.metn keyfun )
matches the search (under
.metn testfun )
is returned. If no such element is found,
.code nil
is returned.

The
.code find-if
function's
.meta predfun
argument specifies a predicate function
which is applied to the successive comparison keys pulled from the list
by applying
.meta keyfun
to successive elements. The first element
for which
.meta predfun
yields true is returned. If no such
element is found,
.code nil
is returned.

.coNP Functions @ rfind and @ rfind-if
.synb
.mets (rfind < key < sequence >> [ testfun <> [ keyfun ]])
.mets (rfind-if < predfun < sequence <> [ keyfun ])
.syne
.desc
The
.code rfind
and
.code rfind-if
functions are almost exactly like
.code find
and
.code find-if
except that if there are multiple matches for
.meta key
in
.metn sequence ,
they return the right-most element rather than
the leftmost.

.coNP Functions @ find-max and @ find-min
.synb
.mets (find-max < sequence >> [ testfun <> [ keyfun ]])
.mets (find-min < sequence >> [ testfun <> [ keyfun ]])
.syne
.desc
The
.code find-min
and
.code find-max
function implement exactly the same algorithm; they
differ only in their defaulting behavior with regard to the
.meta testfun
argument.  If
.meta testfun
is not given, then the find-max function defaults it to
the
.code greater
function, whereas
.code find-min
defaults it to the
.code less
function.

Without a
.meta testfun
argument, the
.code find-max
function finds the numerically
maximum value occurring in
.metn sequence ,
whereas
.code pos-min
without a
.meta testfun
argument finds the minimum value.

If a
.meta testfun
argument is given, the two functions are equivalent.
The
.meta testfun
function must be callable with two arguments.
If
.meta testfun
behaves like a greater-than comparison, then
.code find-max
and
.code find-min
both return the maximum element. If
.meta testfun
behaves like a less-than comparison, then the functions return
the minimum element.

The
.meta keyfun
argument defaults to the
.code identity
function. Each element
from
.meta sequence
is passed through this one-argument function, and
the resulting value is used in its place for the purposes of the
comparison. However, the original element is returned.

.coNP Function @ set-diff
.synb
.mets (set-diff < seq1 < seq2 >> [ testfun <> [ keyfun ]])
.syne
.desc
The
.code set-diff
function treats the sequences
.meta seq1
and
.meta seq2
as if they were sets
and computes the set difference: a sequence which contains those elements in
.meta seq1
which do not occur in
.metn seq2 .

.code set-diff
returns a sequence of the same kind as
.metn seq1 .

Element equivalence is determined by a combination of
.meta testfun
and
.metn keyfun .
Elements are compared pairwise, and each element of a pair is passed through
.meta keyfun
function to produce a comparison value. The comparison values
are compared using
.metn testfun .
If
.meta keyfun
is omitted, then the
untransformed elements themselves are compared, and if
.meta testfun
is omitted,
then the
.code equal
function is used.

If
.meta seq1
contains duplicate elements which do not occur in
.meta seq2
(and thus are preserved in the set difference) then these duplicates appear
in the resulting
sequence. Furthermore, the order of the items from
.meta seq1
is preserved.

.coNP Functions @, mapcar @ mappend @ mapcar* and @ mappend*
.synb
.mets (mapcar < function << sequence *)
.mets (mappend < function << sequence *)
.mets (mapcar* < function << sequence *)
.mets (mappend* < function << sequence *)
.syne
.desc
When given only one argument, the
.code mapcar
function returns
.codn nil .
.meta function
is never called.

When given two arguments, the
.code mapcar
function applies
.meta function
to each elements of
.meta sequence
and returns a sequence of the resulting values
in the same order as the original values.
The returned sequence is the same kind as
.metn sequence ,
if possible. If the accumulated values cannot be
elements of that type of sequence, then a list is returned.

When additional sequences are given as arguments, this filtering behavior is
generalized in the following way:
.code mapcar
traverses the sequences in parallel,
taking a value from each sequence as an argument to the function. If there
are two lists,
.meta function
is called with two arguments and so forth.
The traversal is limited by the length of the shortest sequence.
The return values of the function are collected into a new sequence which is
returned. The returned sequence is of the same kind as the leftmost
input sequence, unless the accumulated values cannot be elements of that type of
sequence, in which case a list is returned.

The
.code mappend
function works like
.codn mapcar ,
with the following difference.
Rather than accumulating the values returned by the function into a sequence,
mappend expects the items returned by the function to be sequences which
are catenated with
.codn append ,
and the resulting sequence is returned. The returned sequence is of the same
kind as the leftmost input sequence, unless the values cannot be elements
of that type of sequence, in which case a list is returned.

The
.code mapcar*
and
.code mappend*
functions work like
.code mapcar
and
.codn mappend ,
respectively.
However, they return lazy lists rather than generating the entire
output list prior to returning.

.TP* Caveats:

Like
.codn mappend ,
.code mappend*
must "consume" empty lists. For instance,
if the function being mapped puts out a sequence of
.codn nil -s,
then the result must be the empty list
.codn nil ,
because
.code "(append nil nil nil nil ...)"
is
.codn nil .

But suppose that
.code mappend*
is used on inputs which are infinite lazy
lists, such that the function returns
.code nil
values indefinitely.
For instance:

.cblk
  ;; Danger: infinite loop!!!
  (mappend* (fun identity) (repeat '(nil))) 
.cble

The
.code mappend*
function is caught in a loop trying to consume
and squash an infinite stream of
.codn nil -s,
and so doesn't return.

.TP* Examples:
.cblk
  ;; multiply every element by two
  (mapcar (lambda (item) (* 2 item)) '(1 2 3)) -> (4 6 8)

  ;; "zipper" two lists together
  (mapcar (lambda (le ri) (list le ri)) '(1 2 3) '(a b c)) '((1 a) (2 b) (3 c)))

  ;; like append, mappend allows a lone atom or a trailing atom:
  (mappend (fun identity) 3) -> (3)
  (mappend (fun identity) '((1) 2)) -> (1 . 2)

  ;; take just the even numbers
  (mappend (lambda (item) (if (evenp x) (list x))) '(1 2 3 4 5))
  -> (2 4)
.cble

.coNP Function @ mapdo
.synb
.mets (mapdo < function << sequence *)
.syne
.desc
The
.code mapdo
function is similar to
.codn mapcar ,
but always returns
.codn nil .
It is useful
when
.meta function
performs some kind of side effect, hence the "do" in the name,
which is a mnemonic for the execution of imperative actions.

When only the
.meta function
argument is given,
.meta function
is never called,
and
.code nil
is returned.

If a single
.meta sequence
argument is given, then
.code mapdo
iterates over
.metn sequence ,
invoking
.meta function
on each element.

If two or more
.meta sequence
arguments are given, then
.code mapdo
iterates over
the sequences in parallel, extracting parallel tuples of items. These
tuples are passed as arguments to
.metn function ,
which must accept as many
arguments as there are sequences.

.coNP Functions @ transpose and @ zip
.synb
.mets (transpose << sequence )
.mets (zip << sequence *)
.syne
.desc
The
.code transpose
function performs a transposition on
.metn sequence .
This means that the
elements of
.meta sequence
must be sequences.  These sequences are understood to be
columns; transpose exchanges rows and columns, returning a sequence of the rows
which make up the columns.  The returned sequence is of the same kind as
.metn sequence ,
and the rows are also the same kind of sequence as the first column
of the original sequence. The number of rows returned is limited by the
shortest column among the sequences.

All of the input sequences (the elements of
.metn sequence )
must have elements
which are compatible with the first sequence. This means that if the first
element of
.meta sequence
is a string, then the remaining sequences must be
strings, or else sequences of characters, or of strings.

The
.code zip
function takes variable arguments, and is equivalent to calling
.code transpose
on a list of the arguments. The following equivalences hold:

.synb
   (zip . x) <--> (transpose x)

   [apply zip x] <--> (transpose x)
.syne

.TP* Examples:
.cblk
  ;; transpose list of lists
  (transpose '((a b c) (c d e))) ->  ((a c) (b d) (c e))

  ;; transpose vector of strings:
  ;; - string columns become string rows
  ;; - vector input becomes vector output
  (transpose #("abc" "def" "ghij")) -> #("adg" "beh" "cfi")

  ;; error: transpose wants to make a list of strings
  ;; but 1 is not a character
  (transpose #("abc" "def" '(1 2 3))) ;; error!

  ;; String elements are catenated:
  (transpose #("abc" "def" ("UV" "XY" "WZ"))) -> #("adUV" "beXY" "cfWZ")

  (zip '(a b c) '(c d e)) ->  ((a c) (b d) (c e))
.cble

.coNP Functions @ window-map and @ window-mappend
.synb
.mets (window-map < range < boundary < function << sequence )
.mets (window-mappend < range < boundary < function << sequence )
.syne
.desc
The
.code window-map
and
.code window-mappend
functions process the elements of
.meta sequence
by passing arguments derived from each successive element to
.metn function .
Both functions return, if possible, a sequence of the same kind as
.codn sequence ,
otherwise a list.

Under
.codn window-map ,
values returned by
.meta function
are accumulated into a sequence of the same type as
.meta sequence
and that sequence is returned.  Under
.codn window-mappend ,
the values returned by the calls to
.meta function
are expected to be sequence which are appended together to
form the output sequence.

These functions are analogous to
.code mapcar
and
.codn mappend .
Unlike these, they operate only on a single sequence, and over this sequence
they perform a
.IR "sliding window mapping" ,
whose description follows.

The argument to the
.meta range
parameter must be a positive integer, not exceeding 512.
This parameter specified the amount of ahead/behind context on either
side of each element which is processed. It indirectly determines
the window size for the mapping. The window size is twice
.metn range ,
plus one. For instance if range is , then the window size is 5:
the element being processed lies at the center of the window, flanked
by two elements on either side, making five.

The
.meta function
argument must specify a function which accepts a number of arguments
corresponding to the window size. For instance if
.meta range
is 2,
making the window size 5,
then
.meta function
must accept 5 arguments. These arguments constitute the sliding
window being processed. Each time
.meta function
is called, the middle argument is the element being processed,
and the arguments surrounding it are its window.

When an element is processed from somewhere in the interior of
a sequence, where it is flanked on either side by at least
.meta range
elements, then the window is populated by those flanking elements
taken from
.metn sequence .

The
.meta boundary
parameter specifies the window contents which are used for the
processing of elements which are closer than
.meta range
to either end of the sequence.  The argument may be a sequence containing
at least twice
.meta range
number of elements (one less than the window size): if it has additional
elements, they are not used. If it is a list, it may be shorter than twice
.metn range .
The argument
may also be one of the two keyword symbols
.code :wrap
or
.codn :reflect ,
described below.

If
.meta boundary
is a sequence, it may be regarded as divided into two pieces of
.meta range
length. If it is a list of insufficient length, then missing elements
are supplied as
.code nil
to make two
.metn range 's
worth of elements. These two pieces then flank
.code sequence
on either end. The left half of
.meta boundary
is effectively prepended to the sequence, and the right half
effectively appended.
When the sliding window extends beyond the boundary of
.meta sequence
near its start or end, the window is populated from these
flanking elements obtained from
.metn boundary .

If
.meta boundary
is the keyword
.codn :wrap ,
then the sequence is effectively flanked by copies of itself on both
ends, repeated enough times to satisfy the window. For instance if
the sequence is
.code "(1 2 3)"
and the window size is 9 due to the value of
.meta range
being 7, then the behavior of
.code :wrap
is as if a
.meta boundary
were specified consisting of
.codn "(3 1 2 3 1 2 3 1)" .
The left flank is
.code "(3 1 2 3)"
and the right flank is
.code "(1 2 3 4)"
formed by repetitions of
.code "(1 2 3)"
surrounding it on either side, extending out to infinity, and chopped to
.metn range .

If
.meta boundary
is the keyword
.codn :reflect ,
then the sequence is effectively flanked by reversed copies of itself
on both ends, repeated enough times to satisfy the window.
For instance if the sequence is
.code "(1 2 3)"
and the window size is 9, then the behavior of
.code :wrap
is as if a
.meta boundary
were specified consisting of
.codn "(1 3 2 1 3 2 1 3)" .

.coNP Function @ interpose
.synb
.mets (interpose < sep << sequence )
.syne
.desc
The
.code interpose
function returns a sequence of the same type as
.metn sequence ,
in which the elements from
.meta sequence
appear with the
.meta sep
value inserted
between them.

If
.meta sequence
is an empty sequence or a sequence of length 1, then a
sequence identical to
.meta sequence
is returned. It may be a copy of
.meta sequence
or it may be
.meta sequence
itself.

If
.meta sequence
is a character string, then the value
.meta sep
must be a character.

It is permissible for
.metn sequence ,
or for a suffix of
.meta sequence
to be a lazy
list, in which case interpose returns a lazy list, or a list with a lazy
suffix.

.TP* Examples:
.cblk
  (interpose #\e- "xyz") -> "x-y-z"
  (interpose t nil) -> nil
  (interpose t #()) -> #()
  (interpose #\ea "") -> ""
  (interpose t (range 0 0)) -> (0)
  (interpose t (range 0 1)) -> (0 t 1)
  (interpose t (range 0 2)) -> (0 t 1 t 2)
.cble

.coNP Functions @ apply and @ iapply
.synb
.mets (apply < function <> [ arg * << trailing-args ])
.mets (iapply < function <> [ arg * << trailing-args ])
.syne
.desc
The
.code apply
function invokes
.metn function ,
optionally passing to it an argument
list. The return value of the
.code apply
call is that of
.metn function .

If no arguments are present after
.metn function ,
then
.meta function
is invoked without arguments.

If one argument is present after
.metn function ,
then it is interpreted as
.metn trailing-args .
If this is a sequence (a list, vector or string),
then the elements of the sequence are passed as individual arguments to
.metn function .
If
.meta trailing-args
is not a sequence, then
.meta function
is invoked
with an improper argument list, terminated by the
.meta trailing-args
atom.

If two or more arguments are present after
.metn function ,
then the last of these arguments is interpreted as
.metn trailing-args .
The previous arguments represent leading arguments which are applied to
.metn function ,
prior to the arguments taken from
.metn trailing-args .

Note that if
.meta trailing-args
value is an atom or an improper list, the function is then
invoked with an improper argument list. Only a variadic
function may be invoked with an improper argument lists.
Moreover, all of the function's required and optional
parameters must be satisfied by elements of the
improper list, such that the terminating atom either
matches the
.meta rest-param
directly (see the
.code lambda
operator) or else the
.meta rest-param
receives an improper list terminated by that atom.
To treat the terminating atom of an improper list as an
ordinary element which can satisfy a required or optional
function parameter, the
.code iapply
function may be used, described next.

The
.code iapply
function ("improper apply") is similar to
.codn apply ,
except with regard to the treatment of
.metn trailing-args .
Firstly, under
.codn iapply ,
if
.meta trailing-args
is an atom other than
.code nil
(possibly a sequence, such as a vector or string),
then it is treated as an ordinary argument:
.meta function
is invoked with a proper argument list, whose last element is
.metn trailing-args .
Secondly, if
.meta trailing-args
is a list, but an improper list, then the terminating atom of
.meta trailing-args
becomes an ordinary argument. Thus, in all possible cases,
.code iapply
treats an extra
.cod2 non- nil
atom as an argument, and never calls
.meta function
with an improper argument list.

.TP* Examples:
.cblk
  ;; '(1 2 3) becomes arguments to list, thus (list 1 2 3).
  (apply (fun list) '(1 2 3)) -> (1 2 3)

  ;; this effectively invokes (list 1 2 3 4)
  (apply (fun list) 1 2 '(3 4)) -> (1 2 3 4)

  ;; this effectively invokes (list 1 2 . 3)
  (apply (fun list) 1 2 3)) -> (1 2 . 3)

  ;; "abc" is separated into characters which become arguments of list
  (apply (fun list) "abc") -> (#\ea #\eb #\ec)
.cble

.TP* "Dialect Note:"
Note that some uses of this function that are necessary in other Lisp dialects
are not necessary in \*(TL. The reason is that in \*(TL, improper list
syntax is accepted as a compound form, and performs application:

.cblk
  (foo a b . x)
.cble

Here, the variables
.code a
and
.code b
supply the first two arguments for
.codn foo .
In
the dotted position,
.code x
must evaluate to a list or vector. The list or
vector's elements are pulled out and treated as additional arguments for
.codn foo .
Of course, this syntax can only be used if
.code x
is a symbolic form or an atom.  It
cannot be a compound form, because
.code "(foo a b . (x))"
and
.code "(foo a b x)"
are equivalent structures.

.coNP Functions @ reduce-left and @ reduce-right
.synb
.mets (reduce-left < binary-function < list
.mets \ \ \ \ \ \ \ \ \ \ \ \  >> [ init-value <> [ key-function ]])

.mets (reduce-right < binary-function < list
.mets \ \ \ \ \ \ \ \ \ \ \ \ \  >> [ init-value <> [ key-function ]])
.syne
.desc
The
.code reduce-left
and
.code reduce-right
functions reduce lists of operands specified
by
.meta list
and
.meta init-value
to a single value by the repeated application of
.metn binary-function .

An effective list of operands is formed by combining
.meta list
and
.metn init-value .
If
.meta key-function
is specified, then the items of
.meta list
are
mapped to a new values through
.metn key-function .
If
.meta init-value
is supplied,
then in the case of
.codn reduce-left ,
the effective list of operands is formed by
prepending
.meta init-value
to
.metn list .
In the case of
.codn reduce-right ,
the effective operand list is produced by appending
.meta init-value
to
.metn list .

The production of the effective list can be expressed like this,
though this is not to be understood as the actual implementation:

.cblk
  (append (if init-value-present (list init-value))
          [mapcar (or key-function identity) list]))))
.cble

In the
.code reduce-right
case, the arguments to
.code append
are reversed.

If the effective list of operands is empty, then
.meta binary-function
is called
with no arguments at all, and its value is returned. This is the only
case in which
.meta binary-function
is called with no arguments; in all
remaining cases, it is called with two arguments.

If the effective list contains one item, then that item is returned.

Otherwise, the effective list contains two or more items, and is decimated as
follows.

Note that an
.meta init-value
specified as
.code nil
is not the same as a missing
.metn init-value ;
this means that the initial value is the object
.codn nil .
Omitting
.meta init-value
is the same as specifying a value of
.code :
(the colon symbol).
It is possible to specify
.meta key-function
while omitting an
.meta init-value
argument. This is achieved by explicitly specifying
.code :
as the
.meta init-value
argument.

Under
.codn reduce-left ,
the leftmost pair of operands is removed
from the list and passed as arguments to
.metn binary-function ,
in the same order
that they appear in the list, and the resulting value initializes an
accumulator. Then, for each remaining item in the list,
.meta binary-function
is invoked on two arguments: the current accumulator value, and the next element
from the list. After each call, the accumulator is updated with the return
value of
.metn binary-function .
The final value of the accumulator is returned.

Under
.codn reduce-right ,
the list is processed right to left.  The rightmost
pair of elements in the effective list is removed, and passed as arguments to
.metn binary-function ,
in the same order that they appear in the list. The
resulting value initializes an accumulator. Then, for each remaining item in
the list,
.meta binary-function
is invoked on two arguments:  the
next element from the list, in right to left order, and the current
accumulator value. After each call, the accumulator is updated with the return
value of
.metn binary-function .
The final value of the accumulator is returned.

.TP* Examples:
.cblk
  ;;; effective list is (1) so 1 is returned
  (reduce-left (fun +) () 1 nil)  ->  1

  ;;; computes (- (- (- 0 1) 2) 3)
  (reduce-left (fun -) '(1 2 3) 0 nil) -> -6

  ;;; computes (- 1 (- 2 (- 3 0)))
  (reduce-right (fun -) '(1 2 3) 0 nil) -> 2

  ;;; computes (* 1 2 3)
  (reduce-left (fun *) '((1) (2) (3)) nil (fun first)) -> 6

  ;;; computes 1 because the effective list is empty
  ;;; and so * is called with no arguments, which yields 1.
  (reduce-left (fun *) nil)
.cble

.coNP Functions @, some @ all and @ none
.synb
.mets (some < sequence >> [ predicate-fun <> [ key-fun ]])
.mets (all < sequence >> [ predicate-fun <> [ key-fun ]])
.mets (none < sequence >> [ predicate-fun <> [ key-fun ]])
.syne
.desc
The
.codn some ,
.code all
and
.code none
functions apply a predicate test function
.meta predicate-fun
over a list of elements.  If the argument
.meta key-fun
is
specified, then elements of
.meta sequence
are passed into
.metn key-fun ,
and
.meta predicate-fun
is
applied to the resulting values. If
.meta key-fun
is omitted, the behavior is
as if
.meta key-fun
is the identity function. If
.meta predicate-fun
is omitted,
the behavior is as if
.meta predicate-fun
is the identity function.

These functions have short-circuiting semantics and return conventions similar
to the and and or operators.

The some function applies
.meta predicate-fun
to successive values
produced by retrieving elements of
.meta list
and processing them through
.metn key-fun .
If the list is empty, it returns
.codn nil .
Otherwise it returns the
first
.cod2 non- nil
return value returned by a call to
.meta predicate-fun
and
stops evaluating more elements. If
.meta predicate-fun
returns
.code nil
for all
elements, it returns
.metn nil .

The
.code all
function applies
.meta predicate-fun
to successive values
produced by retrieving elements of
.meta list
and processing them through
.metn key-fun .
If the list is empty, it returns
.codn t .
Otherwise, if
.meta predicate-fun
yields
.code nil
for any value, the
.code all
function immediately
returns without invoking
.meta predicate-fun
on any more elements.
If all the elements are processed, then the all function returns
the value which
.meta predicate-fun
yielded for the last element.

The
.code none
function applies
.meta predicate-fun
to successive values
produced by retrieving elements of
.meta list
and processing them through
.metn key-fun .
If the list is empty, it returns
.codn t .
Otherwise, if
.meta predicate-fun
yields
.cod2 non- nil
for any value, the none function
immediately returns nil. If
.meta predicate-fun
yields nil for all
values, the none function returns
.codn t .

.TP* Examples:

.cblk
  ;; some of the integers are odd
  [some '(2 4 6 9) oddp] -> t

  ;; none of the integers are even
  [none '(1 3 4 7) evenp] -> t
.cble

.coNP Function @ multi
.synb
.mets (multi < function << sequence *)
.syne
.desc
The
.code multi
function distributes an arbitrary list processing function
.meta multi
over multiple sequences given by the
.meta list
arguments.

The
.meta sequence
arguments are first transposed into a single list of tuples. Each
successive element of this transposed list consists of a tuple of the
successive items from the lists. The length of the transposed list is that
of the shortest
.meta list
argument.

The transposed list is then passed to
.meta function
as an argument.

The
.meta function
is expected to produce a list of tuples, which are transposed
again to produce a list of lists which is then returned.

Conceptually, the input sequences are columns and
.meta function
is invoked on
a list of the rows formed from these columns. The output of
.meta function
is a transformed list of rows which is reconstituted into a list of columns.

.TP* Example:

.cblk
  ;; Take three lists in parallel, and remove from all of them
  ;; them the element at all positions where the third list
  ;; has an element of 20.

  (multi (op remove-if (op eql 20) @1 third)
         '(1 2 3)
         '(a b c)
         '(10 20 30))

  -> ((1 3) (a c) (10 30))

  ;; The (2 b 20) "row" is gone from the three "columns".

  ;; Note that the (op remove if (op eql 20) @1 third)
  ;; expression can be simplified using the ap operator:
  ;;
  ;; (op remove-if (ap eql @3 20))
.cble

.coNP Function @ sort
.synb
.mets (sort < sequence >> [ lessfun <> [ keyfun ]])
.syne
.desc
The
.code sort
function destructively sorts
.metn sequence ,
producing a sequence
which is sorted according to the
.meta lessfun
and
.meta keyfun
arguments.

The
.meta keyfun
argument specifies a function which is applied to elements
of the sequence to obtain the key values which are then compared
using the lessfun. If
.meta keyfun
is omitted, the identity function is used
by default: the sequence elements themselves are their own sort keys.

The
.meta lessfun
argument specifies the comparison function which determines
the sorting order. It must be a binary function which can be invoked
on pairs of keys as produced by the key function. It must
return a
.cod2 non- nil
value if the left argument is considered to be lesser
than the right argument. For instance, if the numeric function
.code <
is used
on numeric keys, it produces an ascending sorted order. If the function
.code >
is used, then a descending sort is produced. If
.meta lessfun
is omitted, then it defaults to the generic
.code less
function.

The
.code sort
function is stable for sequences which are lists. This means that the
original order of items which are considered identical is preserved.
For strings and vectors,
.code sort
is not stable.

.coNP Function @ shuffle
.synb
.mets (shuffle << sequence )
.syne
.desc
The
.code shuffle
function pseudo-randomly rearranges the elements of
.metn sequence .
This is performed in place:
.meta sequence
object is modified.

The return value is
.meta sequence
itself.

The rearrangement depends on pseudo-random numbers obtained from the
.code rand
function.

.coNP Function @ sort-group
.synb
.mets (sort-group < sequence >> [ keyfun <> [ lessfun ]])
.syne
.desc
The
.code sort-group
function sorts
.meta sequence
according to the
.meta keyfun
and
.meta lessfun
arguments, and then breaks the resulting sequence into groups,
based on the equivalence of the elements under
.metn keyfun .

The following equivalence holds:

.cblk
  (sort-group sq lf kf) <--> (partition-by kf (sort (copy sq) kf lf))
.cble

Note the reversed order of
.meta keyfun
and
.meta lessfun
arguments between
.code sort
and
.codn sort-group .

.coNP Function @ uniq
.synb
.mets (uniq << sequence )
.syne
.desc
The
.code uniq
function returns a sequence of the same kind as
.metn sequence ,
but with
duplicates removed. Elements of
.meta sequence
are considered equal under
the
.code equal
function. The first occurrence of each element is retained,
and the subsequent duplicates of that element, of any, are suppressed,
such that the order of the elements is otherwise preserved.

The following equivalence holds between
.code uniq
and
.codn unique :

.cblk
  (uniq s) <--> [unique s : :equal-based]
.cble

That is,
.code uniq
is like
.code unique
with the default
.meta keyfun
argument (the
.code identity
function) and an
.codn equal -based
hash table.

.coNP Function @ unique
.synb
.mets (uniq < sequence >> [ keyfun <> { hash-arg }* ])
.syne
.desc
The
.code unique
function is a generalization of
.codn uniq .
It returns a sequence of the same kind as
.metn sequence ,
but with duplicates removed.

If neither
.meta keyfun
nor
.metn hash-arg -s
are specified, then elements of sequence are considered equal under the
.code eql
function. The first occurrence of each element is retained,
and the subsequent duplicates of that element, of any, are suppressed,
such that the order of the elements is otherwise preserved.

If
.meta keyfun
is specified, then that function is applied to each element,
and the resulting values are compared for equality.
In other words, the behavior is as if
.meta keyfun
were the
.code identity
function.

If one or more
.metn hash-arg -s
are present, these specify the arguments for the construction of
the internal hash table used by
.codn unique .
The arguments are like those of the
.code hash
function. In particular, the argument
.code :equal-based
causes
.code unique
to use
.code equal
equality.

.coNP Function @ tuples
.synb
.mets (tuples < length < sequence <> [ fill-value ])
.syne
.desc
The
.code tuples
function produces a lazy list which represents a reorganization
of the elements of
.meta sequence
into tuples of
.metn length ,
where
.meta length
must be a positive integer.

The length of the sequence might not be evenly divisible by the tuple length.
In this case, if a
.meta fill-value
argument is specified, then the last tuple
is padded with enough repetitions of
.meta fill-value
to make it have
.meta length
elements. If
.meta fill-value
is not specified, then the last tuple is left
shorter than
.metn length .

The output of the function is a list, but the tuples themselves are sequences
of the same kind as
.metn sequence .
If
.meta sequence
is any kind of list, they
are lists, and not lazy lists.

.TP* Examples:

.cblk
  (tuples 3 #(1 2 3 4 5 6 7 8) 0) -> (#(1 2 3) #(4 5 6) #(7 8 0))
  (tuples 3 "abc") -> ("abc")
  (tuples 3 "abcd") -> ("abc" "d")
  (tuples 3 "abcd" #\ez) -> ("abc" "dzz")
  (tuples 3 (list 1 2) #\ez) -> ((1 2 #\ez))
.cble

.coNP Function @ partition-by
.synb
.mets (partition-by < function << sequence )
.syne
.desc
If
.meta sequence
is empty, then
.code partition-by
returns an empty list,
and
.meta function
is never called.

Otherwise,
.code partition-by
returns a lazy list of partitions of the sequence
.metn sequence .
Partitions are consecutive, non-empty sub-strings of
.metn sequence ,
of the same kind as
.metn sequence .

The partitioning begins with the first element of
.meta sequence
being placed into a partition.

The subsequent partitioning is done according to
.metn function ,
which is applied
to each element of
.metn sequence .
Whenever, for the next element, the function
returns the same value as it returned for the previous element, the
element is placed into the same partition. Otherwise, the next element
is placed into, and begins, a new partition.

The return values of the calls to
.meta function
are compared using the
.code equal
function.

.TP* Examples:

.cblk
  [partition-by identity '(1 2 3 3 4 4 4 5)] -> ((1) (2) (3 3)
                                                 (4 4 4) (5))

  (partition-by (op = 3) #(1 2 3 4 5 6 7)) -> (#(1 2) #(3)
                                               #(4 5 6 7))
.cble

.coNP Function @ make-like
.synb
.mets (make-like < list << ref-sequence )
.syne
.desc
The
.meta list
argument must be a list.  If
.meta ref-sequence
is a sequence type,
then
.meta list
is converted to the same type of sequence and returned.
Otherwise the original
.meta list
is returned.

Note: the
.code make-like
function is a helper which supports the development of
unoptimized versions of a generic function that accepts any type of
sequence as input, and produces a sequence of the same type as output.
The implementation of such a function can internally accumulate a list, and
then convert the resulting list to the same type as an input value
by using
.codn make-like .

.coNP Function @ nullify
.synb
.mets (nullify << sequence )
.syne
.desc
The
.code nullify
function returns
.code nil
if
.meta sequence
is an empty sequence.
Otherwise it returns
.meta sequence
itself.

Note: the
.code nullify
function is a helper to support unoptimized generic
programming over sequences.  Thanks to the generic behavior of
.codn cdr ,
any sequence can be traversed using
.code cdr
functions, checking for the
.code nil
value as a terminator.  This, however, breaks for empty sequences which are not
lists, because they are not equal to
.codn nil :
to
.code car
and
.code cdr
they look like
a one-element sequence containing
.codn nil .
The
.code nullify
function reduces all empty
sequences to
.codn nil ,
thereby correcting the behavior of code which traverses
sequences using
.codn cdr ,
and tests for termination with
.codn nil .

.SS* Permutations and Combinations

.coNP Function @ perm
.synb
.mets (perm < seq <> [ len ])
.syne
.desc
The
.code rperm
function returns a lazy list which consists of all
length
.meta len
permutations of formed by items taken from
.metn seq .
The permutations do not use any element of
.meta seq
more than once.

Argument
.metn len ,
if present, must be a positive integer, and
.meta seq
must be a sequence.

If
.meta len
is not present, then its value defaults to the length of
.metn seq :
the list of the full permutations of the entire sequence is returned.

The permutations in the returned list are sequences of the same kind as
.codn seq .

If
.meta len
is zero, then a list containing one permutation is returned, and that
permutation is of zero length.

If
.meta len
exceeds the length of
.metn seq ,
then an empty list is returned,
since it is impossible to make a single non-repeating permutation that
requires more items than are available.

The permutations are lexicographically ordered.

.coNP Function @ rperm
.synb
.mets (rperm < seq << len )
.syne
.desc
The
.code rperm
function returns a lazy list which consists of all the repeating
permutations of length
.meta len
formed by items taken from
.metn seq .
"Repeating" means that the items from
.meta seq
can appear more than
once in the permutations.

The permutations which are returned are sequences of the same kind as
.metn seq .

Argument
.meta len
must be a nonnegative integer, and
.meta seq
must be a sequence.

If
.meta len
is zero, then a single permutation is returned, of zero length.
This is true regardless of whether
.meta seq
is itself empty.

If
.meta seq
is empty and
.meta len
is greater than zero, then no permutations are
returned, since permutations of a positive length require items, and the
sequence has no items. Thus there exist no such permutations.

The first permutation consists of
.meta le
repetitions of the first element of
.metn seq .
The next repetition, if there is one, differs from the first
repetition in that its last element is the second element of
.metn seq .
That is to say, the permutations are lexicographically ordered.

.TP* Examples:

.cblk
  (rperm "01" 4) -> ("000" "001" "010" "011"
                     "100" "101" "110" "111")

  (rperm #(1) 3) -> (#(1 1 1))

  (rperm '(0 1 2) 2) -> ((0 0) (0 1) (0 2) (1 0)
                         (1 1) (1 2) (2 0) (2 1) (2 2))
.cble

.coNP Function @ comb
.synb
.mets (comb < seq << len )
.syne
.desc
The
.code comb
function returns a lazy list which consists of all
length
.meta len
non-repeating combinations formed by taking items taken from
.metn seq .
"Non-repeating combinations" means that the combinations do not use any
element of
.meta seq
more than once. If
.meta seq
contains no duplicates, then
the combinations contain no duplicates.

Argument
.meta len
must be a nonnegative integer, and
.meta seq
must be a sequence or a hash table.

The combinations in the returned list are objects of the same kind as
.metn seq .

If
.meta len
is zero, then a list containing one combination is returned, and that
combination is of zero length.

If
.meta len
exceeds the number of elements in
.metn seq ,
then an empty list is returned, since it is impossible to make a single
non-repeating combination that requires more items than are available.

If
.meta seq
is a sequence, the returned combinations are lexicographically ordered.
This requirement is not applicable when
.meta seq
is a hash table.

.TP* Example:
.cblk
   ;; powerset function, in terms of comb.
   ;; Yields a lazy list of all subsets of s,
   ;; expressed as sequences of the same type as s.

   (defun powerset (s)
     (mappend* (op comb s) (range 0 (length s))))
.cble

.coNP Function @ rcomb
.synb
.mets (rcomb < seq << len )
.syne
.desc
The
.code comb
function returns a lazy list which consists of all
length
.meta len
repeating combinations formed by taking items taken from
.metn seq .
"Repeating combinations" means that the combinations can use
an element of
.meta seq
more than once.

Argument
.meta len
must be a nonnegative integer, and
.meta seq
must be a sequence.

The combinations in the returned list are sequences of the same kind as
.metn seq .

If
.meta len
is zero, then a list containing one combination is returned, and that
combination is of zero length. This is true even if
.meta seq
is empty.

If
.meta seq
is empty, and
.meta len
is nonzero, then an empty list is returned.

The combinations are lexicographically ordered.


.SS* Macros
\*(TL supports structural macros. \*(TX's model of macroexpansion is that
\*(TL code is processed in two phases: the expansion phase and the
evaluation phase. The expansion phase is invoked on Lisp code early during the
processing of source code. For instance when a \*(TX file containing a
.code "@(do ...)"
directive
is loaded, expansion of the Lisp forms are its arguments takes place during the
parsing of the entire source file, and is complete before any of the code in
that file is executed. If the
.code "@(do ...)"
form is later executed,
the expanded forms are then evaluated.

\*(TL also supports symbol macros, which are symbolic forms that stand
for forms, with which they are replaced at macro expansion time.

When Lisp data is processed as code by the
.code eval
function, it is first expanded,
and so processed in its entirety in the expansion phase. Then it is processed
in the evaluation phase.

.NP* Macro parameter lists

\*(TX macros support destructuring, similarly to Common Lisp macros.
This means that macro parameter lists are like function argument lists,
but support nesting. A macro parameter list can specify a nested parameter
list in every place where an argument symbol may appear.  For instance,
consider this macro parameter list:

.cblk
  ((a (b c)) : (c frm) ((d e) frm2 de-p) . g)
.cble

The top-level of this nested form has the structure

.cblk
.meti \ \  >> ( I : < J < K . << L )
.cble

in which we can identify the major constituent positions as
.metn I ,
.metn J ,
.meta K
and
.metn L .

The constituent at position
.meta I
is the mandatory parameter
.codn "(a (b c))" .
Position
.meta J
holds the optional parameter
.code c
(with default init form
.codn frm ).
At
.meta K
is found the optional parameter
.code "(d e)"
(with default init form
.code frm2
and presence-indicating variable
.codn de-p ).
Finally, the parameter in the dot position
.meta L
is
.codn g ,
which captures trailing arguments.

Obviously, some of the parameters are compound expressions rather
than symbols:
.code "(a (b c))"
and
.codn "(d e)" .
These compounds express nested macro parameter lists.

Nested macro parameter lists recursively match the corresponding structure
in the argument object.  For instance if a simple argument would capture
the structure
.code "(1 (2 3))"
then we can replace the argument with the nested argument list
.code "(a (b c))"
which destructures the
.code "(1 (2 3))"
such that the parameters
.codn a ,
.code b
and
.code c
will end up bound
to
.codn 1 ,
.code 2
and
.codn 3 ,
respectively.

Nested macro parameter lists have all the features of the top-level
macro parameter lists: they can have optional arguments with default
values, use the dotted position, and contain the
.codn :env ,
.code :whole
and
.code :form
special parameters, which are described below.  
In nested parameter lists, the binding strictness is relaxed for optional
parameters. If
.code "(a (b c))"
is optional, and the argument is, say,
.codn (1) ,
then
.code a
gets
.codn 1 ,
and
.code b
and
.code c
receive
.codn nil .

Macro parameter lists also supports three special keywords, namely
.codn :env ,
.code :whole
and
.codn :form .

The parameter list
.code "(:whole x :env y :form z)"
will bind parameter
.code x
to the entire
macro parameter list, bind parameter
.code y
to the macro environment and bind parameter
.code z
to the entire macro form (the original compound form used to invoke the
macro).

The
.codn :env ,
.code :whole
and
.code :form
notations can occur anywhere in a macro parameter list, other than
to the right of the consing dot. They can be used in nested
macro parameter lists also.  Note that in a nested macro
parameter list,
.code :form
and
.code :env
do not change meaning: they bind the same object as they would in
the top-level of the macro parameter list.
However the
.code :whole
parameter inside has a restricted scope in a nested parameter
list: its parameter will capture just that part of the argument material which
matches that parameter list, rather than the entire argument list.

.TP* "Dialect Note:"

In ANSI Common Lisp, the lambda list keyword
.code &whole
binds its corresponding variable to the entire macro form, whereas
\*(TL's
.code :whole
binds its variable only to the arguments of the macro form.

Note, however, that ANSI CL distinguishes destructuring lambda lists
and macro lambda lists and the
.code &whole
parameter has a different behavior between the two.  Under
.codn destructuring-bind ,
the
.code &whole
parameter receives just the arguments, just like the behavior
of \*(TL's
.code :whole
parameter.

\*(TL does not distinguish destructuring and macro lambda lists;
they are the same and behave the same way. Thus
.code :whole
is treated the same way in macros as in
.code tree-bind
and related binding operators: it binds just the arguments
to the parameter. \*(TL has the special parameter
.code :form
by means of which macros can access their invoking form.
This parameter is also supported in
.code tree-bind
and binds to the entire
.code tree-bind
form.

.coNP Operator @ macro-time
.synb
.mets (macro-time << form *)
.syne
.desc
The
.code macro-time
operator has a syntax similar to the
.code progn
operator. Each
.meta form
is evaluated from left to right, and the resulting value is that of the last
form.

The special behavior of
.code macro-time
is that the evaluation takes place during
the expansion phase, rather than during the evaluation phase.

During the expansion phase, all
.code macro-time
expressions which occur in a context
that calls for evaluation are evaluated, and replaced by their quoted values.
For instance
.code "(macro-time (list 1 2 3))"
evaluates
.code "(list 1 2 3)"
to the object
.code "(1 2 3)"
and the entire
.code macro-time
form is replaced by that value, quoted:
.codn "'(1 2 3)" .
If the form is evaluated again at evaluation-time, the resulting value will be
that of the quote, in this case
.codn "(1 2 3)" .

.code macro-time
forms do not see the surrounding lexical environment; the see only
global function and variable bindings and macros.

Note 1:
.code macro-time
is intended for defining helper functions and variables that
are used by macros. A macro cannot "see" a
.code defun
function or
.code defvar
variable
because
.code defun
and
.code defvar
forms are evaluated at evaluation time, which occurs
after expansion time.  The macro-time operator hoists the evaluation of these
forms to macro-expansion time.

Note 2:
.code defmacro
forms are implicitly in macro-time; they do not have to
be wrapped with the
.code macro-time
operator. The
.code macro-time
operator doesn't have
to be used in programs whose macros do not make references to variables
or functions.

.coNP Operator @ defmacro
.synb
.mets (defmacro < name <> ( param * [: << opt-param * ] [. < rest-param ])
.mets \ \  << body-form *)
.syne
.desc
The
.code defmacro
operator is evaluated at expansion time. It defines a
macro-expander function under the name
.metn name ,
effectively creating a new operator.

Note that the parameter list is a macro parameter list, and not a
function parameter list. This means that each
.meta param
and
.meta opt-param
can be not only a symbol, but it can itself be a parameter list.
The corresponding argument is then treated as a structure which
matches that parameter list.  This nesting of parameter lists
can be carried to an arbitrary depth.

A macro is called like any other operator, and resembles a function.  Unlike in
a function call, the macro receives the argument expressions themselves, rather
than their values.  Therefore it operates on syntax rather than on values.
Also, unlike a function call, a macro call occurs in the expansion phase,
rather than the evaluation phase.

The return value of the macro is the macro expansion. It is substituted in
place of the entire macro call form. That form is then expanded again;
it may itself be another macro call, or contain more macro calls.

.TP* "Dialect Note:"
A macro in the global namespace introduced by
.code defmacro
may co-exist with a function of the same name introduced by
.codn defun .
This is not permitted in ANSI Common Lisp.

.TP* Example:

.cblk
  ;; dolist macro similar to Common Lisp's:
  ;;
  ;; The following will print 1, 2 and 3
  ;; on separate lines:
  ;; and return 42.
  ;;
  ;; (dolist (x '(1 2 3) 42)
  ;;   (format t "~s\en"))

  (defmacro dolist ((var list : result) . body)
    (let ((i (my-gensym)))
      ^(for ((i ,list)) (i ,result) ((set i (cdr i)))
         (let ((,var (car i)))
           ,*body))))
.cble

.coNP Operator @ macrolet
.synb
.mets (macrolet >> ({( name < macro-style-params << macro-body-form *)}*)
.mets \ \  << body-form *)
.syne
.desc
The
.code macrolet
binding operator extends the macro-time lexical environment
by making zero or more new local macros visible.

The
.code macrolet
symbol is followed by a list of macro definitions.
Each definition is a form which begins with a
.metn name ,
followed by
.meta macro-style-params
which is a macro parameter list, and zero or more
.metn macro-body-form -s.
These macro definitions are similar
to those globally defined by the
.code defmacro
operator, except that they
are in a local environment.

The macro definitions are followed by optional
.metn body-forms .
The macros specified in the definitions are visible to these
forms.

Forms inside the macro definitions such as the
.metn macro-body-form -s,
and initializer forms appearing in the
.meta macro-style-params
are subject
to macro-expansion in a scope in which none of the new macros being
defined are yet visible. Once the macro definitions are themselves
macro-expanded, they are placed into a new macro environment, which
is then used for macro expanding the
.metn body-form -s.

A
.code macrolet
form is fully processed in the expansion phase of a form, and is
effectively replaced by
.code progn
form which contains expanded versions of
.metn body-form -s.
This expanded structure shows no evidence that any
macrolet forms ever existed in it. Therefore, it is impossible for the code
evaluated in the bodies and parameter lists of
.code macrolet
macros to have any visibility to any surrounding lexical variable bindings,
which are only instantiated in the evaluation phase, after expansion is done
and macros no longer exist.

.coNP Function @ macro-form-p
.synb
.mets (macro-form-p < obj <> [ env ])
.syne
.desc
The
.code macro-form-p
function returns
.code t
if
.meta obj
represents the syntax of
a form which is a macro form: either a compound macro or a symbol macro.
Otherwise it returns
.codn nil .

A macro form is one that will transform under
.code macroexpand-1
or
.codn macroexpand ;
an object which isn't a macro form will not undergo expansion.

The optional
.meta env
parameter is a macroexpansion environment.
A macroexpansion environment is passed down to macros and can be received
via their special
.code :env
parameter.

.meta env
is used by
.code macro-form-p
to determine whether
.meta obj
is a macro in a lexical macro environment.

If
.meta env
is not specified or is
.codn nil ,
then
.code macro-form-p
only recognizes global macros.

.TP* Example:

.cblk
  ;; macro which translates to 'yes if its
  ;; argument is a macro from, or otherwise
  ;; transforms to the form 'no.

  (defmacro ismacro (:env menv form)
    (if (macro-form-p form menv)
     ''yes ''no))

  (macrolet ((local ()))
    (ismacro (local)))    ;; yields yes

  (ismacro (local))       ;; yields no

  (ismacro (ismacro foo)) ;; yields yes
.cble

During macro expansion, the global macro
.code ismacro
is handed the macro-expansion environment 
via
.codn ":env menv" .

When the macro is invoked within the macrolet,
this environment includes the macro-time lexical scope in which the
.code local
macro is defined. So when global checks whether the argument form
.code (local)
is a macro, the conclusion is yes: the (local) form is a macro
call in that environment:
.code macro-form-p
yields
.codn t .

When
.code "(global (local))"
is invoked outside of the macrolet, no local macro is visible is
there, and so
.code macro-form-p
yields
.codn nil .

.coNP Functions @ macroexpand-1 and @ macroexpand
.synb
.mets (macroexpand-1 < obj <> [ env ])
.mets (macroexpand < obj <> [ env ])
.syne
.desc
If
.meta obj
is a macro form (an object for which
.code macro-form-p
returns
.codn t ),
these functions expand the macro form and return the expanded form.
Otherwise, they return
.metn obj .

.code macroexpand-1
performs a single expansion, expanding just the macro
that is referenced by the symbol in the first position of
.metn obj ,
and returns the expansion. That expansion may itself be a macro form.

.code macroexpand
performs an expansion similar to
.codn macroexpand-1 .
If the result is
a macro form, then it expands that form, and keeps repeating this process
until the expansion yields a non-macro-form. That non-macro-form is then
returned.

The optional
.meta env
parameter is a macroexpansion environment.
A macroexpansion environment is passed down to macros and can be received
via their special
.code :env
parameter. The environment they receive is their
lexically apparent macro-time environment in which local macros may be
visible.  A macro can use this environment to "manually" expand some
form in the context of that environment.

.TP* Example:

.cblk
  ;; (foo x) expands x, and if x begins with a number,
  ;; it removes  the number and returns the resulting
  ;; form. Otherwise, it returns the entire form.

  (defmacro rem-num (:env menv some-form)
    (let ((expanded (macroexpand some-form menv)))
      (if (numberp (car expanded))
        (cdr expanded)
        some-form)))

  ;; The following yields (42 a).

  (macrolet ((foo () '(1 list 42))
             (bar () '(list 'a)))
    (list (rem-num (foo)) (rem-num (bar)))))
.cble

The
.code rem-num
macro is able to expand the
.code (foo)
and
.code (bar)
forms it receives as
the
.code some-form
argument, even though these forms use local macro that are only
visible in their local scope. This is thanks to the macro
environment passed to
.codn rem-num .
It is correctly able to work with the
expansions
.code "(1 list 42)"
and
.code "(list 'a)"
to produce
.code "(list 42)"
and
.code "(list 'a)"
which evaluate to
.code 42
and
.code a
respectively.

.coNP Functions @ lexical-var-p and @ lexical-fun-p
.synb
.mets (lexical-var-p < env << form )
.mets (lexical-fun-p < env << form )
.syne
.desc
These two functions are useful to macro writers. They are intended
to be called from the bodies of macro expanders, such as the bodies of
.code defmacro
or
.code macrolet
forms.  The
.meta env
argument is a macro-time environment, which is available to macros
via the special
.code :env
parameter. Using these functions, a macro can enquire whether
a given
.meta form
is a symbol which has a variable binding or a function binding
in the lexical environment.
This information is known during macro expansion. The macro expander
recognizes lexical function and variable bindings, because these
bindings can shadow macros.

.TP* Example:

.cblk
  ;;
  ;; this macro replaces itself with :lexical-var if its
  ;; argument is a lexical variable, :lexical-fun if
  ;; its argument is a lexical function, or with
  ;; :not-lex-fun-var if neither is the case.
  ;;
  (defmacro classify (sym :env e)
    (cond
      ((lexical-var-p e expr) :lexical-var)
      ((lexical-fun-p e expr) :lexical-fun)
      (t :not-lex-fun-var)))

  ;;
  ;; This returns:
  ;;
  ;;   (:lexical-var :not-lex-fun-var :lexical-fun)
  ;;
  (let ((x 1) (y 2))
    (symacrolet ((y x))
      (flet ((f () (+ 2 2)))
        (list (classify x) (classify y) (classify z)))))
.cble

.TP* Note:

These functions do not call
.code macroexpand
on the form. In most cases, it is necessary for the macro writers
to do so. Not that in the above example,  symbol
.code y
is classified as neither a lexical function nor variable.
However, it can be macro-expanded to
.code x
which is a lexical variable.

.coNP Function @ lexical-lisp1-binding
.synb
.mets (lexical-lisp1-binding < env << symbol )
.syne
.desc
The
.code lexical-lisp1-binding
function inspects the macro-time environment
.meta env
to determine what kind of binding, if any, does
.meta symbol
have in that environment, from a Lisp-1 perspective.

That is to say, it considers function bindings, variable bindings
and symbol macro bindings to be in a single name space and finds
the innermost binding of one of these types for
.metn symbol .

If such a binding is found, then the function returns one of
the three keyword symbols
.codn :var ,
.codn :fun ,
or
.codn :symacro .

If no such lexical binding is found, then the function
returns
.codn nil .

Note that a
.code nil
return doesn't mean that the symbol doesn't have a lexical binding.  It could
have an operator macro lexical binding (a macro binding in the function
namespace established by
.codn macrolet ).

.coNP Operator @ defsymacro
.synb
.mets (defsymacro < sym << form )
.syne
.desc
A
.code defsymacro
form introduces a symbol macro: a symbol macro is a parameterless
substitution keyed to a symbol.  In contexts where a symbol macro
definition of
.meta sym
is visible, if the form
.meta sym
appears such that its evaluation is called for, it is subject
to replacement by
.metn form .
After replacement takes place,
.meta form
itself is then processed for further replacement of macros and
symbol macros.

Symbol macros are also recognized in contexts
where
.meta sym
denotes a place which is the target of an assignment operation
like
.code set
and similar.

A
.code defsymacro
form is implicitly executed at expansion time, and thus need
not be wrapped in a
.code macro-time
form, just like
.codn defmacro .

Note: if a symbol macro expands to itself directly, expansion stops. However,
if a symbol macro expands to itself through a chain of expansions,
an infinite expansion time loop results.

.coNP Operator @ symacrolet
.synb
.mets (symacrolet >> ({( sym << form )}*) << body-form *)
.syne
.desc
The
.code symacrolet
operator binds local, lexically scoped macros that are
similar to the global symbol macros introduced by
.codn defsymacro .

Each
.meta sym
in the bindings list is bound to its corresponding form, creating a
new extension of the expansion-time lexical macro environment.

Each
.meta body-form
is subsequently macro-expanded in this new environment
in which the new symbol macros are visible.

Note: ordinary lexical bindings such as those introduced by let or by
function parameters lists shadow symbol macros. If a symbol
.code x
is bound by nested instances of
.code macrolet
and a
.codn let ,
then the scope enclosed by both
constructs will see whichever of the two bindings is more inner,
even though the bindings are active in completely separate phases of
processing.

From the perspective of the arguments of a
.code dwim
form, lexical function bindings also shadow symbol macros.
This is consistent with the Lisp-1-style name resolution which
applies inside a
.code dwim
form. Of course, lexical operator macros do not shadow
symbol macros under any circumstances.

.coNP Macros @ placelet and @ placelet*
.synb
.mets (placelet >> ({( sym << place )}*) << body-form *)
.mets (placelet* >> ({( sym << place )}*) << body-form *)
.syne
.desc
The
.code placelet
macro binds lexically scoped symbol macros in such
a way that they behave as aliases for places
denoted by place forms.

Each
.meta place
must be an expression denoting a syntactic place. The
corresponding
.meta sym
is established as an alias for the storage location which that place denotes,
over the scope of the
.metn body-form -s.

This binding takes place in such a way that each
.meta place
is evaluated exactly once, only in order to determine its
storage location.  The corresponding
.meta sym
then serves as an alias for that location, over the
scope of the
.metn body-form -s.
This means that whenever
.meta sym
is evaluated, it stands for the value of the storage
location, and whenever a value is apparently stored into
.metn sym ,
it is actually the storage location which receives it.

The
.code placelet*
variant implements an alternative scoping rule, which allows a later
.meta place
form to refer to a
.meta sym
bound to an earlier
.meta place
form. In other words, a given
.meta sym
binding is visible not only to the
.metn body-form -s
but also to
.meta place
forms which occur later.

Note: certain kinds of places, notably
.cblk
.meti (force << promise )
.cble
expressions, must be accessed before they can be stored,
and this restriction continues to hold when those
places are accessed through
.code placelet
aliases.

Note:
.code placelet
differs from
.code symacrolet
in that the forms themselves are not aliased, but the storage
locations which they denote.
.code "(symacrolet ((x y)) z)"
performs the syntactic substitution of symbol
.code x
by form
.codn y ,
wherever
.code x
appears inside
.code z
as an evaluated form, and is not shadowed by any inner binding.
Whereas
.code "(placelet ((x y)) z)"
generates code which arranges for
.code y
to be evaluated to a storage location, and syntactically replaces occurrences
of
.code x
with a form which directly denotes that storage location,
wherever
.code x
appears inside
.code z
as an evaluated form, and is not shadowed by any inner binding.
Also,
.code x
is not necessarily substituted by a single, fixed form,
as in the case of
.codn symacrolet .
Rather it may be substituted by one kind of form when it
is treated as a pure value, and another kind of form
when it is treated as a place.

.TP* "Example:"

Implementation of
.code inc
using
.codn placelet :

.cblk
  (defmacro inc (place : (delta 1))
    (with-gensyms (p)
      ^(placelet ((,p ,place))
         (set ,p (+ ,p ,delta)))))
.cble

The gensym
.code p
is used to avoid accidental capture of references
emanating from the
.code delta
form.

.coNP Operators @ tree-bind and @ mac-param-bind
.synb
.mets (tree-bind < macro-style-params < expr << form *)
.mets (mac-param-bind < context-expr < macro-style-params < expr << form *)
.syne
.desc
The
.code tree-bind
operator evaluates
.codn expr ,
and then uses the
resulting value as a counterpart to a macro-style parameter list.
If the value has a tree structure which matches the parameters,
then those parameters are established as bindings, and the
.metn form -s,
if any, are evaluated in the scope of those bindings.  The value
of the last
.meta form
is returned. If there are no forms,
.code nil
is returned.

Note: this operator throws an exception if there is a
structural mismatch between the parameters and the value of
.codn expr .

One way to avoid this exception is to use
.codn tree-case .

The
.code mac-param-bind
operator is similar to
.code tree-bind
except that it takes an extra argument,
.metn context-expr .
This argument is an expression which is evaluated. It is expected to
evaluate to a compound form. If an error occurs during binding, the error
diagnostic message is based on information obtained from this form.
By contrast, the
.code tree-bind
operator's error diagnostic refers to the
.code tree-bind
form, which is cryptic if the binding is used for the implementation
of some other construct, hidden from the user of that construct.

.coNP Operator @ tree-case
.synb
.mets (tree-case < expr >> {( macro-style-params << form *)}*)
.syne
.desc
The
.code tree-case
operator evaluates
.meta expr
and matches it against a succession
of zero or more cases. Each case defines a pattern match, expressed as a macro
style parameter list
.metn macro-style-params .

If the object produced by
.meta expr
matches
.metn macro-style-params ,
then the parameters are bound, becoming local variables, and the
.metn form -s,
if any, are evaluated in order in the environment in which those variables are
visible.  If there are forms, the value of the last
.meta form
becomes the result
value of the case, otherwise the result value of the case is nil.

If the result value of a case is the object
.code :
(the colon symbol), then processing continues with the next case. Otherwise the
evaluation of
.code tree-case
terminates, returning the result value.

If the value of
.meta expr
does not match the
.meta macro-style-params
parameter list of a case, processing continues with the next case.

If no cases match, then
.code tree-case
terminates, returning
.codn nil .

.TP* Example:

.cblk
  ;; reverse function implemented using tree-case

  (defun tb-reverse (obj)
    (tree-case obj
      (() ())      ;; the empty list is just returned
      ((a) obj)    ;; one-element list returned (unnecessary case)
      ((a . b) ^(,*(tb-reverse b) ,a)) ;; car/cdr recursion
      (a a)))     ;; atom is just returned
.cble

Note that in this example, the atom case is placed last, because an
argument list which consists of a symbol is a "catch all" match
that matches any object. We know that it matches an atom, because
the previous
.code "(a . b)"
case matches conses. In general, the order of the cases in
.code tree-case
is important: even more so than the order of cases in a
.code cond
or
.codn caseql .

.coNP Macro @ tb
.synb
.mets (tb < macro-style-params << form *)
.syne
.desc
The
.code tb
macro is similar to the
.code lambda
operator but its argument binding is based on a macro-style parameter list.
The name is an abbreviation of
.codn tree-bind .

A
.code tb
form evaluates to a function which takes a variable number of
arguments.

When that function is called, those arguments are taken as a list object which
is matched against
.meta macro-style-params
as if by
.metn tree-bind .
If the match is successful, then the parameters are bound to the
corresponding elements from the argument structure and each successive
.meta form
is evaluated an environment in which those bindings are visible.
The value of the last
.meta form
is the return value of the function. If there are no forms,
the function's return value is
.codn nil .

The following equivalence holds, where
.code args
should be understood to be a globally unique symbol:

.cblk
  (tb pattern body ...) <--> (lambda (. args)
                               (tree-bind pattern args body ...))
.cble

.coNP Macro @ tc
.synb
.mets (tc >> {( macro-style-params << form *)}*)
.syne
.desc
The
.code tc
macro produces an anonymous function whose behavior is closely
based on the
.code tree-case
operator. Its name is an abbreviation of
.codn tree-case .

The anonymous function takes a variable number of arguments.
Its argument list is taken to be the value macro is tested
against the multiple pattern clauses of an implicit
.codn tree-case .
The return value of the function is that of the implied
.codn tree-case .

The following equivalence holds, where
.code args
should be understood to be a globally unique symbol:

.cblk
  (tc clause1 clause2 ...) <--> (lambda (. args)
                                   (tree-case args
                                      clause1 clause2 ...))
.cble


.SS* Mutation of Syntactic Places
.coNP Macro @ set
.synb
.mets (set >> { place << new-value }*)
.syne
.desc
The
.code set
operator stores the values of expressions in places. It must
be given an even number of arguments.

If there are no arguments, then
.code set
does nothing and returns
.codn nil .

If there are two arguments,
.meta place
and
.metn new-value ,
then
.meta place
is evaluated to determine its storage location, then
.meta new-value
is evaluated to determine the value to be stored there,
and then the value is stored in that location. Finally,
the value is also returned as the result value.

If there are more than two arguments, then
.code
set performs multiple assignments in left to right order.
Effectively,
.code "(set v1 e1 v2 e2 ... vn en)"
is precisely equivalent to
.codn "(progn (set v1 e1) (set v2 e2) ... (set vn en))" .

.coNP Macro @ pset
.synb
.mets (pset >> { place << new-value }*)
.syne
.desc
The syntax of
.code pset
is similar to that of
.codn set ,
and the semantics is similar also in that zero or more places are
assigned zero or more values. In fact, if there are no arguments, or
if there is exactly one pair of arguments,
.code pset
is equivalent to
.codn set .

If there are two or more argument pairs, then all of the arguments
are evaluated first, in left-to-right order.  No store takes place
until after every
.meta place
is determined, and every
.meta new-value
is calculated. During the calculation, the values to be stored
are retained in hidden, temporary locations. Finally, these values
are moved into the determined places. The rightmost value is returned
as the form's value.

The assignments thus appear to take place in parallel, and
.code pset
is capable of exchanging the values of a pair of places, or rotating
the values among three or more places. (However, there are more convenient
operators for this, namely
.code rotate
and
.codn swap ).

.TP* Example:
.cblk
  ;; exchange x and y
  (pset x y y x)

  ;; exchange elements 0 and 1; and 2 and 3 of vector v:
  (let ((v (vec 0 10 20 30))
        (i -1))
    (pset [vec (inc i)] [vec (inc i)]
          [vec (inc i)] [vec (inc i)])
     vec)
  -> #(10 0 30 20)
.cble

.coNP Macro @ zap
.synb
.mets (zap < place <> [ new-value ])
.syne
.desc
The
.code zap
macro assigns
.meta new-value
to
.meta place
and returns the previous value of
.metn place .

If
.meta new-value
is missing, then
.code nil
is used.

In more detail, first
.code place
is evaluated to determine the storage location.
Then, the location is accessed to retrieve the
previous value. Then, the
.code new-value
expression is evaluated, and that value is
placed into the storage location.
Finally, the previously retrieved value is returned.


.coNP Macro @ flip
.synb
.mets (flip << place )
.syne
.desc
The
.code flip
macro toggles the Boolean value stored in
.metn place .

If
.meta place
previously held
.codn nil ,
it is set to
.codn t ,
and if it previously held a value other than
.codn nil ,
it is set to
.codn nil .

.coNP Macros @ inc and @ dec
.synb
.mets (inc < place <> [ delta ])
.mets (dec < place <> [ delta ])
.syne
.desc
The
.code inc
macro increments
.meta place
by adding
.meta delta
to its value.
If
.meta delta
is missing, the value used in its place the integer 1.

First the
.meta place
argument is evaluated as a syntactic place to determine the location.
Then, the value currently stored in that location is retrieved.
Next, the
.meta delta
expression is evaluated. Its value is added to the previously retrieved
value as if by the
.code +
function. The resulting value is stored in the place, and returned.

The macro
.code dec
works exactly like
.code inc
except that addition is replaced by subtraction. The similarly defaulted
.meta delta
value is subtracted from the previous value of the place.

.coNP Macro @ swap
.synb
.mets (swap < left-place << right-place )
.syne
.desc
The
.code swap
macro exchanges the values of
.meta left-place
and
.meta right-place
and returns the value which is thereby transferred to
.metn right-place .

First,
.meta left-place
and
.meta right-place
are evaluated, in that order, to determine their locations.
Then the prior values are retrieved, exchanged and stored back.
The value stored in
.meta right-place
is also returned.

If
.meta left-place
and
.meta right-place
are ranges of the same sequence, the behavior is not specified
if the ranges overlap or are of unequal length.

Note: the
.code rotate
macro's behavior is somewhat more specified in this regard.
Thus, although any correct
.code swap
expression can be expressed using
.codn rotate ,
but the reverse isn't true.

.coNP Macro @ push
.synb
.mets (push < item << place )
.syne
.desc
The
.code push
macro places
.meta item
at the head of the list stored in
.meta place
and returns the updated list which is stored back in
.metn place .

First, the expression
.meta item
is evaluated to produce the push value.
Then,
.meta place
is evaluated to determine its storage location.
Next, the storage location is accessed to retrieve the
list value which is stored there. A new object is
produced as if by invoking
.code cons
function on the push value and list value.
This object is stored into the location,
and returned.

.coNP Macro @ pop
.synb
.mets (pop << place )
.syne
.desc
The
.code pop
macro removes an element from the list stored in
.meta place
and returns it.

First,
.meta place
is evaluated to determine the place. The place is accessed to
retrieve the original value. Then a new value is calculated,
as if by applying the
.code cdr
function to the old value. This new value is stored.
Finally, a return value is calculated and returned, as if by applying the
.code car
function to the original value.

.coNP Macro @ pushnew
.synb
.mets (pushnew < item < place >> [ testfun <> [ keyfun ]])
.syne
.desc
The
.code pushnew
macro inspects the list stored in
.metn place .
If the list already contains the item, then
it returns the list. Otherwise it creates a new list
with the item at the front and stores it back
into
.metn place ,
and returns it.

First, the expression
.meta item
is evaluated to produce the push value.
Then,
.meta place
is evaluated to determine its storage location.
Next, the storage location is accessed to retrieve the
list value which is stored there. The list is
inspected to check whether it already contains the push
value, as if using the
.code member
function.  If that is the case, the list
is returned and the operation finishes.
Otherwise, a new object is
produced as if by invoking
.code cons
function on the push value and list value.
This object is stored into the location
and returned.

.coNP Macro @ shift
.synb
.mets (shift << place + << shift-in-value)
.syne
.desc
The
.code shift
macro treats one or more places as a "multi-place shift register".
The values of the places are shifted one place to the left.
The first (leftmost) place receives the value of the second place,
the second receives that of the third, and so on.
The last (rightmost) place receives
.meta shift-in-value
(which is not treated as a place, even if it is a syntactic place form).
The previous value of the first place is returned.

More precisely, all of the argument forms are evaluated left to right, in the
process of which the storage locations of the places are determined,
.meta shift-in-value
is reduced to its value.

The values stored in the places are sampled and saved.

Note that it is not specified whether the places are sampled in a separate
pass after the evaluation of the argument forms, or whether the
sampling is interleaved into the argument evaluation. This affects
the behavior in situations in which the evaluation of any of the
.meta place
forms, or of
.metn shift-in-value ,
has the side effect of modifying later places.

Next, the places are updated by storing the saved value of the second
place into the first place, the third place into the second and so forth,
and the value of
.meta shift-in-value
into the last place.

Finally, the saved original value of the first place is returned.

If any of the places are ranges which index into the same sequence,
and the behavior is not otherwise unspecified due to the issue
noted in an earlier paragraph, the effect upon the multiply-stored
sequence can be inferred from the above-described storage order.
Note that even if stores take place which change the length of
the sequence and move some elements, not-yet-processed stores whose ranges
to refer to these elements are not adjusted.

With regard to the foregoing paragraph, a recommended practice is
that if subranges of the same sequence object are shifted, they be
given to the macro in ascending order of starting index. Furthermore, the
semantics is simpler if the ranges do not overlap.

.coNP Macro @ rotate
.synb
.mets (rotate << place *)
.syne
.desc
Treats zero or more places as a "multi-place rotate register".
If there are no arguments, there is no effect and
.code nil
is returned. Otherwise, the last (rightmost) place receives
the value of the first (leftmost) place. The leftmost place
receives the value of the second place, and so on.
If there are two arguments, this equivalent to
.codn swap .
The prior value of the first place, which is the the value
rotated into the last place, is returned.

More precisely, the
.meta place
arguments are evaluated left to right,
and the storage locations are thereby determined. The storage
locations are sampled, and then the sampled values are
stored back into the locations, but rotated by one place
as described above. The saved original value of the leftmost
.meta place
is returned.

It is not specified whether the sampling of the original values
is a separate pass which takes place after the arguments
are evaluated, or whether this sampling it is interleaved into argument
evaluation. This affects
the behavior in situations in which the evaluation of any of the
.meta place
forms has the side effect of modifying the value stored in
a later
.meta place
form.

If any of the places are ranges which index into the same sequence,
and the behavior is not otherwise unspecified due to the issue
noted in the preceding paragraph, the effect upon the multiply-stored
sequence can be inferred from the above-described storage order.
Note that even if stores take place which change the length of
the sequence and move some elements, not-yet-processed stores whose ranges
to refer to these elements are not adjusted.

With regard to the foregoing paragraph, a recommended practice is
that if subranges of the same sequence object are shifted, they be
given to the macro in ascending order of starting index. Furthermore, the
semantics is simpler if the ranges do not overlap.

.coNP Macro @ del
.synb
.mets (del << place )
.syne
.desc
The
.code del
macro requests the deletion of
.codn place .
If
.code place
doesn't support deletion, an exception is thrown.

First
.code place
is evaluated, thereby determining its location.
Then the place is accessed to retrieve its value.
The place is then subject to deletion. Finally, the
previously retrieved value is returned.

Precisely what deletion means depends on the kind of place.
The built-in places in \*(TL have deletion semantics which are
intended to be unsurprising to the programmer familiar with the
data structure which holds the place.

Generally, if a place denotes the element of a sequence, then deletion of the
place implies deletion of the element, and deletion of the element implies that
the gap produced by the element is closed.  The deleted element is effectively
replaced by its successor, that successor by its successor and so on. If a
place denotes a value stored in a dynamic data set such as a hash table,
then deletion of that place implies deletion of the entry which holds
that value. If the entry is identified by a key, that key is also removed.

.coNP Macro @ lset
.synb
.mets (lset <> { place }+ << list-expr )
.syne
.desc
The
.code lset
operator's parameter list consists of one or more places followed
by an expression
.metn list-expr .

The macro evaluates
.codn list-expr ,
which is expected to produce a proper list.

Successive elements of the resulting list are then assigned to each
successive
.codn place .

If there are fewer elements in the list than places, the
unmatched places receive the value
.codn nil .

Excess elements in the list are ignored.

A
.code lset
form produces the value of
.meta list-expr
as its result value.

.SS* User-Defined Places and Place Operators
\*(TL provides a number of place-modifying operators such as
.codn set ,
.codn push ,
and
.codn inc .
It also provides a variety of kinds of syntactic places
which may be used with these operators.

Both of these categories are open-ended: \*(TL programs may extend
the set of place-modifying operators, as well as the vocabulary of
forms which are recognized as syntactic places.

Regarding place operators, it might seem obvious that new place operators can
be developed, since they are macros, and macros can expand to uses
of existing place operators. As an example, it may seem that
.code inc
operator could be written as a macro which uses
.codn set :

.cblk
  (defmacro new-inc (place : (delta 1))
    ^(set ,place (+ ,place ,delta)))
.cble

However, the above
.code new-inc
macro has a problem: the
.code place
argument form is inserted into two places in the expansion, which
leads to two evaluations. This is visibly incorrect if the place
form contains any side effects. It is also potentially inefficient.

\*(TL provides a framework for writing place update macros which
evaluate their argument forms once, even if they have to access
and update the same places.

The framework also supports the development of new kinds of place forms
as capsules of code which introduce the right kind of material into
the lexical environment of the body of an update macro, to enable
this special evaluation.

.NP* Place-Expander Functions
The central design concept in \*(TL syntactic places are
.IR "place-expander functions" .
Each compound place is defined by up to three place-expander functions,
which are associated with the place via the leftmost operator
symbol of the place form. One place-expander, the
.IR "update expander" ,
is mandatory. Optionally, a place may also provide a
.I "clobber expander"
as well as a
.IR "delete expander" .
An update expander provides the expertise for evaluating a place form once
in its proper run-time context to determine its actual run-time storage
location, and to access and modify the storage location.
A clobber expander provides an optimized mechanism for uses that perform
a one-time store to a place without requiring its prior value.
If a place definition does not supply a clobber expander, then the syntactic
places framework uses the update expander to achieve the functionality.
A delete expander provides the expertise for determining the actual run-time
storage location corresponding to a place, and obliterating it,
returning its prior value.  If a place does not supply a delete expander, then
the place does not support deletion. Operators which require deletion, such as
.code del
will raise an error when applied to that place.

The expanders operate independently, and it is expected that place-modifying
operators choose one of the three, and use only that expander. For example,
accessing a place with an update expander and then overwriting its value
with a clobber expander may result in incorrect code which contains multiple
evaluations of the place form.

The programmer who implements a new place does not write expanders directly,
but rather defines them via the
.code defplace
macro.

The programmer who implements a new place update macro likewise does not
call the expanders directly. Usually, they are invoked via the macros
.codn with-update-expander ,
.code with-clobber-expander
and
.codn with-delete-expander .
These are sufficient for most kind of macros.
In certain complicated cases, expanders may be invoked using the wrapper
functions
.codn call-update-expander ,
.code call-clobber-expander
and
.codn call-delete-expander .
These convenience macros and functions perform certain common chores, like
macro-expanding the place in the correct environment, and choosing the
appropriate function.

The expanders are described in the following sections.

.NP* The Update Expander
.synb
.mets (lambda >> ( getter-sym < setter-sym < place-form
.mets \ \ \ \ \ \ \ \  << body-form ) ...)
.syne
.desc
The update expander is a code-writer. It takes a
.meta body-form
argument, representing code, and returns a larger form which surrounds
this code with additional code.

This larger form returned by the update expander can be regarded as having two
abstract actions, when it is substituted and evaluated in the context where
.meta place-form
occurs.  The first abstract action is to evaluate
.meta place-form
exactly one time, in order to determine the actual run-time location to which
that form refers.
The second abstract action is to evaluate the caller's
.metn body-form -s,
in a lexical environment in which bindings exist for some lexical
functions or (more usually) lexical macros. These lexical macros
are explicitly referenced by the
.metn body-form ;
the update expander just provides their definition, under the names
it is given via the
.meta getter-sym
and
.meta setter-sym
arguments.

The update expander writes local functions or macros under these names: a
getter function and a setter function.  Usually, update expanders write
macros rather than functions, possibly in combination with some lexical
anonymous variables which hold temporary objects. Therefore the getter
and setter are henceforth referred to as macros.

The code being generated is with regard to some concrete instance of
.metn place-form .
This argument is the actual form which occurs in a program. For
instance, the update expander for the
.code car
place might be called with an arbitrary variant of the
.meta place-form
might look like
.codn "(car (inc (third some-list)))" .

In the abstract semantics, upfront code wrapped around the
.meta body-form
by the update expander provides the logic to evaluate this place to
a location, which is retained in some hidden local context.

The getter local macro named by
.meta getter-sym
must provide the logic for retrieving the value of this place.
The getter macro takes no arguments.
The
.meta body-form
makes free use of the getter function; they may call it multiple times,
which must not trigger multiple evaluations of the original place
form.

The setter local macro named by
.meta setter-sym
must generate the logic for storing a new value into the once-evaluated
version of
.metn place-form .
The setter function takes exactly one argument, whose
value specifies the value to be stored into the place.
It is the caller's responsibility to ensure that the
argument form which produces the value to be stored via the setter is evaluated
only once, and in the correct order.  The setter does not concern itself with
this form. Multiple calls to the setter can be expected to result in multiple
evaluations of its argument. Thus, if necessary, the caller must supply the code
to evaluate the new value form to a temporary variable, and then pass the
temporary variable to the setter. This code can be embedded in
the
.meta body-form
or can be added to the code returned by a call to the update expander.

The setter local macro or function must return the new value which is stored.
That is to say, when
.meta body-form
invokes this local macro or function, it may rely on it yielding the
new value which was stored, as part of achieving its own semantics.

The update expander does not macro-expand
.codn place-form .
It is assumed that the expander is invoked in such a way that the
place has been expanded in the correct environment. In other words, the
form matches the type of place which the expander handles.
If the expander had to macro-expand the place form, it would sometimes have
to come to the conclusion that the place form must be handled by a different
expander. No such consideration is the case: when an expander is called on
a form, that is final; it is certain that it is the correct expander, which
matches the symbol in the
.code car
position of the form, which is not a macro in the context where it occurs.

An update expander is free to assume that any place which is stored
(the setter local macro is invoked on it) is accessed at least once by
an invocation of the getter. A place update macro which relies on an update
expander, but uses only the store macro, might not work properly.
An example of an update expander which relies on this assumption is the
expander for the
.cblk
.meti (force << promise )
.cble
place type. If
.meta promise
has not yet been forced, and only the setter is used, then
.meta promise
might remain unforced as its internal value location is updated.
A subsequent access to the place will incorrectly trigger a force,
which will overwrite the value. The expected behavior is that storing
a value in an unforced
.code force
place changes the place to forced state, preempting the evaluation of
the delayed form. Afterward, the promise exhibits the value which was
thus assigned.

The update expander is not responsible for all issues of evaluation order.  A
place update macro may consist of numerous places, as well as numerous
value-producing forms which are not places. Each of the places can provide its
registered update expander which provides code for evaluating just that place,
and a means of accessing and storing the values.  The place update macro must
call the place expanders in the correct order, and generate any additional code
in the correct order, so that the macro achieves its required documented
evaluation order.

.TP* "Example Update Expander Call:"

.cblk
  ;; First, capture the update expander
  ;; function for (car ...) places
  ;; in a variable, for clarity.

  (defvar car-update-expander [*place-update-expander* 'car])

  ;; Next, call it for the place (car [a 0]).
  ;; The body form specifies logic for
  ;; incrementing the place by one and
  ;; returning the new value.

  (call car-update-expander 'getit 'setit '(car [a 0])
    '(setit (+ (getit) 1)))

  -->  ;; Resulting code:

  (rlet ((#:g0032 [a 0]))
    (macrolet ((getit nil
                 (append (list 'car) (list '#:g0032)))
               (setit (val)
                 (append (list 'sys:rplaca)
                         (list '#:g0032) (list val))))
      (setit (+ (getit) 1))))

  ;; Same expander call as above, with a sys:expand to show the
  ;; fully expanded version of the returned code, in which the
  ;; setit and getit calls have disappeared, replaced by their
  ;; macro-expansions.

  (sys:expand
    (call car-update-expander 'getit 'setit '(car [a 0])
      '(setit (+ (getit) 1))))

  -->

  (let ((#:g0032 [a 0]))
    (sys:rplaca #:g0032 (+ (car #:g0032) 1)))

.cble
The main noteworthy points about the generated code are:
.RS
.IP -
the
.code "(car [a 0])"
place is evaluated by evaluating the embedded form
.code "[a 0]"
and storing storing the resulting object into a hidden local variable.
That's as close a reference as we can make to the
.code car
field.
.IP -
the getter macro expands to code which simply calls the
.code car
function on the cell.
.IP -
the setter uses a system function called
.codn sys:rplaca ,
which differs from
.code rplaca
in that it returns the stored value, rather than the cell.
.RE

.NP* The Clobber Expander
.synb
.mets (lambda >> ( simple-setter-sym < place-form
.mets \ \ \ \ \ \ \ \  << body-form ) ...)
.syne
.desc
The clobber expander is a code-writer similar to the update expander.
It takes a
.meta body-form
argument, and returns a larger form which surrounds this form
with additional program code.

The returned block of code has one main abstract action.
It must arrange for the evaluation of
.meta body-form
in a lexical environment in which a lexical macro or lexical function
exists which has the name requested by the
.meta simple-setter-sym
argument.

The simple setter local macro written by the clobber expander is similar to the
local setter written by the update expander. It has exactly the
same interface, performs the same action of storing a value into
the place, and returns the new value.

The difference is that its logic may be considerably simplified by the
assumption that the place is being subject to exactly one store,
and no access.

A place update macro which uses a clobber expander, and calls it more than
once, break the assumption; doing so may result in multiple evaluations
of the
.metn place-form .

.NP* The Delete Expander
.synb
.mets (lambda >> ( deleter-sym < place-form
.mets \ \ \ \ \ \ \ \  << body-form ) ...)
.syne
.desc
The delete expander is a code-writer similar to clobber expander.
It takes a
.meta body-form
arguments, and returns a larger form which surrounds this form
with additional program code.

The returned block of code has one main abstract action.
It must arrange for the evaluation of
.meta body-form
in a lexical environment in which a lexical macro or lexical function
exists which has the name requested by the
.meta deleter-sym
argument.

The deleter macro written by the clobber expander takes no arguments.
It may be called at most once. It returns the previous value of the
place, and arranges for its obliteration, whatever that means for
that particular kind of place.

.coNP Macro @ with-update-expander
.synb
.mets (with-update-expander >> ( getter << setter ) < place < env
.mets \  << body-form )
.syne
.desc
The
.code with-update-expander
macro evaluates the
.meta body-form
argument, whose result is expected to be a Lisp form.
The macro adds additional code around this code, and the result is returned.
This additional code is called the
.IR "place-access code" .

The
.meta getter
and
.meta setter
arguments must be symbols. Over the evaluation of the
.metn body-form ,
these symbols are bound to the names of local functions which
are provided in the place-access code.

The
.meta place
argument is a form which evaluates to a syntactic place. The generated
place-access code is based on this place.

The
.meta env
argument is a form which evaluates to a macro-expansion-time environment.
The
.code with-update-expander
macro uses this environment to perform macro-expansion on the value of the
.meta place
form, to obtain the correct update expander function for the fully
macro-expanded place.

The place-access code is generated by calling the update expander
for the expanded version of
.codn place .

.TP* "Example:"

The following is an implementation of the
.code swap
macro, which exchanges the contents of two places.

Two places are involved, and, correspondingly, the
.code with-update-expander
macro is used twice, to add two instances of place-update code
to the macro's body.

.cblk
  (defmacro swap (place-0 place-1 :env env)
    (with-gensyms (tmp)
      (with-update-expander (getter-0 setter-0) place-0 env
        (with-update-expander (getter-1 setter-1) place-1 env
          ^(let ((,tmp (,getter-0)))
             (,setter-0 (,getter-1))
             (,setter-1 ,tmp))))))
.cble

The basic logic for swapping two places is contained in the code template:

.cblk
  ^(let ((,tmp (,getter-0)))
     (,setter-0 (,getter-1))
     (,setter-1 ,tmp))
.cble

The temporary variable named by the
.code gensym
symbol
.code tmp
is initialized by calling the getter function for
.metn place-0 .
Then the setter function of
.meta place-0
is called in order to store the value of
.meta place-1
into
.metn place-0 .
Finally, the setter for
.meta place-1
is invoked to store the previously saved temporary value into
that place.

The name for the temporary variable is provided by the
.code with-gensyms
macro, but establishing the variable is the caller's responsibility;
this is seen as an explicit
.code let
binding in the code template.

The names of the getter and setter functions are similarly provided
by the
.code with-update-expander
macros. However, binding those functions is the responsibility of that
macro. To achieve this, it adds the place-access code to the code generated by
the
.code "^(let ...)"
backquote template.  In the following example macro-expansion, the additional
code added around the template is seen. It takes the form of two
.code macrolet
binding blocks, each added by an invocation of
.codn with-update-expander :

.cblk
  (macroexpand '(swap a b))

  -->

  (macrolet ((#:g0036 () 'a)      ;; getter macro for a
             (#:g0037 (val-expr)  ;; setter macro for a
               (append (list 'sys:setq) (list 'a)
                       (list val-expr))))
    (macrolet ((#:g0038 () 'b)     ;; getter macro for b
               (#:g0039 (val-expr) ;; setter macro for b
                 (append (list 'sys:setq) (list 'b)
                         (list val-expr))))
      (let ((#:g0035 (#:g0036)))  ;; temp <- a
        (#:g0037 (#:g0038))       ;; a <- b
        (#:g0039 #:g0035))))      ;; b <- temp
.cble

In this expansion, for example
.code #:g0036
is the generated symbol which forms the value of the
.code getter-0
variable in the
.code swap
macro. The getter is a macro which simply expands to a
.codn a :
straightforward access to the variable a.
Of course,
.code #:g0035
is nothing but the value of the
.code tmp
variable. Thus the swap macro's
.cblk
^(let ((,tmp (,getter-0))) ...)
.cble
has turned into
.cblk
^(let ((#:g0035 (#:g0036))) ...)
.cble

A full expansion, with the
.code macrolet
local macros expanded out:

.cblk
  (sys:expand '(swap a b))

  -->

  (let ((#:g0035 a))
    (sys:setq a b)
    (sys:setq b #:g0035))
.cble

In other words, the original syntax
.cblk
(,getter-0)
.cble
became
.cblk
(#:g0036)
.cble
and finally just
.codn a .

Similarly,
.cblk
(,setter-0 (,getter-1))
.cble
became the
.code macrolet
invocations
.cblk
(#:g0037 (#:g0038))
.cble
which finally turned into:
.codn "(sys:setq a b)" .

.coNP Macro @ with-clobber-expander
.synb
.mets (with-clobber-expander <> ( simple-setter ) < place < env
.mets \  << body-form )
.syne
.desc
The
.code with-clobber-expander
macro evaluates
.metn body-form ,
whose result is expected to be a Lisp form. The macro adds additional code
around this form, and the result is returned. This additional code is called
the
.IR "place-access code" .

The
.meta simple-setter
argument must be a symbol. Over the evaluation of the
.metn body-form ,
this symbol is bound to the name of a functions which
are provided in the place-access code.

The
.meta place
argument is a form which evaluates to a syntactic place. The generated
place-access code is based on this place.

The
.meta env
argument is a form which evaluates to a macro-expansion-time environment.
The
.code with-clobber-expander
macro uses this environment to perform macro-expansion on the value of the
.meta place
form, to obtain the correct update expander function for the fully
macro-expanded place.

The place-access code is generated by calling the update expander
for the expanded version of
.codn place .

.TP* "Example:"

The following implements a simple assignment statement, similar to
.code set
except that it only handles exactly two arguments:

.cblk
  (defmacro assign (place new-value :env env)
    (with-clobber-expander (setter) place env
      ^(,setter ,new-value)))
.cble

Note that the correct evaluation order of
.code place
and
.code new-value
is taken care of, because
.code with-clobber-expander
generates the code which performs all the necessary evaluations of
.codn place .
This evaluation occurs before the code which is generated by
.cblk
^(,setter ,new-value)
.cble
part is evaluated, and that code is what evaluates
.codn new-value .

Suppose that a macro were desired which allows assignment to be notated in a right to left
style, as in:

.cblk
   (assign 42 a)  ;; store 42 in variable a
.cble

Now, the new value must be evaluated prior to the place, if left to right
evaluation order is to be maintained. The standard
.code push
macro has this property: the push value is on the left, and the place
is on the right.

Now, the code has to explicitly take care of the order, like this:

.cblk
  ;; WRONG! We can't just swap the parameters;
  ;; place is still evaluated first, then new-value:

  (defmacro assign (new-value place :env env)
    (with-clobber-expander (setter) place env
      ^(,setter ,new-value)))

  ;; Correct: arrange for evaluation of new-value first,
  ;; then place:

  (defmacro assign (new-value place :env env)
    (with-gensym (tmp)
      ^(let ((,tmp ,new-value))
         ,(with-clobber-expander (setter) place env
           ^(,setter ,tmp)))))
.cble

.coNP Macro @ with-delete-expander
.synb
.mets (with-delete-expander <> ( deleter ) < place < env
.mets \  << body-form )
.syne
.desc
The
.code with-delete-expander
macro evaluates
.metn body-form ,
whose result is expected to be a Lisp form.
The macro adds additional code
around this code, and the resulting code is returned. This additional code is
called the
.IR "place-access code" .

The
.meta deleter
argument must be a symbol. Over the evaluation of the
.metn body-form ,
this symbol is bound to the name of a functions which
are provided in the place-access code.

The
.meta place
argument is a form which evaluates to a syntactic place. The generated
place-access code is based on this place.

The
.meta env
argument is a form which evaluates to a macro-expansion-time environment.
The
.code with-delete-expander
macro uses this environment to perform macro-expansion on the value of the
.meta place
form, to obtain the correct update expander function for the fully
macro-expanded place.

The place-access code is generated by calling the update expander
for the expanded version of
.codn place .

.TP* "Example:"

The following implements the
.code del
macro:

.cblk
  (defmacro del (place :env env)
    (with-delete-expander (deleter) place env
      ^(,deleter)))
.cble

.coNP Function @ call-update-expander
.synb
.mets (call-update-expander < getter < setter < place < env << body-form )
.syne
.desc
The
.code call-update-expander
function provides an alternative interface for making use of an update
expander, complementary to
.codn with-update-expander .

Arguments
.meta getter
and
.meta setter
are symbols, provided by the caller. These are passed to the update
expander function, and are used for naming local functions in the
generated code which the update expander adds to
.metn body-form .

The
.meta place
argument is a place which has not been subject to macro-expansion.
The
.code call-update-expander
function takes on the responsibility for macro-expanding the place.

The
.meta env
parameter is the macro-expansion environment object required to
correctly expand
.code place
in its original environment.

The
.meta body-form
argument represents the source code of a place update operation.
This code makes references to the local functions whose names
are given by
.meta getter
and
.metn setter .
Those arguments allow the update expander to write these functions
with the matching names expected by
.metn body-form .

The return value is an object representing source code which incorporates
the
.metn body-form ,
augmenting it with additional code which evaluates
.code place
to determine its location, and provides place accessor local functions
expected by the
.metn body-form .

.TP* "Example:"

The following shows how to implement a
.code with-update-expander
macro using
.codn call-update-expander :

.cblk
  (defmacro with-update-expander ((getter setter)
                                  unex-place env body)
    ^(with-gensyms (,getter ,setter)
       (call-update-expander ,getter ,setter
                             ,unex-place ,env ,body)))
.cble

Essentially, all that
.code with-update-expander
does is to choose the names for the local functions, and bind them
to the local variable names it is given as arguments. Then it
calls
.codn call-update-expander .

.TP* "Example:"

Implement the swap macro using
.codn call-update-expander :

.cblk
  (defmacro swap (place-0 place-1 :env env)
    (with-gensyms (tmp getter-0 setter-0 getter-1 setter-1)
      (call-update-expander getter-0 setter-0 place-0 env
        (call-update-expander getter-1 setter-1 place-1 env
          ^(let ((,tmp (,getter-0)))
             (,setter-0 (,getter-1))
             (,setter-1 ,tmp))))))
.cble

.coNP Function @ call-clobber-expander
.synb
.mets (call-clobber-expander < simple-setter < place < env << body-form )
.syne
.desc
The
.code call-clobber-expander
function provides an alternative interface for making use of a clobber
expander, complementary to
.codn with-clobber-expander .

Argument
.meta simple-setter
is a symbol, provided by the caller. It is passed to the clobber
expander function, and is used for naming a local function in the
generated code which the update expander adds to
.metn body-form .

The
.meta place
argument is a place which has not been subject to macro-expansion.
The
.code call-clobber-expander
function takes on the responsibility for macro-expanding the place.

The
.meta env
parameter is the macro-expansion environment object required to
correctly expand
.code place
in its original environment.

The
.meta body-form
argument represents the source code of a place update operation.
This code makes references to the local function whose name
is given by
.metn simple-setter .
That argument allows the update expander to write this function
with the matching name expected by
.metn body-form .

The return value is an object representing source code which incorporates
the
.metn body-form ,
augmenting it with additional code which evaluates
.code place
to determine its location, and provides the clobber local function
to the
.metn body-form .

.coNP Function @ call-delete-expander
.synb
.mets (call-delete-expander < deleter < place < env << body-form )
.syne
.desc
The
.code call-delete-expander
function provides an alternative interface for making use of a delete
expander, complementary to
.codn with-delete-expander .

Argument
.meta deleter
is a symbol, provided by the caller. It is passed to the delete
expander function, and is used for naming a local function in the
generated code which the update expander adds to
.metn body-form .

The
.meta place
argument is a place which has not been subject to macro-expansion.
The
.code call-delete-expander
function takes on the responsibility for macro-expanding the place.

The
.meta env
parameter is the macro-expansion environment object required to
correctly expand
.code place
in its original environment.

The
.meta body-form
argument represents the source code of a place delete operation.
This code makes references to the local function whose name
is given by
.metn deleter .
That argument allows the update expander to write this function
with the matching name expected by
.metn body-form .

The return value is an object representing source code which incorporates
the
.metn body-form ,
augmenting it with additional code which evaluates
.code place
to determine its location, and provides the delete local function
to the
.metn body-form .

.coNP Macro @ define-modify-macro
.synb
.mets (define-modify-macro < name < parameter-list << function-name )
.syne
.desc
The
.code define-modify-macro
macro provides a simplified way to write certain kinds of place update
macros. Specifically, it provides a way to write place update macros
which modify a place by retrieving the previous value, pass it through
a function (perhaps together with some additional arguments), and then store
the resulting value back into the place and return it.

The
.meta name
parameter specifies the name for the place update macro to be written.

The
.meta function-name
parameter must specify a symbol: the name of the update function.

The update macro and update function both take at least one parameter:
the place to be updated, and its value, respectively.

The
.meta parameter-list
specifies the additional parameters for update function, which will also
become additional parameters of the macro. Because it is a
function parameter list, it cannot use the special destructuring features of
macro parameter lists, or the
.code :env
or
.code :whole
special parameters. It can use optional parameters. Of course, it may be empty.

The
.code define-modify-macro
macro writes a macro called
.metn name .
The leftmost parameter of this macro is a place, followed by the additional arguments
specified by
.metn parameter-list .
The macro will arrange for the evaluation of the place argument to determine
the place location.  It will then retrieve and save the prior value of the
place, and evaluate the remaining arguments. The prior value of the
place, and the values of the additional arguments, are all passed to
.meta function
and the resulting value is then stored back into the location previously
determined for
.metn place .

.TP* "Example:"

Some standard place update macros are implementable using
.codn define-modify-macro ,
such as
.codn inc .

The
.code inc
macro reads the old value of the place, then passes it through the
.code +
(plus) function, along with an extra argument: the delta value, which
defaults to one. The
.code inc
macro could be written using
.code define-modify-macro
as follows:

.cblk
  (define-modify-macro inc (: (delta 1)) +)
.cble

Note that the argument list
.code "(: (delta 1))"
doesn't specify the place, because the place is the implicit leftmost
argument of the macro which isn't given a name. With the above definition
in place, when
.code "(inc (car a))"
is invoked, then
.code "(car a)"
is first reduced to a location, and that location's value is retrieved and
saved. Then the
.code delta
parameter s evaluated to its value, which has defaulted to 1, since
the argument was omitted.
Then these two values are passed to the
.code +
function, and so 1 is added to the value previously retrieved from
.codn "(car a)" .
The resulting sum is then stored back
.code "(car a)"
without, of course, evaluating
.code "(car a)"
again.

.coNP Macro @ defplace
.synb
.mets (defplace < place-destructuring-args < body-sym
.mets \ \ \ \ \ \ \ \ \  >> ( getter-sym < setter-sym << update-body )
.mets \ \ \ \ \ \ \ \ \  >> [( ssetter-sym << clobber-body )
.mets \ \ \ \ \ \ \ \ \ \  >> [( deleter-sym << delete-body )]])
.syne
.desc
The
.code defplace
macro is used to introduce a new kind of syntactic place.
It writes the update expander, and optionally clobber and delete
expander functions, from a simpler, more compact specification,
and automatically registers the resulting functions. The compact specification
of a
.code defplace
call contains only code fragments for the expander functions.

The name and syntax of the place is determined by the
.meta place-destructuring-args
argument, which is macro-style parameter list whose structure
mimics that of the the place. In particular, its leftmost symbol
gives the name under which the place is registered.
The
.code defplace
macro provides automatic destructuring of the syntactic place,
so that the expander code fragments can refer to the components
of a place by name.

The
.meta body-sym
parameter must be be a symbol. This symbol will capture the
.meta body-forms
parameter which is passed to the update expander, clobber
expander or delete expander. The code fragments then have
access to the the body forms via this name.

The
.metn getter-sym ,
.metn setter-sym ,
and
.meta update-body
parenthesized triplet specify the update expander fragment.
The
.code defplace
macro will bind
.meta getter-sym
and
.meta setter-sym
to symbols.  The
.meta update-body
must then specify a template of code which evaluates the syntactic place to
determine its storage location, and provides a pair of local functions, using
these two symbols as their name. The template must also insert the
.meta body-sym
forms into the scope of these local functions, and the place determining code.

The
.meta setter-sym
and
.meta clobber-body
arguments similarly specify an optional clobber expander fragment,
as a single optional argument. If specified, the
.meta clobber-body
must generate a local function named using
.meta setter-sym
wrapped around
.meta body-sym
forms.

The
.meta deleter-sym
and
.meta deleter-body
likewise specify a delete expander fragment. If this is omitted,
then the place shall not support deletion.

.TP* "Example:"

Implementation of the place denoting the
.code car
field of
.code cons
cells:

.cblk
  (defplace (car cell) body

    ;; the update expander fragment
    (getter setter
      (with-gensyms (cell-sym) ;; temporary symbol for cell
        ^(let ((,cell-sym ,cell)) ;; evaluate place to cell
           ;; getter and setter access cell via temp var
           (macrolet ((,getter ()
                         ^(car ,',cell-sym))
                      (,setter (val)
                         ^(sys:rplaca ,',cell-sym ,val)))

             ;; insert body form from place update macro
             ,body))))

    ;; clobber expander fragment: simpler: no need
    ;; to evaluate cell to temporary variable.
    (ssetter
      ^(macrolet ((,ssetter (val)
                     ^(sys:rplaca ,',cell ,val)))
        ,body))

    ;; deleter: delegate to pop semantics:
    ;; (del (car a)) == (pop a).
    (deleter
      ^(macrolet ((,deleter () ^(pop ,',cell)))
         ,body)))
.cble

.coNP Macro @ define-place-macro
.synb
.mets (define-place-macro < name < macro-style-params
.mets \ \  << body-form *)
.syne
.desc
In some situations, an equivalence exists between two forms, only one
of which is recognized as a place. The
.code define-place-macro
macro can be used to establish a form as a place in terms of a translation to
an equivalent form which is already a place.

The
.code define-place-macro
has the same syntax as
.codn defmacro .
It specifies a macro transformation for a compound form which has the
.meta name
symbol in its leftmost position.

Forms which are used as syntactic places are subject to a modified
macro-expansion algorithm. If a place macro applies to a place, then it is
expanded, otherwise it is taken as-is. Then the place is expanded as a ordinary
macro (possibly a symbol macro). Then the process is repeated from the
beginning, as necessary.  Thus, the output of the ordinary macro expansion may
potentially be, again, a place macro. Place macros can expand to other place
macros or ordinary macros and vice versa.

Place macro expansion doesn't use an environment; place macros are in a single
global namespace, special to place macros. There are no lexically scoped place
macros. Such an effect can be achieved by having a place macro expand to
an a form which is the target of a global or local macro, as necessary.

The
.code define-place-macro
form does not cause
.meta name
to become
.codn mboundp .

There can exist both an ordinary macro and a place macro of the same name;
moreover, this is potentially useful.

.TP* "Example:"

Implementation of
.code first
in terms of
.codn car :

.cblk
  (define-place-macro first (obj)
    ^(car ,obj))
.cble

.coNP Macro @ rlet
.synb
.mets (rlet >> ({( sym << init-form )}*) << body-form *)
.syne
.desc
The macro
.code rlet
is similar to the
.code let
operator. It establishes bindings for one or more
.metn sym -s,
which are initialized using the values of
.metn init-form -s.

Note that the simplified syntax for a variable which initializes to
.code nil
by default is not supported by
.codn rlet ;
that is to say, the syntax
.meta sym
cannot be used in place of the
.meti >> ( sym << init-form )
syntax when
.meta sym
is to be initialized to
.codn nil .

The
.code rlet
macro differs from
.code let
in that
.code rlet
assumes that those
.metn sym -s
which have constant
.metn init-form -s
(according to the
.code constantp
function) may be safely implemented as a symbol macro rather than a lexical
variable.

Therefore
.code rlet
is suitable in situations in which simpler code is desired from the output
of certain kinds of machine-generated code, which binds local symbols:
code with fewer temporary variables.

On the other hand,
.code rlet
is not suitable in situations when true variables are required, which
are assignable, and provide temporary storage.

.TP* "Example:"

.cblk
  ;; WRONG! Exchange two variables, a and b:
  (rlet ((temp a))
    (set a b)
    (set b temp))

  ;; Demonstration of constant-propagation
  (let ((a 42))
    (rlet ((x 1)
           (y a))
      (+ x y)))  -->  43

  (sys:expand
    '(let ((a 42))
      (rlet ((x 1)
             (y a))
        (+ x y))))  -->  (let ((a 42))
                           (let ((y a))
                              (+ 1 y)))
.cble

The last example shows that the
.code x
variable has disappeared in the expansion. The
.code rlet
macro turned it into into a
.code symacrolet
denoting the constant 1, which then propagated to the use site,
turning the expression
.code "(+ x y)"
into
.codn "(+ 1 y)" .

.coNP Macro @ define-accessor
.synb
.mets (define-accessor < get-function << set-function )
.syne
.desc
The
.code define-accessor
macro is used for turning a function into an accessor,
such that forms which call the function can be treated
as places.

Arguments to
.code define-accessor
are two symbols, which must name functions. When the
.code define-accessor
call is evaluated, the
.meta get-function
symbol is registered as a syntactic place. Stores to the
place are handled via calls to
.metn set-function .

If
.meta get-function
names a function which takes N
arguments,
.meta set-function
must name a function which takes N+1 arguments.

Moreover, in order for the accessor semantics to be correct
.meta set-function
must treat its rightmost argument as the value being stored,
and must also return that value.

When a function call form targeting
.meta get-function
is treated as a place which is subject
to an update operation (for instance an increment via the
.code inc
macro),
the accessor definition created by
.code define-accessor
ensures that the arguments of
.meta get-function
are evaluated only once, even though the update involves
a call to
.meta get-function
and
.meta set-function
with the same arguments. The argument forms are evaluated to
temporary variables, and these temporaries are used as the
arguments in the calls.

No other assurances are provided by
.codn define-accessor .

In particular, if
.meta get-function
and
.meta set-function
internally each perform some redundant calculation over their arguments,
this cannot be optimized. Moreover, if that calculation has a visible effect,
that effect is observed multiple times in an update operation.

If further optimization or suppression of multiple effects is required,
the more general
.code defplace
macro must be used to define the accessor. It may also be possible to
treat the situation  in a satisfactory way using a
.code define-place-macro
definition, which effectively then supplies inline code whenever a certain form
is used as a place, and that code itself is treated as a place.

.coNP Macro @ with-gensyms
.synb
.mets (with-gensyms <> ( sym *) << body-form *)
.syne
.desc
The
.code with-gensyms
evaluates the
.metn body-form -s
in an environment in which each variable name symbol
.meta sym
is bound to a new uninterned symbol ("gensym").

.TP* "Example:"

The code:

.cblk
  (let ((x (gensym))
        (y (gensym))
        (z (gensym)))
    ^(,x ,y ,z))
.cble

may be expressed more conveniently using the
.code with-gensyms
shorthand:

.cblk
  (with-gensyms (x y z)
    ^(,x ,y ,z))
.cble

.SS* Quasiquote Operator Syntax
.coNP Macro @ qquote
.synb
.mets (qquote << form )
.syne
.desc
The
.code qquote
(quasi-quote) macro operator implements a notation for convenient
list construction.  If
.meta form
is an atom, or a list structure which
does not contain any
.code unquote
or
.code splice
operators, then
.cblk
.meti (qquote << form )
.cble
is equivalent to
.cblk
.meti (qquote << form ).
.cble

If
.metn form ,
however, is a list structure which contains
.code unquote
or
.code splice
operators, then the substitutions implied by those operators are performed
on
.metn form ,
and the
.code qquote
operator returns the resulting structure.

Note: how the qquote operator actually works is that it is compiled into
code. It becomes a Lisp expression which, when evaluated, computes the
resulting structure.

A
.code qquote
can contain another
.codn qquote .
If an
.code unquote
or
.code splice
operator occurs
within a nested
.codn qquote ,
it belongs to that
.codn qquote ,
and not to the outer one.

However, an unquote operator which occurs inside another one belongs one level
higher. For instance in

.cblk
  (qquote (qquote (unquote (unquote x))))
.cble

the leftmost
.code qquote
belongs with the rightmost unquote, and the inner
.code qquote
and
.code unquote
belong together. When the outer
.code qquote
is evaluated,
it will insert the value of
.codn x ,
resulting in the object
.codn "(qquote (unquote [value-of-x]))" .
If this resulting qquote value is evaluated again as Lisp syntax, then it will
yield
.codn [value-of-value-of-x] ,
the value of
.code [value-of-x]
when treated as a Lisp expression and evaluated.

.TP* Examples:

.cblk
  (qquote a) -> a

  (qquote (a b c)) -> (a b c)

  (qquote (1 2 3 (unquote (+ 2 2)) (+ 2 3))) -> (1 2 3 4 (+ 2 3))

  (qquote (unquote (+ 2 2))) -> 4
.cble

In the second-to-last example, the
.code "1 2 3"
and the
.code "(+ 2 3)"
are quoted verbatim.
Whereas the
.code "(unquote (+ 2 2))"
operator caused the evaluation of
.code "(+ 2 2)"
and the substitution of the resulting value.

The last example shows that
.meta form
can itself (the entire argument of
.codn qquote )
can be an unquote operator.
However, note:
.code "(quote (splice form))"
is not valid.

Note: a way to understand the nesting behavior is a via a possible model of
quasi-quote expansion which recursively compiles any nested quasi quotes first,
and then treats the result of their expansion. For instance, in the processing
of

.cblk
  (qquote (qquote (unquote (unquote x))))
.cble

the
.code qquote
operator first encounters the
embedded
.code "(qquote ...)"
and compiles it to code. During that recursive
compilation, the syntax
.code "(unquote (unquote x))"
is encountered.  The inner quote
processes the outer unquote which belongs to it, and the inner
.code "(unquote x)"
becomes material that is embedded verbatim in the compilation, which will then
be found when the recursion pops back to the outer quasiquote, which will
then traverse the result of the inner compilation and find the
.codn "(unquote x)" .

.TP* "Dialect note:"

In Lisp dialects which have a published quasiquoting operator syntax, there is
the expectation that the quasiquote read syntax corresponds to it. That is to
say, that for instance the read syntax
.code "^(a b ,c)"
is expected translated to
.codn "(qquote b (unquote c))" .

In \*(TL, this is not true! Although
.code "^(b b ,c)"
is translated to a
quasiquoting macro, it is an internal one, not based on the public
.codn qquote ,
.code unquote
and
.code splice
symbols being documented here.

This idea exists for hygiene. The quasiquote read syntax is not confused
by the presence of the symbols
.codn qquote ,
.code unquote
or
.code splice
in the template, since it doesn't treat them specially.

This also allows programmers to use the quasiquote read syntax to construct
quasiquote macros. For instance

.cblk
  ^(qquote (unquote ,x)) ;; does not mean ^^,x 
.cble

To the quasiquote reader, the
.code qquote
and
.code unquote
symbols mean nothing special,
and so this syntax simply means that if the value of
.code x
is
.codn foo ,
the result will be
.codn "(qquote (unquote foo))" .

The form's expansion is actually this:

.cblk
  (sys:qquote (qquote (unquote (sys:unquote x))))
.cble

the
.code sys:qquote
macro recognizes
.code sys:unquote
embedded in the form, and
the other symbols not in the
.code sys:
package are just static template material.

The
.code sys:quote
macro and its associated
.code sys:unquote
and
.code sys:splice
operators work exactly like their ordinary counterparts. So in effect, \*(TX has
two nearly identical, independent quasi-quote implementations, one of which is
tied to the read syntax, and one of which isn't. This is useful for writing
quasiquotes which write quasiquotes.

.coNP Operator @ unquote
.synb
.mets (qquote (... (unquote << form ) ...))
.mets (qquote (unquote << form ))
.syne
.desc
The
.code unquote
operator is not an operator
.I per
.IR se .
The
.code unquote
symbol has no
binding in the global environment. It is a special syntax that is recognized
within a
.code qquote
form, to indicate forms within the quasiquote which are to be
evaluated and inserted into the resulting structure.

The syntax
.cblk
.meti (qquote (unquote << form ))
.cble
is equivalent to
.metn form :
the
.code qquote
and
.code unquote
"cancel out".

.coNP Operator @ splice
.synb
.mets (qquote (... (splice << form ) ...))
.syne
.desc
The
.code splice
operator is not an operator
.I per
.IR se .
The
.code splice
symbol has no
binding in the global environment. It is a special syntax that is recognized
within a
.code qquote
form, to indicate forms within the quasiquote which are to be
evaluated and inserted into the resulting structure.

The syntax
.cblk
.meti (qquote (splice << form ))
.cble
is not permitted and raises an exception if evaluated. The
.code splice
syntax must occur within a list, and not in the dotted position.

The
.code splice
form differs from unquote in that
.cblk
.meti (splice << form )
.cble
requires that
.meta form
must evaluate to a list. That list is
integrated into the surrounding list.

.SS* Math Library
.coNP Functions @ + and @ -
.synb
.mets (+ << number *)
.mets (- < number << number *)
.mets (* << number *)
.syne
.desc
The
.codn + ,
.code -
and
.code *
functions perform addition, subtraction and multiplication,
respectively.  Additionally, the
.code -
function performs additive inverse.

The
.code +
function requires zero or more arguments. When called with no
arguments, it produces 0 (the identity element for addition), otherwise it
produces the sum over all of the arguments.

Similarly, the
.code *
function requires zero or more arguments. When called
with no arguments, it produces 1 (the identity element for multiplication).
Otherwise it produces the product of all the arguments.

The semantics of
.code -
changes from subtraction to additive inverse
when there is only one argument. The argument is treated as a subtrahend,
against an implicit minuend of zero. When there are two or more
argument, the first one is the minuend, and the remaining are subtrahends.

When there are three or more operands, these operations are performed as if by
binary operations, in a left-associative way. That is to say,
.code "(+ a b c)"
means
.codn "(+ (+ a b) c)" .
The sum of
.code a
and
.code b
is computed first, and then this is added to
.codn c .
Similarly
.code "(- a b c)"
means
.codn "(- (- a b) c)" .
First,
.code b
is subtracted from
.codn a ,
and then
.code c
is subtracted from that result.

The arithmetic inverse is performed as if it were subtraction from integer 0.
That is,
.code "(- x)"
means the same thing as
.codn "(- 0 x)" .

The operands of
.codn + ,
.code -
and
.code *
can be characters, integers (fixnum and bignum), and
floats, in nearly any combination.

If two operands have different types, then one of them is converted to the
type of the one with the higher rank, according to this ranking:
character < integer < float.  For instance if one operand is integer, and the
other float, the integer is converted to a float.

.TP* Restrictions:

Characters are not considered numbers, and participate in these operations in
limited ways. Subtraction can be used to computed the displacement between the
Unicode values of characters, and an integer displacement can be added to a
character, or subtracted from a character.  For instance
.codn "(- #\e9 #\e0) is 9" .
The Unicode value of a character
.code C
can be found using
.codn "(- C #\ex0)" :
the displacement from the NUL character.

The rules can be stated as a set of restrictions:
.RS
.IP 1
Two characters may not be added together.
.IP 2
A character may not be subtracted from an integer (which also rules out
the possibility of computing the additive inverse of a character).
.IP 3
A character operand may not be opposite to a floating point operand
in any operation.
.IP 4
A character may not be an operand of multiplication.
.RE

.PP

.coNP Functions @, / @ trunc, @ mod and @ trunc-rem
.synb
.mets (/ <> [ dividend ] << divisor *)
.mets (trunc < dividend << divisor )
.mets (mod < dividend << divisor )
.mets (trunc-rem < dividend << divisor )
.syne
.desc
The arguments to these functions are numbers. Characters are not permitted.

The
.code /
function performs floating-point division. Each operands is first
converted to floating-point type, if necessary. If
.meta dividend
is omitted,
then it is taken to be
.code 1.0
and the function calculates the reciprocal. Of these division functions,
only this one may be called with just one argument, or with more than two
arguments.  If there are more than two arguments, then each additional argument
is treated as an additional divisor which further divides the result of the
division by the previous divisors.

The
.code trunc
function performs a division of
.meta dividend
by
.meta divisor
whose result
is truncated to integer toward zero. If both operands are integers, then an
integer division is performed and the result is an integer. If either operand
is a floating point value,  a floating point division occurs, and the result is
truncated toward zero to a floating-point integral value.

The
.code mod
function performs a modulus operation. Firstly, the absolute value
of
.meta divisor
is taken to be a modulus. Then a residue of
.meta dividend
with respect to
.meta modulus
is calculated. The residue's sign follows
that of the sign of
.metn divisor .
That is, it is the smallest magnitude
(closest to zero) residue of
.meta dividend
with respect to the absolute
value of
.metn divisor ,
having the same sign as
.metn divisor .
If the operands are integer, the result is an integer. If either operand
is of type float, then the result is a float. The modulus operation is
then generalized into the floating point domain. For instance the expression
.code "(mod 0.75 0.5)"
yields a residue of 0.25 because 0.5 "goes into" 0.75 only
once, with a "remainder" of 0.25.

The
.code trunc-rem
function returns a list of two values: a
.meta quotient
and a
.metn remainder .
The
.meta quotient
is exactly the same value as what
.code trunc
would return for the same inputs.
The
.meta remainder
obeys the following identity:

.cblk
.mets (eql < remainder (- < dividend >> (* divisor << quotient )))
.cble

.coNP Functions @ wrap and @ wrap*
.synb
.mets (wrap < start < end << number )
.mets (wrap* < start < end << number )
.syne
.desc
The
.code wrap
and
.code wrap*
functions reduce
.meta number
into the range specified by
.meta start
and
.metn end .

Under
.code wrap
the range is inclusive of the
.meta end
value, whereas under
.code wrap*
it is exclusive.

The following equivalence holds

.cblk
  (wrap a b c) <--> (wrap* a (succ b) c)
.cble

The expression
.code "(wrap* x0 x1 x)"
performs the following calculation:

.cblk
.mets (+ (mod (- x x0) (- x1 x0)) x0)
.cble

In other words, first
.meta start
is subtracted from
.metn number .
Then the result is reduced modulo the displacement
between
.code start
and
.codn end .
Finally,
.meta start
is added back to that result, which is returned.

.TP* Example:

.cblk
  ;; perform ROT13 on the string "nop"
  [mapcar (opip (+ 13) (wrap #\ea #\ez)) "nop"] -> "abc"
.cble

.coNP Functions @ gcd and @ lcm
.synb
.mets (gcd << number *)
.mets (lcm << number *)
.syne
.desc
The
.code gcd
function computes the greatest common divisor: the largest positive
integer which divides each
.metn number .

The
.code lcm
function computes the lowest common multiple: the smallest positive
integer which is a multiple of
each
.metn number .

Each
.meta number
must be an integer.

Negative integers are replaced by their absolute values, so
.code "(lcm -3 -4)"
is
.code 12
and
.code "(gcd -12 -9)"
yields
.codn 3 .

The value of
.code (gcd)
is
.code 0
and that of
.code (lcm)
is 1 .

The value of
.code "(gcd x)"
and
.code "(lcm x)"
is
.codn "(abs x)" .

Any arguments of
.code gcd
which are zero are effectively ignored so that
.code "(gcd 0)"
and
.code "(gcd 0 0 0)"
are both the same as
.code (gcd)
and
.code "(gcd 1 0 2 0 3)"
is the same as
.codn "(gcd 1 2 3)" .

If
.code lcm
has any argument which is zero, it yields zero.

.coNP Function @ abs
.synb
.mets (abs << number )
.syne
.desc
The
.code abs
function computes the absolute value of
.metn number .
If
.meta number
is positive, it is returned. If
.meta number
is negative, its additive inverse is
returned: a positive number of the same type with exactly the same magnitude.

.coNP Functions @ floor and @ ceil
.synb
.mets (floor << number )
.mets (ceil << number )
.syne
.desc
The
.code floor
function returns the highest integer which does not exceed
the value of
.metn number .
The ceiling function returns the lowest integer which
does not exceed the value of
.metn number .

If
.meta number
an integer, it is simply returned.

If the argument is a float, then the value returned is a float.
For instance
.code "(floor 1.1)"
returns 1.0 rather than 1.

.coNP Functions @, sin @, cos @, tan @, asin @, acos @ atan and @ atan2
.synb
.mets (sin << radians )
.mets (cos << radians )
.mets (tan << radians )
.mets (atan << slope )
.mets (atan2 < y << x )
.mets (asin << num )
.mets (acos << num )
.syne
.desc
These trigonometric functions convert their argument to floating point and
return a float result. The
.codn sin ,
.code cos
and
.code tan
functions compute the sine and
cosine and tangent of the
.meta radians
argument which represents an angle
expressed in radians. The
.codn atan ,
.code acos
and
.code asin
are their respective inverse
functions.  The
.meta num
argument to
.code asin
and
.code acos
must be in the
range -1.0 to 1.0. The
.code atan2
function converts the rectilinear coordinates
.meta x
and
.meta y
to an angle in polar coordinates in the range [0, 2\(*p).

.coNP Functions @, exp @, log @ log10 and @ log2
.synb
.mets (exp << arg )
.mets (log << arg )
.mets (log10 << arg )
.mets (log2 << arg )
.syne
.desc
The
.code exp
function calculates the value of the transcendental number e raised to
the exponent
.metn arg .

The
.code log
function calculates the base e logarithm of
.metn arg ,
which must be a positive value.

The
.code log10
function calculates the base 10 logarithm of
.metn arg ,
which must be a positive value.

The
.code log2
function calculates the base 2 logarithm of
.metn arg ,
which must be a positive value.

.coNP Functions @, expt @ sqrt and @ isqrt
.synb
.mets (expt < base << exponent *)
.mets (sqrt << arg )
.mets (isqrt << arg )
.syne
.desc
The
.code expt
function raises
.meta base
to zero or more exponents given
by the
.meta exponent
arguments.
.code "(expt x)"
is equivalent to
.codn "(expt x 1)" ,
and yields
.code x
for all
.codn x .
For three or more arguments, the operation is right-associative.
That is to say,
.code "(expt x y z)"
is equivalent to
.codn "(expt x (expt y z))" ,
similarly to the way nested exponents work in standard algebraic
notation.

Exponentiation is done pairwise using a binary operation.
If both operands to this binary operation are integers, then the
result is an integer. If either operand is a float, then the other
operand is converted to a float, and a floating point exponentiation
is performed. Exponentiation that would produce a complex number is
not supported.

The
.code sqrt
function produces a floating-point square root of
.metn arg ,
which is converted from integer to floating-point if necessary.  Negative
operands are not supported.

The
.code isqrt
function computes the integer square root of
.metn arg ,
which must be an integer.
The integer square root is a value which is the
greatest integer that is no greater than the real square root of
.metn arg .
The input value must be an integer.

.coNP Function @ exptmod
.synb
.mets (exptmod < base < exponent << modulus )
.syne
.desc
The
.code exptmod
function performs modular exponentiation and accepts only integer
arguments. Furthermore,
.meta exponent
must be a non-negative and
.meta modulus
must be positive.

The return value is
.meta base
raised to
.metn exponent ,
and reduced to the
least positive residue modulo
.metn modulus .

.coNP Function @ cum-norm-dist
.synb
.mets (cum-norm-dist << argument )
.syne
.desc
The
.code cum-norm-dist
function calculates an approximation to the cumulative normal
distribution function: the integral, of the normal distribution function, from
negative infinity to the
.metn argument .

.coNP Functions @ n-choose-k and @ n-perm-k
.synb
.mets (n-choose-k < n << k )
.mets (n-perm-k < n << k )
.syne
.desc
The
.code n-choose-k
function computes the binomial coefficient nCk which
expresses the number of combinations of
.meta k
items that can be chosen from
a set of
.metn n ,
where combinations are subsets.

The
.code n-perm-k
function computes nPk: the number of permutations of size
.meta k
that can be drawn from a set of
.metn n ,
where permutations are sequences,
whose order is significant.

The calculations only make sense when
.meta n
and
.meta k
are nonnegative integers, and
.meta k
does not exceed
.metn n .
The behavior is not specified if these conditions
are not met.

.coNP Functions @, fixnump @, bignump @, integerp @ floatp and @ numberp
.synb
.mets (fixnump << object )
.mets (bignump << object )
.mets (integerp << object )
.mets (floatp << object )
.mets (numberp << object )
.syne
.desc
These functions test the type of
.metn object ,
returning
.code t
if it is an object
of the implied type,
.code nil
otherwise. The
.codn fixnump ,
.code bignump
and
.code floatp
functions return
.code t
if the object is of the basic type
.codn fixnum ,
.code bignum
or
.codn float .
The function
.code integerp
returns true of
.meta object
is either a
.code fixnum
or
a
.codn bignum .
The function
.code numberp
returns
.code t
if
.meta object
is either
a
.codn fixnum ,
.code bignum
or
.codn float .

.coNP Function @ zerop
.synb
.mets (zerop << number )
.syne
.desc
The
.code zerop
function tests
.meta number
for equivalence to zero. The argument must be
a number or character. It returns
.code t
for the integer value
.code 0
and for the floating-point
value
.codn 0.0 .
For other numbers, it returns
.codn nil .
It returns
.code t
for the null character
.code #\enul
and
.code nil
for all other characters.

.coNP Functions @ plusp and @ minusp
.synb
.mets (plusp << number )
.mets (minusp << number )
.syne
.desc
These functions test whether a number is positive or negative,
returning
.code t
or
.codn nil ,
as the case may be.

The argument may also be a character. All characters other than
the null character
.code #\enul
are positive. No character is negative.

.coNP Functions @ evenp and @ oddp
.synb
.mets (evenp << integer )
.mets (oddp << integer )
.syne
.desc
The
.code evenp
and
.code oddp
functions require integer arguments.
.code evenp
returns
.code t
if
.meta integer
is even (divisible by two), otherwise it returns
.codn nil .
.code oddp
returns
.code t
if
.meta integer
is not divisible by two (odd), otherwise
it returns
.codn nil .

.coNP Functions @, succ @, ssucc @, sssucc @, pred @ ppred and @ pppred
.synb
.mets (succ << number )
.mets (ssucc << number )
.mets (sssucc << number )
.mets (pred << number )
.mets (ppred << number )
.mets (pppred << number )
.syne
.desc
The
.code succ
function adds 1 to its argument and returns the resulting value.
If the argument is an integer, then the return value is the successor
of that integer, and if it is a character, then the return value
is the successor of that character according to Unicode.

The
.code pred
function subtracts 1 from its argument, and under similar considerations
as above, the result represents the predecessor.

The
.code ssucc
and
.code sssucc
functions add 2 and 3, respectively. Similarly,
.code ppred
and
.code pppred
subtract 2 and 3 from their argument.

.coNP Functions @, > @, < @, >= @ <= and @ =
.synb
.mets (> < number << number *)
.mets (> < number << number *)
.mets (>= < number << number *)
.mets (<= < number << number *)
.mets (= < number << number *)
.syne
.desc
These relational functions compare characters and numbers for numeric equality
or inequality. The arguments must be one or more numbers or characters.

If just one argument is given, then these functions all return
.codn t .

If two arguments are given then, they are compared as follows.
First, if the numbers do not have the same type, then the one
which has the lower ranking type is converted to the type of
the other, according to this ranking: character < integer < float.
For instance if a character and integer are compared, the character
is converted to integer. Then a straightforward numeric comparison
is applied.

Three or more arguments may be given, in which case the comparison proceeds
pairwise from left to right. For instance in
.codn "(< a b c)" ,
the comparison
.code "(< a b)"
is performed in isolation. If the comparison is false, then
.code nil
is returned, otherwise
the comparison
.code "(< b c)"
is performed in isolation, and if that is false,
.code nil
is returned, otherwise
.code t
is returned.  Note that it is possible for
.code b
to
undergo two different conversions.  For instance in the
.cblk
.meti (< < float < character << integer )
.cble
comparison,
.meta character
will first convert to a floating-point representation
of its Unicode value so that it can be compared to
.metn float ,
and if that comparison succeeds, then in the second comparison,
.meta character
will be converted to integer so that it can be compared to
.metn integer .

.coNP Function @ /=
.synb
.mets (/= << number *)
.syne
.desc
The arguments to
.code /=
may be numbers or characters.  The
.code /=
function returns
.code t
if no two of its arguments are numerically equal. That is to say, if there
exist some
.code a
and
.code b
which are distinct arguments such that
.code "(= a b)"
is true, then
the function returns
.codn nil .
Otherwise it returns
.codn t .

.coNP Functions @ max and @ min
.synb
.mets (max < first-arg << arg *)
.mets (min < first-arg << args *)
.syne
.desc
The
.code max
and
.code min
functions determine and return the highest or lowest
value from among their arguments.

If only
.meta first-arg
is given, that value is returned.

These functions are type generic, since they compare arguments
using the same semantics as the
.code less
function.

If two or more arguments are given, then
.code "(max a b)"
is equivalent to
.codn "(if (less a b) b a)" ,
and
.code "(min a b)"
is equivalent to
.codn "(if (less a b) a b)" .
If the operands do not
have the same type, then one of them is converted to the type of the other;
however, the original unconverted values are returned. For instance
.code "(max 4 3.0)"
yields the integer
.codn 4 ,
not
.codn 4.0 .

If three or more arguments are given,
.code max
and
.code min
reduce the arguments in a left-associative manner.
Thus
.code "(max a b c)"
means
.codn "(max (max a b) c)" .

.coNP Function @ clamp
.synb
.mets (clamp < low < high << val )
.syne
.desc
The
.code clamp
function clamps value
.meta val
into the range
.meta low
to
.metn high .

The
.code clamp
function returns
.meta low
if
.meta val
is less than
.metn low .
If
.meta val
is greater than or equal to
.metn low ,
but less than
.metn high ,
then it returns
.metn val .
Otherwise it returns
.metn high .

More precisely,
.code "(clamp a b c)"
is equivalent to
.codn "(max a (min b c))" .

.coNP Functions @, int-str @ flo-str and @ num-str
.synb
.mets (int-str < string <> [ radix ])
.mets (flo-str << string )
.mets (num-str << string )
.syne
.desc
These functions extract numeric values from character string
.metn string .
Leading whitespace in
.metn string ,
if any, is skipped. If no digits can be successfully extracted, then
.code nil
is returned.  Trailing material which does not contribute to the number is
ignored.

The
.code int-str
function converts a string of digits in the specified
radix to an integer value. If the radix isn't specified, it defaults to 10.
Otherwise it must be an integer in the range 2 to 36.
For radices above 10, letters of the alphabet
are used for digits:
.code A
represent a digit whose value is 10,
.code B
represents 11 and
so forth until
.codn Z .
For values of radix above 36, the returned value is
unspecified. Upper and lower case letters are recognized.
Any character which is not a digit of the specified radix is regarded
as the start of trailing junk at which the extraction of the digits stops.

The
.code flo-str
function converts a floating-point decimal notation to a nearby
floating point value. The material which contributes to the value
is the longest match for optional leading space, followed by a
mantissa which consists of an optional sign followed by a mixture of at least
one digit, and at most one decimal point, optionally followed by an exponent
part denoted by the letter
.code E
or
.codn e ,
an optional sign and one or more optional exponent digits.

The
.code num-str
function converts a decimal notation to either an integer as if by
a radix 10 application of
.codn int-str ,
or to a floating point value as if by
.codn flo-str .
The floating point interpretation is chosen if the possibly empty
initial sequence of digits (following any whitespace and optional sign) is
followed by a period, or by
.code e
or
.codn E .

.coNP Functions @ int-flo and @ flo-int
.synb
.mets (int-flo << float )
.mets (flo-int << integer )
.syne
.desc
These functions perform numeric conversion between integer and floating point
type. The
.code int-flo
function returns an integer by truncating toward zero.
The
.code flo-int
function returns an exact floating point value corresponding to
.metn integer ,
if possible, otherwise an approximation using a nearby
floating point value.

.coNP Functions @ tofloat and @ toint
.synb
.mets (tofloat << value )
.mets (toint < value <> [ radix ])
.syne
.desc
These convenience functions convert
.meta value
to floating-point or integer, respectively.

If a floating-point value is passed into tofloat, or an integer value into
toint, then the value is simply returned.

If
.meta value
is a character, then it is treated as a string of length one
containing that character.

If
.meta value
is a string, then it is converted by
.code tofloat
as if by the function
.metn flo-str ,
, and by
.code toint
as if by the function
.codn int-str .

If
.meta value
is an integer, then it is converted by
.code tofloat
as if by the function
.codn flo-int .

If
.meta value
is a floating-point number, then it is converted by
.code toint
as if by the function
.codn int-flo .

.coNP Variables @ fixnum-min and @ fixnum-max
.desc
These variables hold, respectively, the most negative value of the
.code fixnum
integer type, and its most positive value. Integer values
from
.code fixnum-min
to
.code fixnum-max
are all of type
.codn fixnum .
Integers outside of this range are
.code bignum
integers.

.coNP Variables @, flo-min @ flo-max and @ flo-epsilon
.desc
These variables hold, respectively: the smallest positive floating-point
value; the largest positive floating-point value; and the difference
between 1.0 and the smallest representable value greater than 1.0.

.code flo-min
and
.code flo-max
define the floating-point range, which consists
of three regions: values from
.code "(- flo-max)"
to
.codn "(- flo-min)" ;
the value 0.0, and values from
.code flo-min
to
.codn flo-max .

.coNP Variable @ flo-dig
.desc
This variable holds an integer representing the number of decimal digits
in a decimal floating-point number such that this number can be converted
to a \*(TX floating-point number, and back to decimal, without a change in any of
the digits. This holds regardless of the value of the number, provided that it
does not exceed the floating-point range.

.coNP Variable @ flo-max-dig
.desc
This variable holds an integer representing the maximum number of
decimal digits required to capture the value of a floating-point number
such that the resulting decimal form will convert back to the same
floating-point number. See also the
.code *print-flo-precision*
variable.

.coNP Variables @ %pi% and @ %e%
.desc
These variables hold an approximation of the mathematical constants \(*p and e.
To four digits of precision, \(*p is 3.142 and e is 2.718. The
.code %pi%
and
.code %e%
approximations are accurate to
.code flo-dig
decimal digits.

.SS* Bit Operations
In \*(TL, similarly to Common Lisp, bit operations on integers are based
on a concept that might be called "infinite two's-complement".  
Under infinite two's complement, a positive number is regarded as having
a binary representation prefixed by an infinite stream of zero digits (for
example
.code 1
is
.codn ...00001 ).
A negative number
in infinite two's complement is the bitwise negation of its positive counterpart,
plus one: it carries an infinite prefix of 1 digits. So for instance the number
.code -1
is represented by
.codn ...11111111 :
an infinite sequence of
1
bits. There
is no specific sign bit; any operation which produces such an infinite sequence
of 1 digits on the left gives rise to a negative number. For instance, consider the
operation of computing the bitwise complement of the number
.codn 1 .
Since the
number
.code 1
is represented as
.codn ...0000001 ,
its complement is
.codn ...11111110 .
Each one of the
.code 0
digits in the infinite sequence is replaced by
.codn 1 ,
And this leading sequence means that the number
is negative, in fact corresponding to the two's-complement representation of
the value
.codn -2 .
Hence, the infinite digit concept corresponds to an arithmetic
interpretation.

In fact \*(TL's bignum integers do not use a two's complement
representation internally. Numbers are represented as an array which holds a
pure binary number. A separate field indicates the sign: negative,
or non-negative.  That negative numbers appear as two's-complement under the
bit operations is merely a carefully maintained illusion (which makes bit
operations on negative numbers more expensive).

The
.code logtrunc
function, as well as a feature of the
.code lognot
function, allow bit
manipulation code to be written which works with positive numbers only, even if
complements are required. The trade off is that the application has to manage a
limit on the number of bits.

.coNP Functions @, logand @ logior and @ logxor
.synb
.mets (logand << integer *)
.mets (logior << integer *)
.mets (logxor < int1 << int2 )
.syne
.desc
These operations perform the familiar bitwise and, inclusive or, and exclusive
or operations, respectively. Positive values inputs are treated as
pure binary numbers.  Negative inputs are treated as infinite-bit
two's-complement.

For example
.code "(logand -2 7)"
produces
.codn 6 .
This is because
.code -2
is
.code ...111110
in infinite-bit two's-complement.  And-ing this value with
.code 7
(or
.codn ...000111 )
produces
.codn 110 .

The
.code logand
and
.code logior
functions are variadic, and may be called with zero, one,
two, or more input values. If
.code logand
is called with no arguments, it produces
the value -1 (all bits 1). If
.code logior
is called with no arguments it produces
zero. In the one-argument case, the functions just return their argument value.

.coNP Function @ logtest
.synb
.mets (logtest < int1 << int2 )
.syne
.desc
The
.code logtest
function returns true if
.meta int1
and
.meta int2
have bits in
common. The following equivalence holds:

.cblk
  (logtest a b) <--> (not (zerop (logand a b)))
.cble

.coNP Functions @ lognot and @ logtrunc
.synb
.mets (lognot < value <> [ bits ])
.mets (logtrunc < value << bits )
.syne
.desc
The
.code lognot
function performs a bitwise complement of
.metn value .
When the one-argument form of lognot is used, then if
.meta value
is nonnegative,
then the result is negative, and vice versa, according to the infinite-bit
two's complement representation. For instance
.code "(lognot -2)"
is
.codn 1 ,
and
.code "(lognot 1)"
is
.codn -2 .

The two-argument form of
.code lognot
produces a truncated complement. Conceptually,
a bitwise complement is first calculated, and then the resulting number is
truncated to the number of bits given by
.metn bits ,
which must be a nonnegative integer. The following equivalence holds:

.cblk
  (lognot a b) <--> (logtrunc (lognot a) b)
.cble

The
.code logtrunc
function truncates the integer
.meta value
to the  specified number
of bits. If
.meta value
is negative, then the two's-complement representation
is truncated. The return value of
.code logtrunc
is always a non-negative integer.

.coNP Function @ sign-extend
.synb
.mets (sign-extend < value << bits )
.syne
.desc
The
.code sign-extend
function first truncates the infinite-bit two's complement representation of
the integer
.meta value
to the specified number of bits, similarly to the
.code logtrunc
function. Then, this truncated value is regarded as a
.meta bits
wide two's complement integer. The value of this integer is
calculated and returned.

.TP* Examples:

.cblk
  (sign-extend 127 8) -> 127
  (sign-extend 128 8) -> -128
  (sign-extend 129 8) -> -127
  (sign-extend 255 8) -> -1
  (sign-extend 256 8) -> 0
  (sign-extend -1  8) -> -1
  (sign-extend -255 8) -> 0
.cble

.coNP Function @ ash
.synb
.mets (ash < value << bits )
.syne
.desc
The
.code ash
function shifts
.meta value
by the specified number of
.meta bits
producing a
new value.  If
.meta bits
is positive, then a left shift takes place.  If
.meta bits
is negative, then a right shift takes place. If
.meta bit
is zero, then
.meta value
is returned unaltered.  For positive numbers, a left shift by n bits is
equivalent to a multiplication by two to the power of n, or
.codn "(expt 2 n)" .
A right shift by n bits of a positive integer is equivalent to integer
division by
.codn "(expt 2 n)" ,
with truncation toward zero.
For negative numbers, the bit shift is performed as if on the two's-complement
representation. Under the infinite two's-complement representation,
a right shift does not exhaust the infinite sequence of
.code 1
digits which
extends to the left. Thus if
.code -4
is shifted right it becomes
.code -2
because
the bitwise representations of these values are
.code ...111100
and
.codn ...11110 .

.coNP Function @ bit
.synb
.mets (bit < value << bit )
.syne
.desc
The
.code bit
function tests whether the integer
.meta value
has a 1 in bit position
.metn bit .
The
.meta bit
argument must be a non-negative integer. A value of zero of
.meta bit
indicates the least significant bit position of
.metn value .

The
.code bit
function has a Boolean result, returning the symbol
.code t
if bit
.meta bit
of
.meta value
is set, otherwise
.codn nil .

If
.meta value
is negative, it is treated as if it had an infinite-bit two's
complement representation. For instance, if value is 
.codn -2 ,
then the bit
function returns
.code nil
for a
.meta bit
value of zero, and
.code t
for all other values,
since the infinite bit two's complement representation of
.code -2
is
.codn ...11110 .

.coNP Function @ mask
.synb
.mets (mask << integer *)
.syne
.desc
The
.code mask
function takes zero or more integer arguments, and produces an integer
value which corresponds a bitmask made up of the bit positions specified by the
integer values.

If
.code mask
is called with no arguments, then the return value is zero.

If
.code mask
is called with a single argument
.meta integer
then the return value is the same as
that of the expression
.codn "(ash 1 <integer>)" :
the value 1 shifted left by
.meta integer
bit positions. If
.meta integer
is zero, then the result is
.codn 1 ;
if
.meta integer
is
.codn 1 ,
the
result is
.code 2
and so forth.  If
.meta value
is negative, then the result is zero.

If
.code mask
is called with two or more arguments, then the result is a bitwise of
the masks individually computed for each of the values.

In other words, the following equivalences hold:

.cblk
  (mask) <--> 0
  (mask a) <--> (ash 1 a)
  (mask a b c ...) <--> (logior (mask a) (mask b) (mask c) ...)
.cble

.coNP Function @ width
.synb
.mets (width << integer *)
.syne
.desc
A two's complement representation of an integer consists of a sign bit and a
mantissa field.
The
.code width
function computes the minimum number of bits required for the mantissa portion
of the two's complement representation of the
.meta integer
argument.

For a nonnegative argument, the width also corresponds to the number of bits
required for a natural binary representation of that value.

Two integer values have a width of zero, namely 0 and -1. This means that these
two values can be represented in a one-bit two's complement, consisting of only
a sign bit: the one-bit two's complement bitfield 1 denotes -1, and 0 denotes
0.

Similarly, two integer values have a width of 1: 1 and -2. The two-bit
two's complement bitfield 01 denotes 1, and 10 denotes -2.

The argument may be a character.

.SS* Exception Handling

An
.I exception
in \*(TX is a special event in the execution of the program which
results in transfer of control. An exception is identified by a symbol,
known as the
.IR "exception type" ,
and it carries zero or more arguments, called the
.IR "exception arguments" .

When an exception is initiated, it is said to be
.IR thrown .
When an exception is thrown, \*(TX enters into exception processing
mode. Exception processing mode terminates in one of several ways:
.IP -
A
.I catch
is found which matches the exception, and control is transferred
to the catch. Catches are defined by the
.code catch
operator.
.IP -
A handler accepts the exception by performing a non-local transfer.
Handlers are defined by the
.code handler-bind
operator or
.code handle
macro.
.IP -
If no catch or accepting handler is found, control is transferred
to the function stored in the
.code *unhandled-hook*
variable. If that function returns, then unwinding is performed
after which the process terminates (unless the unwinding actions
intercept the control to prevent that).
.IP -
If no catch or accepting handler is found and
.code *unhandled-hook*
is
.codn nil ,
then a built-in strategy for handling the exception is invoked,
consisting of unwinding, and then printing some informational messages and
terminating.
.PP

From the above it should be evident that there are two ways by which exceptions
are handled: catches and handlers. Catches and handlers are similar, but different.
A catch is an exit point associated with an active scope. When an exception is
handled by a catch, the form which threw the exception is abandoned, and unwinding
takes place to the catch site, which receives the exception type and arguments.
A handler is also associated with an active scope. However, it is a function,
and not a dynamic exit point.  When an exception is passed to handler,
unwinding does not take place; rather, the function is called. The function then
either completes the exception handling by performing a non-local transfer,
or else declines the exception by performing an ordinary return.

Catches and handlers are identified by exception type symbols. A catch or
handler is eligible to process an exception if it handles a type which is
a supertype of the exception which is being processed. Handles and catches
are located in a combined search which proceeds from the innermost nesting
to the outermost. When an eligible handle is encountered, it is called. If
it returns, the search continues. When an eligible catch is encountered,
the search stops and a control transfer takes place to the catch site.

Exception types are arranged
in an inheritance hierarchy, at whose top the symbol
.code t
is is the supertype of every exception type, and the
.code nil
symbol is at the bottom, the subtype of every exception type.

Keyword symbols may be used as exception types.

Every symbol is its own supertype and subtype. Thus whenever X is known to be a
subtype of Y, it is possible that X is exactly Y.
The
.code defex
macro registers exception supertype/subtype relationships among symbols.

.coNP Functions @, throw @ throwf and @ error
.synb
.mets (throw < symbol << arg *)
.mets (throwf < symbol < format-string << format-arg *)
.mets (error < format-string << format-arg *)
.syne
.desc
These functions generate an exception. The
.code throw
and
.code throwf
functions generate
an exception identified by
.metn symbol ,
whereas
.code error
throws an exception of
type
.codn error .
The call
.code "(error ...)"
can be regarded as a shorthand for
.codn "(throwf 'error ...)" .

The
.code throw
function takes zero or more additional arguments. These arguments
become the arguments of a
.code catch
handler which takes the exception. The
handler will have to be capable of accepting that number of arguments.

The
.code throwf
and
.code error
functions generate an exception which has a single
argument: a character string created by a formatted print to a string stream
using the
.code format
string and additional arguments.

.coNP Operator @ catch
.synb
.mets (catch < try-expression
.mets \ \  >> {( symbol <> ( arg *) << body-form *)}*)
.syne
.desc
The
.code catch
operator establishes an exception catching block around
the
.metn try-expression .
The
.meta try-expression
is followed by zero or more
catch clauses. Each catch clause consists of a symbol which denotes
an exception type, an argument list, and zero or more body forms.

If
.meta try-expression
terminates normally, then the catch clauses
are ignored. The catch itself terminates, and its return value is
that of the
.metn try-expression .

If
.meta try-expression
throws an exception which is a subtype of one or more of
the type symbols given in the exception clauses, then the first (leftmost) such
clause becomes the exit point where the exception is handled.
The exception is converted into arguments for the clause, and the clause
body is executed. When the clause body terminates, the catch terminates,
and the return value of the catch is that of the clause body.

If
.meta try-expression
throws an exception which is not a subtype of any of
the symbols given in the clauses, then the search for an exit point for
the exception continues through the enclosing forms. The catch clauses
are not involved in the handling of that exception.

When a clause catches an exception, the number of arguments in the catch must
match the number of elements in the exception.  A catch argument list
resembles a function or lambda argument list, and may be dotted.  For instance
the clause
.code "(foo (a . b))"
catches an exception subtyped from
.codn foo ,
with one or
more elements. The first element binds to parameter
.codn a ,
and the rest, if any,
bind to parameter
.codn b .
If there is only one element,
.code b
takes on the value
.codn nil .

Also see: the
.code unwind-protect
operator, and the functions
.codn throw ,
.code throwf
and
.codn error ,
as well as the
.code handler-bind
operator and
.code handler
macro.

.coNP Operator @ unwind-protect
.synb
.mets (unwind-protect < protected-form << cleanup-form *)
.syne
.desc
The
.code unwind-protect
operator evaluates
.meta protected-form
in such a way that no matter how the execution of
.meta protected-form
terminates, the
.metn cleanup-form -s
will be executed.

The
.metn cleanup-form -s,
however, are not protected. If a
.meta cleanup-form
terminates via
some non-local jump, the subsequent
.metn cleanup-form -s
are not evaluated.

.metn cleanup-form -s
themselves can "hijack" a non-local control transfer such
as an exception. If a
.meta cleanup-form
is evaluated during the processing of
a dynamic control transfer such as an exception, and that
.meta cleanup-form
initiates its own dynamic control transfer, the original control transfer
is aborted and replaced with the new one.

.TP* Example:
.cblk
  (block foo
    (unwind-protect
      (progn (return-from foo 42)
             (format t "not reached!\en"))
      (format t "cleanup!\en")))
.cble

In this example, the protected
.code progn
form terminates by returning from
block
.codn foo .
Therefore the form does not complete and so the
output
.str not reached!
is not produced. However, the cleanup form
executes, producing the output
.strn cleanup! .


.coNP Macro @ ignerr
.synb
.mets (ignerr << form *)
.syne
.desc
The
.code ignerr
macro operator evaluates each
.meta form
similarly to the
.code progn
operator. If no forms are present, it returns
.codn nil .
Otherwise it evaluates each
.meta form
in turn, yielding the value of the last one.

If the evaluation of any
.meta form
is abandoned due to an exception of type
.codn error ,
the code generated by the
.code ignerr
macro catches this exception. In this situation,
the execution of the
.code ignerr
form terminates without evaluating the remaining
forms, and yields
.codn nil .

.coNP Operator @ handler-bind
.synb
.mets (handler-bind < function-form < symbol-list << body-form *)
.syne
.desc
The
.code handler-bind
operator establishes a handler for one or more
exception types, and evaluates zero or more
.metn body-form -s
in a dynamic scope in which that handler is visible.

When the
.code handler-bind
form terminates normally, the handler is removed. The value of the
last
.meta body-form
is returned, or else
.code nil
if there are no forms.

The
.meta function-form
argument is an expression which must evaluate to a function. The function
must be capable of accepting the exception arguments. All exceptions functions
require at least one argument, since the leftmost argument in an exception handler
call is the exception type symbol.

The
.meta symbol-list
argument is a list of symbols, not evaluated. If it is empty, then the handler
isn't eligible for any exceptions. Otherwise it is eligible for any exception
whose exception type is a subtype of any of the symbols.

If the evaluation of any
.meta body-form
throws an exception which is not handled within that form, and the handler
is eligible for that exception, then the function is invoked. It receives
the exception's type symbol as the leftmost argument. If the exception has
arguments, they appear as additional arguments in the function call.
If the function returns normally, then the exception search continues.
The handler remains established until the exception is handled in such a way
that a dynamic control transfer abandons the
.code handler-bind
form.

Note: while a handler's function is executing, the handler is disabled.
If the function throws an exception for which the handler is eligible,
the handler will not receive that exception; it will be skipped by the
exception search as if it didn't exist.  When the handler function terminates,
either via a normal return or a nonlocal control transfer, then the handler is
re-enabled.

.coNP Macro @ handle
.synb
.mets (handle < try-expression
.mets \ \  >> {( symbol <> ( arg *) << body-form *)}*)
.syne
.desc
The
.code handle
macro is a syntactic sugar for the
.code handler-bind
operator. Its syntax is exactly like that of
.codn catch .
The difference between
.code handle
and
.code catch
is that the clauses in
.code handle
are invoked without unwinding. That is to say,
.code handle
does not establish an exit point for an exception. When control passes to
a clause, it is by means of an ordinary function call and not a dynamic
control transfer. No evaluation frames are yet unwound when this takes place.

The
.code handle
macro establishes a handler, by
.code handler-bind
whose
.meta symbol-list
consists of every
.meta symbol
gathered from every clause.

The handler function established in the generated
.code handler-bind
is synthesized from of all of the clauses, together with dispatch logic which
which passes the exception and its arguments to the first
eligible clause.

The
.meta try-expression
is evaluated in the context of this handler.

The clause of the
.code handle
syntax can return normally, like a function, in which case the handler
is understood to have declined the exception, and exception processing
continues. To handle an exception, the clause of the
.code handle
macro must perform a dynamic control transfer, such returning from a block
via
.code return
or throwing an exception.

.coNP Macro @ with-resources
.synb
.mets (with-resources >> ({ sym >> [ init-form <> [ cleanup-form ])}*)
.mets \ \  << body-form *)
.syne
.desc
The
.code with-resources
macro provides a sequential binding construct similar to
.codn let* .
Every
.meta sym
is established as a variable which is visible to the
.metn init-form -s
of subsequent variables, to all subsequent
.metn cleanup-form -s
including that of the same variable,
and to the
.metn body-form -s.

If no
.meta init-form
is supplied, then
.meta sym
is bound to the value
.codn nil .

If an
.meta init-form
is supplied, but no
.metn cleanup-form ,
then
.meta sym
is bound to the value of the
.metn init-form .

If a
.meta cleanup-form
is supplied in addition to
.metn init-form ,
it specifies code to be executed upon the termination of the
entire
.code with-resources
construct.

When an instance of
.code with-resources
terminates, all of the
.metn cleanup-form -s
specified in its binding clauses are evaluated, in reverse (right-to-left)
order. The value of the last
.meta body-form
is returned, or else
.code nil
if no
.metn body-form -s
are present.

.TP* "Example:"

The following opens a text file and reads a line from it, returning that line,
while ensuring that the stream is closed immediately:

.cblk
(with-resources ((f (open-file "/etc/motd") (close-stream f)))
  (whilet ((l (get-line f)))
    (put-line l)))
.cble



.coNP Special variable @ *unhandled-hook*
The
.code *unhandled-hook*
variable is initialized with
.code nil
by default.

It may instead be assigned a function which is capable of taking
three arguments.

When an exception occurs which has no handler, this function is called,
with the following arguments: the exception type symbol, the exception object,
and a third value which is either
.code nil
or else the form which was being evaluated when the exception was thrown.
The call occurs before any unwinding takes place.

If the variable is
.codn nil ,
or isn't a function, or the function returns after being called,
then unwinding takes place, after which some informational messages are printed
about the exception, and the process exits with a failed termination status.

In the case when the variable contains a object other than
.code nil
which isn't a function, a diagnostic message is printed on the
.code *stderr*
stream prior to unwinding.

Prior to the function being called, the
.code *unhandled-hook*
variable is reset to
.codn nil .

Note: the functions
.code source-loc
or
.code source-loc-str
may be applied to the third argument of the
.code *unhandled-hook*
function to obtain more information about the form.

.coNP Macro @ defex
.synb
.mets (defex <> { symbol }*)
.syne
.desc
The macro
.code defex
records hierarchical relationships among symbols, for the purposes
of the use of those symbols as exceptions. It is closely related to the
.code @(defex)
directive in the \*(TX pattern language, performing the same function.

All symbols are considered to be exception subtypes, and every symbol
is implicitly its own exception subtype. This macro does not introduce
symbols as exception types; it only introduces subtype-supertype
relationships.

If
.code defex
is invoked with no arguments, it has no effect.

If arguments are present, they must be symbols.

If
.code defex
is invoked with only one symbol as its argument, it has no effect.

At least two
symbols must be specified for a useful effect to take place.  If exactly two
symbols are specified, then, subject to error checks,
.code defex
makes the left symbol an
.I exception subtype
of the right symbol.

This behavior generalizes to three or more arguments: if three or more symbols
are specified, then each symbol other than the last is registered as a subtype of
the symbol which follows.

If a
.code defex
has three or more arguments, they are processed from left to right.
If errors are encountered during the processing, the correct registrations
already made for prior arguments remain in place.

It is erroneous to register a duplicate relationship. If symbol
.code a
is already a direct or indirect subtype of
.code b
then
.code "(defex a b)"
and
.code "(defex a x b)"
are erroneous.

Every symbol is implicitly considered to be its own exception subtype,
therefore it is erroneous to explicitly register a symbol as its
own subtype.

The foregoing rules eliminate the possibility of creating cycles in the
exception subtype inheritance graph.

The symbol
.code nil
is implicitly a subtype of every exception type. Therefore, it is erroneous
to attempt to specify it as a supertype in a registration.
Using
.code nil
as a subtype in a registration is silently permitted, but has no effect.
No explicit registration is recorded between
.code nil
and its successor in the argument list.

The symbol
.code t
is implicitly the supertype of every exception type. Therefore, it
is erroneous to attempt to register it as an exception subtype.
Using
.code t
as a supertype in a registration is also erroneous.

Keyword symbols may be used as exception types.

.coNP Function @ register-exception-subtypes
.synb
.mets (register-exception-subtypes <> { symbol }*)
.syne
.desc
The
.code register-exception-subtypes
function constitutes the underlying implementation for the
.code defex
macro.

The following equivalence applies:

.cblk
  (defex a b ...)  <-->  (register-exception-subtypes 'a 'b ...)
.cble

That is, the
.code defex
macro works as if by generating a call to the function, with
the arguments quoted.

The semantics of the function is precisely that of the macro.

.coNP Function @ exception-subtype-p
.synb
.mets (exception-subtype-p < left-symbol << right-symbol )
.syne
.desc
The
.code exception-subtype-p
function tests whether two symbols are in a relationship as exception types,
such that
.meta left-symbol
is a direct or indirect exception subtype of
.metn right-symbol .

If that is the case, then
.code t
is returned, otherwise
.codn nil .

.coNP Structures @, frame @ catch-frame and @ handle-frame
.synb
  (defstruct frame nil)
  (defstruct catch-frame frame types jump)
  (defstruct handle-frame frame types fun)
.syne
.desc
The structure types
.codn frame ,
.code catch-frame
and
.code handle-frame
are used by the
.code get-frames
and
.code find-frame
functions to represent information about the currently established
exception catches (see the
.code catch
macro) and handlers
(see
.code handler-bind
and
.codn handler ).

The
.code frame
type serves as the common base for
.code catch-frame
and
.codn handle-frame .

Modifying any of the slots of these structures has no effect on the
actual frame from which they are derived; the frame structures are only
representation which provides information about frames. They are not
the actual frames themselves.

Both
.code catch-frame
and
.code handle-frame
have a
.code types
slot. This holds the list of exception type symbols which are matched
by the catch or handler.

The
.code jump
slot of a
.code catch-frame
is an opaque
.code cptr
("C pointer")
object which is related to the stack address of the catch
frame. If it is altered, the catch frame object becomes invalid
for the purposes of
.codn invoke-catch .

The
.code fun
slot of a
.code handle-frame
is the registered handler function. Note that all the clauses of a
.code handler
macro are compiled to a single function, which is established via
.codn handler-bind ,
so an instance of the
.code handler
macro corresponds to a single
.codn handle-frame .

.coNP Function @ get-frames
.synb
.mets (get-frames)
.syne
.desc
The
.code get-frames
function inquires the current dynamic environment in order to retrieve
information about established exception catch and handler frames.
The function returns a list, ordered from the inner-most nesting
level to the outer-most nesting, of structure objects derived from the
.code frame
structure type. The list contains two kinds of objects: structures
of type
.code catch-frame
and of type
.codn handle-frame .

These objects are not the frames themselves, but only provide information
about frames. Modifying the slots in these structures has no effect on
the original frames. Also, these structures have their own lifetime and
can endure after the original frames have disappeared. This has implications
for the use of the
.code invoke-catch
function.

The
.code handle-frame
structures have a
.code fun
slot, which holds a function. It may be invoked directly.

A
.code catch-frame
structure may be passed as an argument to the
.code invoke-catch
function.

.coNP Function @ find-frame
.synb
.mets (find-frame >> [ exception-symbol <> [ frame-type ]])
.syne
.desc
The
.code find-frame
function locates the first (innermost) instance of a specific kind of
exception frame (a catch frame or a handler frame) which is eligible
for processing an exception of a specific type. If such a frame
is found, it is returned.  The returned frame object is of the same kind as the
objects which comprise the list returned by the function
.codn get-frames .
If such a frame is not found,
.code nil
is returned.

The
.meta exception-symbol
argument specifies a match by exception type: the candidate frame
must specify in its list of matches at least one type which is an exception
supertype of
.metn exception-symbol .
If this argument is omitted, it defaults to
.code nil
which finds any handler that matches at least one type. There is no way to
search for handlers which match an empty set of types; the
.code find-frame
function skips such frames.

The
.meta frame-type
argument specifies which frame type to find. Useful values for this
argument are the structure type names
.code catch-frame
and
.code handle-frame
or the actual structure type objects which these type names denote.
If any other value is specified, the function returns
.codn nil .
If the argument is omitted, it defaults to the type of the
.code catch-frame
structure. That is to say, by default, the function looks for catch
frames.

Thus, if
.code find-frame
is called with no arguments at all it finds the innermost catch frame,
if any exists, or else returns
.codn nil .

.coNP Function @ invoke-catch
.synb
.mets (invoke-catch < catch-frame < symbol << argument *)
.syne
.desc
The
.code invoke-catch
function abandons the current evaluation context to perform
a non-local control transfer directly to the catch
described by the
.meta catch-frame
argument, which must be a structure of type
.code catch-frame
returned by a call to
.code get-frame
or
.codn find-frame .

The control transfer is possible only if the catch
frame represented by
.meta catch-frame
structure is still established, and if the structure
hasn't been tampered with.

If a given
.code catch-frame
structure is usable with
.codn invoke-catch ,
then a copy of that structure made with
.code copy-struct
is also usable, denoting the same catch frame.

The
.meta symbol
argument should be an exception symbol. It is passed to the
exception frame, as if it had appeared as the first argument of the
.code throw
function. Similarly, the
.metn argument -s
are passed to the catch frame as if they were the trailing arguments
of a
.codn throw .
The difference between
.code invoke-catch
and
.code throw
is that
.code invoke-catch
targets a specific catch frame as its exit point, rather than searching for a
matching catch or handler frame. That specific frame receives the control.
The frame receives control even if it it is not otherwise eligible for
catching the exception type denoted by
.metn symbol .

.SS* Delimited Continuations

\*(TL supports delimited continuations, which are integrated with the
.code block
feature. Any named or anonymous block, including the implicit blocks
created around function bodies, can be used as the delimiting
.I prompt
for the capture of a continuation.

A delimited continuation is section of a possible future of the
computation, up to a delimiting prompt,
.I reified
as a first class function.

.TP* Example:

.cblk
  (defun receive (cont)
    (format t "cont returned ~a\en" (call cont 3)))

  (defun function ()
    (sys:capture-cont 'abcd (fun receive)))

  (block abcd
    (format t "function returned ~a\en" (function))
    4)

  Output:

  function returned 3
  cont returned 4
  function returned t
.cble

.PP

Evaluation begins with the
.code block
form. This form calls
.code function
which uses
.code sys:capture-cont
to capture a continuation up to the
.code abcd
prompt.  The continuation is passed to the
.code receive
function as an argument.

This captured object represents the continuation of computation
up to that prompt.  It appears as a one-argument function which, when called,
resumes the captured computation. Its argument emerges out of the
.code sys:capture-cont
call as a return value. When the computation eventually returns all
the way to the delimiting prompt, the return value of that prompt
will then appear as the return value of the continuation function.

In this example, the function
.code receive
immediately invokes the continuation function which it receives, passing
it the argument value
.codn 3 .
And so,
evaluation now continues in the resumed future represented by the
continuation. Inside the continuation,
.code sys:capture-cont
appears to return, yielding the value
.codn 3 .
This bubbles up through
.code function
up to the
.code "block abcd"
where a message is printed:
.strn "function returned 3" .

The
.code block
terminates, yielding the value 4. Thereby, the continuation ends, since
it is delimited up to that block.  Control now returns to the
.code receive
function which invoked the continuation, where the function call form
.code "(call cont)"
terminates, yielding the value
.code 4
that was returned by the continuation's delimiting
.code block
form. The message
.str "cont returned 4"
is printed. The
.code receive
function returns normally, returning the value
.code t
which emerged from the
.code format
call. Control is now back in
.code function
where the
.code sys:capture-cont
form terminates and returns the
.codn t .
This bubbles up to
.code block
which prints
.strn "function returned t" .

In summary, a continuation represents, as a function, the subsequent
computation that is to take place starting at some point, up to some
recently established, dynamically enclosing delimiting prompt. When
the continuation is captured, that future doesn't have to take place;
an alternative future can carry out in which that continuation is
available as a function. That alternative future can invoke the continuation at
will.  Invocations (resumptions) of the continuation appear as additional
returns from the capture operator. A resumption of a continuation terminates
when the delimiting prompt terminates, and the continuation yields the
value which emerges from the prompt.

Delimited continuations are implemented by capturing a segment of the
evaluation stack between the prompt and the capture point. When
a continuation is resumed, this saved copy of a stack segment is inserted on
top of the current stack and the procedure context is resumed such
that evaluation appears to emerge from the capture operator.
As the continuation runs to completion, it simply pops these inserted
stack frames naturally. Eventually it pops out of the delimiting prompt,
at which point control ends up at the point which invoked the continuation
function.

The low-level operator for capturing a continuation is
.codn sys:capture-cont .
More expressive and convenient programming with continuations is
provided by the macros
.codn obtain ,
.codn obtain-block ,
.code yield-from
and
.codn yield ,
which create an abstraction which models the continuation as a suspended
procedure supporting two-way communication of data.
A
.code suspend
operator is provided, which is more general. It is identical to the
.code shift
operator described in various computer science literature about
delimited continuations, except that it refers to a specific delimiting
prompt by name.

Continuations raise the issue of what to do about unwinding.
The language Scheme provides the much criticized
.code dynamic-wind
operator which can execute initialization and clean-up code as
a continuation is entered and abandoned. \*(TX takes a simpler,
albeit risky approach. It provides a non-unwinding escape operator
.code sys:abscond-from
for use with continuations. Code which has captured a continuation
can use this operator to escape from the delimiting block without
triggering any unwinding among the frames between the capture point and the
delimiter. When the continuation is restarted, it will then do so
with all of the resources associated with it frames intact.
When the continuation executes normal returns within its context,
the unwinding takes place then.  Thus tidy, "thread-like" use
of continuations is possible with a small measure of coding discipline.
Unfortunately, the absconding operator is dangerous: its use
breaks the language guarantee that clean-up associated with a form is done no
matter how a form terminates.

.TP* Notes:

Delimited continuations resemble lexical closures in some ways. Both
constructs provide a way to return to some context whose evaluation
has already been abandoned, and to access some aspects of that context.
However, lexical closures are statically scoped. Closures capture the lexically
apparent scope at a given point, and produce a function whose body has access
to that scope, as well as to some arbitrary arguments. Thus, a lexical scope
is reified as a first-class function. By contrast, a delimited continuation
is dynamic. It captures an an entire segment of a program activation chain,
up to the delimiting prompt. This segment includes scopes which are not
lexically visible at the capture point: the scopes of parent functions.
Moreover, the segment includes not only scopes, but also other aspects of
the evaluation context, such as the possibility of returning to callers,
and the (captured portion of) the original dynamic environment, such as
exception handlers.  That is to say, a lexical closure's body cannot return to
the surrounding code or see any of its original dynamic environment; it can
only inspect the environment, and then return to its own caller.  Whereas a
restarted delimited continuation can continue evaluation of the surrounding
code, return to surrounding forms and parent functions, and access the dynamic
environment. The continuation function returns to its caller when that entire
restarted context terminates, whereas a closure returns to its caller as soon
as the closure body terminates.

.coNP Function @ sys:capture-cont
.synb
.mets (sys:capture-cont < name < receive-fun <> [ context-form ])
.syne
.desc
The
.code sys:capture-cont
function captures a continuation, and also serves as the resume point
for the resulting continuation. Which of these two situations is the
case (capture or resumption) is distinguished by the use of the
.meta receive-fun
argument, which must be a function capable of being called with one
argument.

A block named
.meta name
must be visible; the continuation is delimited by the closest
enclosing block of this name.

The optional
.meta context-form
argument should be a compound form. If
.code sys:capture-cont
reports an error, it reports it against this form,
and uses the form's operator symbol as the name of the function which
encountered the error.  If the argument is omitted,
.code sys:capture-cont
uses its own name.

The
.code sys:capture-cont
function captures a continuation, represented as a function.
It immediately calls
.metn receive-fun ,
passing it it the continuation function as an argument.
If
.meta receive-fun
returns normally, then
.code sys:capture-cont
returns whatever value
.meta receive-fun
returns.

When the continuation function is called (thereby resuming the captured
continuation), inside that resumed continuation,
.code sys:capture-cont
function appears to return.  Its return value is the argument
which was passed to the continuation function.  The continuation function
appears suspended while the resumed continuation executes.
If the resumed continuation context terminates normally (by terminating
the continuation's delimiting block named by
.metn name )
the continuation function terminates, and yields the value which emerged
from the terminated block.

If the symbol
.code sys:cont-poison
is passed to the continuation function, the continuation will be
resumed in a different manner: its context will be restored as in the
ordinary resume case, whereupon it will be immediately abandoned by
a nonlocal exit, causing unwinding to take place across all of the
evaluation's continuation frames. The function then returns
.codn nil .

If the symbol
.code sys:cont-free
is passed to the continuation function, the continuation isn't
be resumed at all; rather, the buffer which holds the saved context
of the continuation is released. Thereafter, an attempt to resume
the continuation results in an error exception being thrown.
After releasing the buffer, the function returns
.codn nil .

.TP* Note:

The continuation function may be used any time after it is produced, and may be
called more than once, regardless of whether the originally captured dynamic
context is still executing. The underlying continuation stores a copy of the
captured dynamic context.  Whenever the continuation function is invoked, a
copy of the captured context is made again and reinstated as if it were a new
context.  Thus the apparent additional returns from
.code sys:capture-cont
are not actually made in the original context, but a copy. The copy of the
context is not complete; it only extends up to the enclosing block which was
named in the capturing call.

.TP* "Example:"

The following example shows an implementation of the
.meta suspend
operator.

.cblk
  (defmacro suspend (:form form name var . body)
    ^(sys:capture-cont ',name (lambda (,var)
                                (sys:abscond-from ,name ,*body))
                       ',form))
.cble

.coNP Operator @ sys:abscond-from
.synb
.mets (sys:abscond-from < name <> [ value ])
.syne
.desc
The
.code sys:abscond-from
operator closely resembles
.code return-from
and performs the same function: it causes an enclosing block
.meta name
to terminate with
.meta value
which defaults to
.codn nil .

However, unlike
.codn return-from ,
.code sys:abscond-from
does not perform any unwinding.

This operator should never be used for any purpose other than
implementing primitives for the use of delimited continuations.
It is used by the
.code yield-from
and
.code yield
operators to escape out of a block in which a continuation has
been captured. Neglecting to unwind is valid due to the expectation
that control will return into a restarted copy of that context.

.coNP Function @ sys:abscond*
.synb
.mets (sys:abscond* < name <> [ value ])
.syne
.desc
The
.code sys:abscond*
function is similar to the the
.code sys:abscond-from
operator, except that
.code name
is an ordinary function parameter, and so when
.code return*
is used, an argument expression must be specified which evaluates
to a symbol. Thus
.code sys:abscond*
allows the target block of a return to be dynamically computed.

The following equivalence holds between the operator and function:

.cblk
  (sys:abscond-from a b)  <-->  (sys:abscond* 'a b)
.cble

Expressions used as
.meta name
arguments to
.code abscond*
which do not simply quote a symbol have no equivalent in
.codn abscond-from .

.coNP Macros @ obtain and @ yield-from
.synb
.mets (obtain << forms *)
.mets (yield-from < name <> [ form ])
.syne
.desc
The
.code obtain
and
.code yield-from
macros closely inter-operate.

The
.code obtain
macro treats zero or more
.metn form -s
as a suspendable execution context called the
.IR "obtain block" .
It is expected that
.metn form -s
establish a block named
.meta name
and return its result value to
.codn obtain .

Without evaluating any of the forms in the obtain block,
.code obtain
returns a function, which takes one optional argument.
This argument, called the
.IR "resume value" ,
defaults to
.code nil
if it is omitted.

The function represents the suspended execution context.

The context is resumed whenever the function is called, and executes
until the next
.code yield-from
statement which references the block named
.metn name .
The function's reply argument is noted.

If the
.code yield-from
specifies a
.meta form
argument, then the execution context suspends, and the resume function
terminates and returns the value of that form. When the function is called
again to resume the context, the
.code yield-from
returns the previously noted resume value (and the new resume
value just passed is noted in its place).

If the
.code yield-from
specifies no
.meta form
argument, then it briefly suspends the execution context only
to retrieve the resume value, without producing an item. Since
no item is produced, the resume function does not return.
The execution context implicitly resumes.

When execution reaches the last form in the obtain block, the
resume value is discarded. The execution context terminates, and
the most recent call to the resume function returns the value of
that last form.

.TP* Notes:

The
.code obtain
macro registers a finalizer against the returned resume function.
The finalizer invokes the function, passing it the symbol
.codn sys:cont-poison ,
thereby triggering unwinding in the most recently captured
continuation. Thus, abandoned
.code obtain
blocks are subject to unwinding when they become garbage.

The
.code yield-from
macro works by capturing a continuation and performing a nonlocal
exit to the nearest block called
.metn name .
It passes a special yield object to that block. The
.code obtain
macro generates code which knows what to do with this special yield
object.

.TP* Examples:

The following example shows a function which recursively
traverses a
.code cons
cell structure, yielding all the
.cod2 non- nil
atoms it encounters. Finally, it returns the object
.codn nil .
The function is invoked on a list,
and the invocation is wrapped in an
.code obtain
block to convert it to a generating function.

The generating function is then called six times
to retrieve the five atoms from the list,
and the final
.code nil
value. These are collected into a list.

This example demonstrates the power of delimited
continuations to suspend and resume a recursive
procedure.

.cblk
  (defun yflatten (obj)
    (labels ((flatten-rec (obj)
               (cond
                 ((null obj))
                 ((atom obj) (yield-from yflatten obj))
                 (t (flatten-rec (car obj))
                    (flatten-rec (cdr obj))))))
      (flatten-rec obj)
      nil))

  (let ((f (obtain (yflatten '(a (b (c . d)) e)))))
    (list [f] [f] [f] [f] [f] [f]))
  --> (a b c d e nil)
.cble

The following interactive session log exemplifies two-way communication between
the main code and a suspending function.

Here,
.code mappend
is invoked on a list of symbols representing fruit and vegetable names.
The objective is to return a list containing only fruits.
The
.code lambda
function suspends execution and yields a question out of the
.code map
block. It then classifies
the item as a fruit or not according to the reply it receives. The reply
emerges as a the result value of the
.code yield-from
call.

The
.code obtain
macro converts the block to a generating function. The first call to the
function is made with no argument, because the argument would be ignored
anyway. The function returns a question, asking whether the first item
in the list, the potato, is a fruit.
To answer negatively, the user calls the function again, passing in
.codn nil .
The function returns the next question, which is answered in the
same manner.

When the question for the last item is answered, the function
call yields the final item: the ordinary result of the block, which is the list
of fruit names.

.cblk
  1> (obtain
       (block map
         (mappend (lambda (item)
                    (if (yield-from map `is @item a fruit?`)
                      (list item)))
                  '(potato apple banana lettuce orange carrot))))
  #<interpreted fun: lambda (: reply)>
  2> (call *1)
  "is potato a fruit?"
  3> (call *1 nil)
  "is apple a fruit?"
  4> (call *1 t)
  "is banana a fruit?"
  5> (call *1 t)
  "is lettuce a fruit?"
  6> (call *1 nil)
  "is orange a fruit?"
  7> (call *1 t)
  "is carrot a fruit?"
  8> (call *1 nil)
  (apple banana orange)
.cble

The following example demonstrates an accumulator. Values passed to the
resume function are added to a counter which is initially zero.
Each call to the function returns the updated value of the accumulator.
Note the use of
.code "(yield-from acc)"
with no arguments to receive the value passed to the first
call to the resume function, without yielding an item.
The very first return value
.code 1
is produced by the
.code "(yield-from acc sum)"
form, not by
.codn "(yield-from acc)" .
The latter only obtains the initial value
.code 1
and uses it to establish the seed value of the accumulator. Without causing
the resume function to terminate and return, control passes into the loop,
which yields the first item, causing the resume function call
.code "(call *1 1)"
to return
.codn 1 :

.cblk
  1> (obtain
       (block acc
         (let ((sum (yield-from acc)))
            (while t (inc sum (yield-from acc sum))))))
  #<interpreted fun: lambda (: resume-val)>
  2> (call *1 1)
  1
  3> (call *1 2)
  3
  4> (call *1 3)
  6
  5> (call *1 4)
  10
.cble

.coNP Macro @ obtain-block
.synb
.mets (obtain-block < name << forms *)
.syne
.desc
The
.code obtain-block
macro combines
.code block
and
.code obtain
into a single expression.
The
.metn form -s
are evaluated in a block named
.codn name .

That is to say, the following equivalence holds:

.cblk
  (obtain-block n f ...)  <-->  (obtain (block n f ...))
.cble

.coNP Macro @ yield
.synb
.mets (yield <> [ form ])
.syne
.desc
The
.code yield
macro is to
.code yield-from
as
.code return
is to
.codn return-from :
it yields from an anonymous block.

It is equivalent to calling
.code yield-from
using
.code nil
as the block name.

In other words, the following equivalence holds:

.cblk
  (yield x)  <-->  (yield-from nil x)
.cble

.TP* Example:

.cblk
  ;; Yield the integers 0 to 4 from a for loop, taking
  ;; advantage of its implicit anonymous block:

  (defvarl f (obtain (for ((i 0)) ((< i 5)) ((inc i))
                       (yield i))))

  [f] -> 0
  [f] -> 1
  [f] -> 2
  [f] -> 3
  [f] -> 4
  [f] -> nil
  [f] -> nil
.cble

.coNP Macros @ obtain* and @ obtain*-block
.synb
.mets (obtain* << forms *)
.mets (obtain*-block < name << forms *)
.syne
.desc
The
.code obtain*
and
.code obtain*-block
macros implement a useful variation of
.code obtain
and
.codn obtain-block .

The
.code obtain*
macro differs from
.code obtain
in exactly one regard: prior to returning the function, it invokes
it one time, with the argument value
.codn nil .

Thus, the following equivalence holds

.cblk
  (obtain* forms ...)   <-->  (let ((f (obtain forms ...)))
                                (call f)
                                f)
.cble

In other words, the suspended block is immediately resumed, so that it executes
either to completion (in which case its value is discarded), or to its first
.code yield
or
.code yield-from
call (in which case the yielded value is discarded).

Note: the
.code obtain*
macro is useful in creating suspensions which accept data rather than
produce data.

The
.code obtain*-block
macro combines
.code obtain*
and
.code block
in the same manner that
.code obtain-block
combines
.code obtain
and
.codn block .

.TP* Example:

.cblk
  ;; Pass three values into suspended block,
  ;; which get accumulated into list.
  (let ((f (obtain*-block nil
             (list (yield nil) (yield nil) (yield nil)))))
    (call f 1)
    (call f 2)
    (call f 3))  ->  (1 2 3)

  ;; Under obtain, extra call is required:
  (let ((f (obtain-block nil
             (list (yield nil) (yield nil) (yield nil)))))
    (call f nil)  ;; execute block to first yield
    (call f 1)    ;; resume first yield with 1
    (call f 2)
    (call f 3))  ->  (1 2 3)
.cble

.coNP Macro @ suspend
.synb
.mets (suspend < block-name < var-name << body-form *)
.syne
.desc
The
.code suspend
operator captures a continuation up to the prompt given by the
symbol
.meta block-name
and binds it to the variable name given by
.metn var-name ,
which must be a symbol suitable for binding variables with
.codn let .

Each
.meta body-form
is then evaluated in the scope of the variable
.metn var-name .

When the last
.meta body-form
is evaluated, a non-local exit takes place to the block
named by
.meta block-name
(using the
.code sys:abscond-from
operator, so that unwinding isn't performed).

When the continuation bound to
.meta var-name
is invoked, a copy of the entire block
.meta block-name
is re-started, and in that copy, the
.code suspend
call appears to return normally, yielding the value which had been
passed to the continuation.

.TP* Example

Define John McCarthy's
.code amb
function using
.code block
and
.codn suspend :

.cblk
  (defmacro amb-scope (. forms)
    ^(block amb-scope ,*forms))

  (defun amb (. args)
    (suspend amb-scope cont
      (each ((a args))
        (when (and a (call cont a))
          (return-from amb a)))))
.cble

Use
.code amb
to bind the of
.code x
and
.code y
which satisfy the predicate
.cblk
.meti (eql (* x y) 8)
.cble
non-deterministically:

.cblk
  (amb-scope
    (let ((x (amb 1 2 3))
          (y (amb 4 5 6)))
      (amb (eql (* x y) 8)
      (list x y))))
  -> (2 4)
.cble

.SS* Regular Expression Library
.coNP Functions @ search-regex and @ range-regex
.synb
.mets (search-regex < string < regex >> [ start <> [ from-end ]])
.mets (range-regex < string < regex >> [ start <> [ from-end ]])
.mets (search-regst < string < regex >> [ start <> [ from-end ]])
.syne
.desc
The
.code search-regex
function searches through
.meta string
starting
at position
.meta start
for a match for
.metn regex .
If
.meta start
is omitted, the search starts at position 0. If
.meta from-end
is specified and has a
.cod2 non- nil
value, the search
proceeds in reverse, from the last position in the string, toward
.metn start .
This function returns
.code nil
if no match is found, otherwise it returns
a cons, whose
.code car
indicates the position of the match, and whose
.code cdr
indicates the length of the match.

The
.code range-regex
function is similar to
.codn search-regex ,
except that when
a match is found, it returns a position range, rather than a position
and length. A range object is returned whose
.code from
field indicates the position
of the match, and whose
.code to
indicates the position one element past the
last character of the match. If the match is empty, the two integers
are equal.

The
.code search-regst
differs from
.code search-regex
in the representation of the return value in the matching case.
Rather than returning the position and length of the match,
it returns the matching substring of
.metn string .

.coNP Functions @ match-regex and @ match-regst
.synb
.mets (match-regex < string < regex <> [ position ])
.mets (match-regst < string < regex <> [ position ])
.syne
.desc
The
.code match-regex
function tests whether
.meta regex
matches at
.meta position
in
.metn string .
If
.meta position
is not specified, it is taken to be zero.
If the regex matches, then the length of the match is returned.
If it does not match, then
.code nil
is returned.

The
.code match-regst
differs from
.code match-regex
in the representation of the return value in the matching case.
Rather than returning the length of the match, it returns
matching substring of
.metn string .

.coNP Functions @ match-regex-right and @ match-regst-right
.synb
.mets (match-regex-right < string < regex <> [ end-position ])
.mets (match-regst-right < string < regex <> [ end-position ])
.syne
.desc
The
.code match-regex
function tests whether
.meta string
contains a match which ends
precisely on the character just before
.metn end-position .
If
.meta end-position
is not specified, it defaults to the length of the string, and the function
performs a right-anchored regex match.

If a match is found, then the length of the match is returned.

The match must terminate just before
.meta end-position
in the sense that
additional characters at
.meta end-position
and beyond can no longer satisfy the
regular expression. More formally, the function searches, starting from
position zero, for positions where there occurs a match for the regular
expression, taking the longest possible match. The length of first such a match
which terminates on the character just before
.meta end-position
is returned.
If no such a match is found, then
.code nil
is returned.

The
.code match-regst-right
differs from
.code match-regst-right
in the representation of the return value in the matching case.
Rather than returning the length of the match, it returns
matching substring of
.metn string .

.TP* Examples:

.cblk
  ;; Return matching portion rather than length thereof.

  (defun match-regex-right-substring (str reg : end-pos)
    (set end-pos (or end-pos (length str)))
    (let ((len (match-regex-right str reg end-pos)))
      (if len
        [str (- end-pos len)..end-pos]
        nil)))

  (match-regex-right-substring "abc" #/c/) -> ""

  (match-regex-right-substring "acc" #/c*/) -> "cc"

  ;; Regex matches starting at multiple positions, but all
  ;; the matches extend past the limit.
  (match-regex-right-substring "acc" #/c*/ 2) -> nil

  ;; If the above behavior is not wanted, then
  ;; we can extract the string up to the limiting
  ;; position and do the match on that.
  (match-regex-right-substring ["acc" 0..2] #/c*/) -> "c"

  ;; Equivalent of above call
  (match-regex-right-substring "ac" #/c*/) -> "c"
.cble

.coNP Function @ regsub
.synb
.mets (regsub < regex < replacement << string )
.syne
.desc
The
.code regsub
function searches
.meta
string
for multiple occurrences of
non-overlapping matches for
.metn regex .
A new string is constructed
similar to
.meta string
but in which each matching region is replaced
with using
.meta replacement
as follows.

The
.meta replacement
object may be a character or a string, in which
case it is simply taken to be the replacement for each match
of the regular expression.

The
.meta replacement
object may be a function of one argument, in
which case for every match which is found, this function is invoked,
with the matching piece of text as an argument. The function's
return value is then taken to be the replacement text.

.TP* Examples:

.cblk
  ;; match every lower case e or o, and replace by filtering
  ;; through the upcase-str function:

  [regsub #/[eo]/ upcase-str "Hello world!"] -> "HEllO wOrld!"

  ;; Replace Hello with Goodbye:
  (regsub #/Hello/ "Goodbye" "Hello world!") -> "Goodbye world!"
.cble

.coNP Function @ regexp
.synb
.mets (regexp << obj )
.syne
.desc
The
.code regexp
function returns
.code t
if
.meta obj
is a compiled regular expression
object. For any other object type, it returns
.codn nil .

.coNP Function @ regex-compile
.synb
.mets (regex-compile < form-or-string <> [ error-stream ])
.syne
.desc
The
.code regex-compile
function takes the source code of a regular expression,
expressed as a Lisp data structure representing an abstract syntax tree, or
else a regular expression specified as a character string, and compiles it to a
regular expression object.

If
.meta form-or-string
is a character string, it is parsed to an
abstract syntax tree first, if by the
.code regex-parse
function.
If the parse is successful (the result is not
.codn nil )
then
the resulting tree structure is compiled by a recursive call to
.codn regex-compile .

The optional
.meta error-stream
argument is passed down to
.code regex-parse
as well as in the recursive call to
.codn regex-compile ,
if that call takes place.

If
.meta error-stream
is specified, it must be a stream. Any error diagnostics are sent to that
stream.

.TP* Examples:

.cblk
  ;; the equivalent of #/[a-zA-Z0-9_/
  (regex-compile '(set (#\ea . #\ez) (#\eA . #\eZ)
                       (#\e0 . #\e9) #\e_))

  ;; the equivalent of #/.*/ and #/.+/
  (regex-compile '(0+ wild))
  (regex-compile '(1+ wild))

  ;; #/a|b|c/
  (regex-compile '(or (or #\ea #\eb) #\ec))

  ;; string
  (regex-compile "a|b|c")
.cble

.coNP Function @ regex-parse
.synb
.mets (regex-parse < string <> [ error-stream ])
.syne
.desc
The
.code regex-parse
function parses a character string which contains a regular expression and
turns it into a Lisp data structure (the abstract syntax tree representation of
the regular expression).

The regular expression syntax
.code #/RE/
produces the same structure, but as a
literal which is processed at the time \*(TX source code is read; the
.code regex-parse
function performs this parsing at run-time.

If there are parse errors, the function returns
.codn nil .

The optional
.meta error-stream
argument specifies a stream to which error messages
are sent from the parser. By default, diagnostic output goes to the
.code *stdnull*
stream, which discards it. If
.meta error-stream
is specified as
.codn t ,
then the diagnostic output goes to the
.code *stdout*
stream.

If
.code regex-parse
returns a
.cod2 non- nil
value, that structure is then something
which is suitable as input to
.codn regex-compile .

There is a small difference in the syntax accepted by
.code regex-parse
and the syntax of regular expression literals. Any
.code /
(slash) characters occurring in any position within
.meta string
are treated as ordinary characters, not as regular expression delimiters.
The call
.cblk
(regex-parse "/a/")
.cble
matches three characters: a slash, followed by the letter "a", followed
by another slash. Note that the slashes are not escaped.

Note: if a
.code regex-parse
call is written using a string literal as the
.meta string
argument, then note that any backslashes which are to be processed
by the regular expression must be doubled up, otherwise they belong
to the string literal:

.cblk
  (regex-parse "\e*")  ;; error, invalid string literal escape
  (regex-parse "\e\e*") ;; correct: the \e* literal match for *
.cble

The double backslash in the string literal produces a single backslash
in the resulting string object that is processed by
.codn regex-parse .

.coNP Function @ read-until-match
.synb
.mets (read-until-match < regex >> [ stream <> [ include-match ]])
.syne
.desc
The
.code read-until-match
function reads characters from
.metn stream ,
accumulating them into a string, which is returned.

If an argument is not specified for
.metn stream ,
then the
.code *std-input*
stream is used.

The
.meta include-match
argument is Boolean, indicating whether the delimiting text
matched by
.meta regex
is included in the returned string. It defaults to
.codn nil .

The accumulation of characters is terminated by a match on
.metn regex ,
the end of the stream, or an error.

This means that characters are read from the stream and accumulated while the
stream has more characters available, and while its prefix does not match
.metn regex .

If
.meta regex
matches the stream before any characters are accumulated,
then an empty string is returned.

If the stream ends or an error occurs before any characters
are accumulated, the function returns
.codn nil .

When the accumulation of characters terminates by a match on
.metn regex ,
the longest possible matching sequence of characters is
removed from the stream.  If
.meta include-match
is true, that matching text is included in
the returned string. Otherwise, it is discarded.

.SS* Hashing Library
.coNP Functions @ make-hash and @ hash
.synb
.mets (make-hash < weak-keys < weak-vals << equal-based )
.mets (hash { :weak-keys | :weak-vals | :equal-based }*)
.syne
.desc
These functions construct a new hash table.

A hash table is an object which retains an association between pairs of
objects. Each pair consists of a key and value. Given an object which is
similar to a key in the hash table, it is possible to retrieve the
corresponding value. Entries in a hash table are not ordered in any way, and
lookup is facilitated by hashing: quickly mapping a key object to a numeric
value which is then used to index into one of many buckets where the matching
key will be found (if such a key is present in the hash table).

.code make-hash
takes three mandatory Boolean arguments. The
.meta weak-keys
argument specifies whether the hash table shall have weak keys. The
.meta weak-vals
argument specifies whether it shall have weak values, and
.meta equal-based
specifies whether it is
.codn equal -based.
The hash function defaults
all three of these properties to false, and allows them to be overridden to
true by the presence of keyword arguments.

It is an error to attempt to construct an
.codn equal -based
hash table which has weak keys.

The hash function provides an alternative interface. It accepts optional
arguments which are keyword symbols. Any combination of the three symbols
.codn :weak-keys ,
.code :weak-vals
and
.code :equal-based
can be specified in any order
to turn on the corresponding properties in the newly constructed hash table.
If any of the keywords is not specified, the corresponding property defaults to
.codn nil .

If a hash table has weak keys, this means that from the point of view
of garbage collection, that table holds only weak references to the keys
stored in it.  Similarly, if a hash table has weak values, it means that it
holds a weak reference to each value stored. A weak reference is one
which does not prevent the reclamation of an object by the garbage
collector. That is to say, when the garbage collector discovers that the only
references to some object are weak references, then that object is considered
garbage, just as if it had no references to it. The object is reclaimed, and
the weak references "lapse" in some way, which depends on what kind they are.
Hash table weak references lapse by entry removal: if either a key or a value
object is reclaimed, then the corresponding key-value entry is erased from the
hash table.

Important to the operation of a hash table is the criterion by which keys are
considered same. By default, this similarity follows the eql function.  A hash
table will search for a stored key which is
.code eql
to the given search key.
A hash table constructed with the
.codn equal -based
property compares keys using
the
.code equal
function instead.

In addition to storing key-value pairs, a hash table can have a piece of
information associated with it, called the user data.

A hash table can be traversed to visit all of the keys and data.  The order of
traversal bears no relation to the order of insertion, or to any properties of
the key type.

During an open traversal, new keys can be inserted into a hash table or deleted
from it while a a traversal is in progress. Insertion of a new key during
traversal will not cause any existing key to be visited twice or to be skipped;
however, it is not specified whether the new key will be traversed. Similarly,
if a key is deleted during traversal, and that key has not yet been visited, it
is not specified whether it will be visited during the remainder of the
traversal.

An open traversal of a hash table is performed by the
.code maphash
function and the
.code dohash
operator. The traversal is open because code supplied by the program
is evaluated for each entry.

The functions
.codn hash-keys ,
.codn hash-values ,
.codn hash-pairs ,
and
.code hash-alist
also perform an open traversal, because they return
lazy lists. The traversal isn't complete until the returned lazy list
is fully instantiated. In the meanwhile, the
\*(TX program can mutate the hash table from which the lazy list
is being generated.

.coNP Functions @ hash-construct and @ hash-from-pairs
.synb
.mets (hash-construct < hash-args << key-val-pairs )
.mets (hash-from-pairs < key-val-pairs << hash-arg *)
.syne
.desc
The
.code hash-construct
function constructs a populated hash in one step. The
.meta hash-args
argument specifies a list suitable as an argument list in a call to the hash
function.  The
.meta key-val-pairs
is a sequence of pairs, which are two-element
lists representing key-value pairs.

A hash is constructed as if by a call to
.cblk
.meti (apply hash << hash-args ),
.cble
then populated
with the specified pairs, and returned.

The
.code hash-from-pairs
function is an alternative interface to the same semantics. The
.meta key-val-pairs
argument is first, and the
.meta hash-args
are passed as trailing variadic arguments, rather than a single list argument.

.coNP Function @ hash-list
.synb
.mets (hash-list < key-list << hash-arg *)
.syne
.desc
The
.code hash-list
function constructs a hash as if by a call to
.cblk
.meti (apply hash << hash-args ),
.cble
where
.meta hash-args
is a list of the individual
.meta hash-arg
variadic arguments.

The hash is then populated with keys taken from
.meta key-list
and returned.

The value associated with each key is that key itself.

.coNP Function @ hash-update
.synb
.mets (hash-update < hash << function )
.syne
.desc
The
.code hash-update
function replaces each values in
.metn hash ,
with the value of
.meta function
applied to that value.

The return value is
.metn hash .

.coNP Function @ hash-update-1
.synb
.mets (hash-update-1 < hash < key < function <> [ init ])
.syne
.desc
The
.code hash-update-1
function operates on a single entry in the hash table.

If
.meta key
exists in the hash table, then its corresponding value is passed
into
.metn function ,
and the return value of
.meta function
is then installed
in place of the key's value. The value is then returned.

If
.meta key
does not exist in the hash table, and no
.meta init
argument is given,
then
.code hash-update-1
does nothing and returns
.codn nil .

If
.meta key
does not exist in the hash table, and an
.meta init
argument is given,
then
.meta function
is applied to
.metn init ,
and then
.meta key
is inserted into
.meta hash
with the value returned by
.meta function
as the datum. This value
is also returned.

.coNP Function @ group-by
.synb
.mets (group-by < func < sequence << option *)
.syne
.desc
The
.code group-by
function produces a hash table from
.metn sequence ,
which is a
list or vector. Entries of the hash table are not elements of
.metn sequence ,
but lists of elements of
.metn sequence .
The function
.meta func
is applied to
each element of
.meta sequence
to compute a key. That key is used to determine
which list the item is added to in the hash table.

The trailing arguments
.cblk
.meti << option *
.cble
if any, consist of the same keywords
that are understood by the hash function, and determine the properties
of the hash.

.TP* Example:
Group the integers from 0 to 10 into three buckets keyed on 0, 1 and 2
according to the modulo 3 congruence:

.cblk
  (group-by (op mod @1 3) (range 0 10)))

  -> #H(() (0 (0 3 6 9)) (1 (1 4 7 10)) (2 (2 5 8)))
.cble

.coNP Function @ group-reduce
.synb
.mets (group-reduce < hash < classify-fun < binary-fun < seq
.mets \ \  >> [ init-value <> [ filter-fun ]])
.syne
.desc
The
.code group-reduce
updates hash table
.meta hash
by grouping and reducing sequence
.metn seq .

The function regards the hash table as being populated with
keys denoting accumulator values. Missing accumulators which
need to be created in the hash table are initialized with
.meta init-value
which defaults to
.codn nil .

The function iterates over
.meta seq
and treats each element according to the following steps:
.RS
.IP 1.
Each element is mapped to a hash key through
.metn classify-fun .
.IP 2.
The value associated with the hash key (the accumulator for that
key) is retrieved. If it doesn't exist,
.meta init-value
is used.
.IP 3.
The function
.meta binary-fun
is invoked with two arguments: the accumulator from step 2, and the
original element from
.metn seq .
.IP 4.
The resulting value is stored back into the hash table under the
same key.
.RE

.IP
If
.code group-reduce
is invoked on an empty hash table, its net result closely resembles a
.code group-by
operation followed by separately performing a
.code reduce-left
on each value in the hash.

.TP* Examples:

Frequency histogram:

.cblk
  [group-reduce (hash) identity (do inc @1)
    "fourscoreandsevenyearsago" 0]
  --> #H(() (#\ea 3) (#\ec 1) (#\ed 1) (#\ee 4) (#\ef 1)
        (#\eg 1) (#\en 2) (#\eo 3) (#\er 3) (#\es 3)
        (#\eu 1) (#\ev 1) (#\ey 1))
.cble

Separate the integers 1-10 into even and odd, and sum these groups:

.cblk
  [group-reduce (hash) evenp + (range 1 10) 0]
  -> #H(() (t 30) (nil 25))
.cble

.coNP Functions @ make-similar-hash and @ copy-hash
.synb
.mets (make-similar-hash << hash )
.mets (copy-hash << hash )
.syne
.desc
The
.code make-similar-hash
and copy-hash functions create a new hash object based on
the existing
.meta hash
object.

.code make-similar-hash
produces an empty hash table which inherits all of the
attributes of
.metn hash .
It uses the same kind of key equality, the
same configuration of weak keys and values, and has the same user data (see
the
.code set-hash-userdata
function).

The
.code copy-hash
function is like
.codn make-similar-hash ,
except that instead of
producing an empty hash table, it produces one which has all the same elements
as
.metn hash :
it contains the same key and value objects.

.coNP Function @ inhash
.synb
.mets (inhash < hash < key <> [ init ])
.syne
.desc
The
.code inhash
function searches hash table
.meta hash
for
.metn key .
If
.meta key
is found, then it return the hash table's cons cell which
represents the association between
.meta hash
and
.metn key .
Otherwise, it returns
.codn nil .

If argument
.meta init
is specified, then the function will create
an entry for
.meta key
in
.meta hash
whose value is that of
.metn init .
The cons cell representing that association is returned.

Note: for as long as the
.meta key
continues to exist inside
.metn hash .
modifying the
.code car
field of the returned cons has ramifications for the logical integrity of
the hash. Modifying the
.code cdr
field has the effect of updating the association with a new value.

.coNP Accessor @ gethash
.synb
.mets (gethash < hash < key <> [ alt ])
.mets (set (gethash < hash < key <> [ alt ]) << new-value )
.syne
.desc
The
.code gethash
function searches hash table
.meta hash
for key
.metn key .
If the
key is found then the associated value is returned. Otherwise, if
the
.meta alt
argument was specified, it is returned. If the
.meta alt
argument
was not specified,
.code nil
is returned.

A valid
.code gethash
form serves as a place. It denotes either an existing value in a hash
table or a value that would be created by the evaluation of the form.
The
.meta alt
argument is meaningful when
.code gethash
is used as a place, and, if present, is always evaluated whenever the place is
evaluated.
In place update operations, it provides the initial value, which defaults
to
.code nil
if the argument is not specified. For example
.code "(inc (gethash h k d))"
will increment the value stored under key
.code k
in hash table
.code h
by one. If the key does not exist in the hash table, then
the value
.code "(+ 1 d)"
is inserted into the table under that key.
The expression
.code d
is always evaluated, whether or not its value is needed.

If a
.code gethash
place is subject to a deletion, but doesn't exist, it is not an error.
The operation does nothing, and
.code nil
is considered the prior value of the place yielded
by the deletion.

.coNP Function @ sethash
.synb
.mets (sethash < hash < key << value )
.syne
.desc
The
.code sethash
function places a value into
.meta hash
table under the given
.metn key .
If a similar key already exists in the hash table, then that key's
value is replaced by
.metn value .
Otherwise, the
.meta key
and
.meta value
pair is
newly inserted into
.metn hash .

The
.code sethash
function returns the
.meta value
argument.

.coNP Function @ pushhash
.synb
.mets (pushhash < hash < key << element )
.syne
.desc
The
.code pushhash
function is useful when the values stored in a hash table
are lists.  If the given
.meta key
does not already exist in
.metn hash ,
then a list of
length one is made which contains
.metn element ,
and stored in
.meta hash
table under
.metn key .
If the
.meta key
already exists in the hash table, then the corresponding
value must be a list. The
.meta element
value is added to the front of that list,
and the extended list then becomes the new value under
.metn key .

The return value is Boolean. If true, indicates that the hash table entry was
newly created. If false, it indicates that the push took place on an existing
entry.

.coNP Function @ remhash
.synb
.mets (remhash < hash << key )
.syne
.desc
The
.code remhash
function searches
.meta hash
for a key similar to the
.metn key .
If that key is found, then that key and its corresponding value are
removed from the hash table.

If the key is found and removal takes place, then the associated value
is returned. Otherwise
.code nil
is returned.

.coNP Function @ hash-count
.synb
.mets (hash-count << hash )
.syne
.desc
The
.code hash-count
function returns an integer representing the number of
key-value pairs stored in
.metn hash .

.coNP Function @ get-hash-userdata
.synb
.mets (get-hash-userdata << hash )
.syne
.desc
This function retrieves the user data object associated with
.metn hash .
The user data object of a newly-created hash table is initialized to
.codn nil .

.coNP Function @ set-hash-userdata
.synb
.mets (set-hash-userdata < hash << object )
.syne
.desc
The
.code set-hash-userdata
replaces, with the
.metn object ,
the user data object
associated with
.metn hash .

.coNP Function @ hashp
.synb
.mets (hashp << object )
.syne
.desc
The
.code hashp
function returns
.code t
if the
.meta object
is a hash table,
otherwise it returns
.codn nil .

.coNP Function @ maphash
.synb
.mets (maphash < hash << binary-function )
.syne
.desc
The
.code maphash
function successively invokes
.meta binary-function
for each entry stored in
.metn hash .
Each entry's key and value are passed as arguments
to
.codn binary-function .

The function returns
.codn nil .

.coNP Function @ hash-revget
.synb
.mets (hash-revget < hash < value >> [ testfun <> [ keyfun ]])
.syne
.desc
The
.code hash-revget
function performs a reverse lookup on
.metn hash .

It searches through the entries stored in
.meta hash
for an entry whose value matches
.metn value .

If such an entry is found, that entry's key is returned.
Otherwise
.code nil
is returned.

If multiple matching entries exist, it is not specified which entry's
key is returned.

The
.meta keyfun
function is applied to each value in
.meta hash
and the resulting value is compared with
.metn value .
The default
.meta keyfun
is the
.code identity
function.

The comparison is performed using
.metn testfun .

The default
.meta testfun
is the
.code eql
function.

.coNP Functions @ hash-eql and @ hash-equal
.synb
.mets (hash-eql << object )
.mets (hash-equal << object )
.syne
.desc
These functions each compute an integer hash value from the internal
representation of
.metn object ,
which satisfies the following properties.
If two objects
.code A
and
.code B
are the same under the
.code eql
function, then
.code "(hash-eql A)"
and
.code "(hash-eql B)"
produce the same integer hash value.  Similarly,
if two objects
.code A
and
.code B
are the same under the
.code equal
function, then
.code "(hash-equal A)"
and
.code "(hash-equal B)"
each produce the same integer hash value.  In all other
circumstances, the hash values of two distinct objects are unrelated, and
may or may not be the same.

Object of struct type may support custom hashing by way of defining
an equality substitution via an
.code equal
method. See the Equality Substitution section under Structures.

.coNP Functions @, hash_keys @, hash_values @ hash_pairs and @ hash_alist
.synb
.mets (hash-keys << hash )
.mets (hash-values << hash )
.mets (hash-pairs << hash )
.mets (hash-alist << hash )
.syne
.desc
These functions retrieve the bulk key-value data of hash table
.meta hash
in various ways.
.code hash-keys
retrieves a list of the keys.
.code hash-values
retrieves a list of the values.
.code hash-pairs
retrieves a list of pairs,
which are two-element lists consisting of the key, followed by the value.
Finally,
.code hash-alist
retrieves the key-value pairs as a Lisp association list:
a list of cons cells whose
.code car
fields are keys, and whose
.code cdr
fields are the values. Note that
.code hash-alist
returns the actual entries from the hash table, which are
conses. Modifying the
.code cdr
fields of these conses constitutes modifying the hash values
in the original hash table. Modifying the
.code car
fields interferes with the integrity of the hash table.

These functions all retrieve the keys and values in the
same order. For example, if the keys are retrieved with
.codn hash-keys ,
and the values with
.codn hash-values ,
then the corresponding entries from
each list pairwise correspond to the pairs in
.metn hash .

The list returned by each of these functions is lazy, and hence constitutes
an open traversal of the hash table.

.coNP Operator @ dohash
.synb
.mets (dohash >> ( key-var < value-var < hash-form <> [ result-form ])
.mets \ \  << body-form *)
.syne
.desc
The
.code dohash
operator iterates over a hash table. The
.meta hash-form
expression must
evaluate to an object of hash table type. The
.meta key-var
and
.meta value-var
arguments must be symbols suitable for use as variable names.
Bindings are established for these variables over the scope of the
.metn body-form -s
and the optional
.metn result-form .

For each element in the hash table, the
.meta key-var
and
.meta value-var
variables are set to the key and value of that entry, respectively,
and each
.metn body-form ,
if there are any, is evaluated.

When all of the entries of the table are thus processed, the
.meta result-form
is evaluated, and its return value becomes the return value of the dohash form.
If there is no
.metn result-form ,
the return value is
.codn nil .

The
.meta result-form
and
.metn body-form -s
are in the scope of an implicit anonymous
block, which means that it is possible to terminate the execution of
dohash early using
.cblk
.meti (return << value )
.cble
or
.codn (return) .

.coNP Functions @, hash-uni @ hash-diff and @ hash-isec
.synb
.mets (hash-uni < hash1 < hash2 <> [ join-func ])
.mets (hash-diff < hash1 << hash2 )
.mets (hash-isec < hash1 < hash2 <> [ join-func ])
.syne
.desc
These functions perform basic set operations on hash tables in a nondestructive
way, returning a new hash table without altering the inputs. The arguments
.meta hash1
and
.meta hash2
must be compatible hash tables.  This means that their keys
must use the same kind of equality.

The resulting hash table inherits attributes from
.metn hash1 ,
as if created by the
.code make-similar-hash
function. If
.meta hash1
has userdata, the resulting hash table
has the same userdata. If
.meta hash1
has weak keys, the resulting table has weak
keys, and so forth.

The
.code hash-uni
function performs a set union. The resulting hash contains all of
the keys from
.meta hash1
and all of the keys from
.metn hash2 ,
and their corresponding
values.  If a key occurs both in
.meta hash1
and
.metn hash2 ,
then it occurs only once
in the resulting hash. In this case, if the
.meta join-func
argument is not given,
the value associated with this key is the one from
.metn hash1 .
If
.meta join-func
is specified then it is called with two arguments: the respective
data items from
.meta hash1
and
.metn hash2 .
The return value of this function is used
as the value in the union hash.

The
.code hash-diff
function performs a set difference. First, a copy of
.meta hash1
is made as if by the
.code copy-hash
function. Then from this copy, all keys which occur
in
.code hash2
are deleted.

The
.code hash-isec
function performs a set intersection. The resulting hash contains
only those keys which occur both in
.meta hash1
and
.metn hash2 .
If
.meta join-func
is not
specified, the values selected for these common keys are those from
.metn hash1 .
If
.meta join-func
is specified, then for each key which occurs in both
.meta hash1
and
.metn hash2 ,
it is called with two arguments: the respective data items. The return
value is then used as the data item in the intersection hash.

.coNP Functions @ hash-subset and @ hash-proper-subset
.synb
.mets (hash-subset < hash1 << hash2 )
.mets (hash-proper-subset < hash1 << hash2 )
.syne
.desc
The
.code hash-subset
function returns
.code t
if the keys in
.meta hash1
are a subset of the keys in
.metn hash2 .

The
.code hash-proper-subset
function returns
.code t
if the keys in
.meta hash1
are a proper subset of the keys in
.metn hash2 .
This means that
.meta hash2
has all the keys which are in
.meta hash1
and at least one which isn't.

Note: the return value may not be mathematically meaningful if
.meta hash1
and
.meta hash2
use different equality. In any case, the actual behavior
may be understood as follows. The implementation of
.code hash-subset
tests whether each of the keys in
.meta hash1
occurs in
.meta hash2
using their respective equalities.
The implementation of
.code hash-proper-subset
applies
.code hash-subset
first, as above. If that is true, and the two hashes have the same number of
elements, the result is falsified.

.coNP Function @ hash-begin and @ hash-next
.synb
.mets (hash-begin << hash )
.mets (hash-next << hash-iter )
.syne
The
.code hash-begin
function returns a an iterator object capable of retrieving the
entries in stored in
.meta hash
one by one.

The
.code hash-next
function applies to a hash iterator returned by
.codn hash-begin .

If unvisited entries remain, it returns the next one as a cons cell
whose
.code car
holds the key and whose
.code cdr
holds the value.

If no more entries remain to be visited, it returns
.codn nil .

.coNP Macro @ with-hash-iter
.synb
.mets (with-hash-iter >> ( isym < hash-form >> [ ksym <> [ vsym ]])
.mets \ \  << body-form *)
.syne
.desc
The
.code with-hash-iter
macro evaluates
.metn body-form -s
in an environment in which a lexically scoped function is visible.

The function is named by
.meta isym
which must be a symbol suitable for naming functions with
.codn flet .

The
.meta hash-form
argument must be a form which evaluates to a hash table object.

Invocations of the function retrieve successive entries of the hash table
as cons cell pairs of keys and values. The function returns
.code nil
to indicate no more entries remain.

If either of the
.meta ksym
or
.meta vsym
arguments are present, they must be symbols suitable as variable names. They
are bound as variables visible to
.metn body-form -s,
initialized to the value
.codn nil .

If
.meta ksym
is specified, then whenever the function
.meta isym
macro is invoked and retrieves a hash table entry, the
.meta ksym
variable is set to the key. If the function returns
.code nil
then the value of
.meta ksym
is set to
.codn nil .

Similarly, if
.meta vsym
is specified, then the function stores the retrieved
hash value in that variable, or else sets the variable
to
.code nil
if there is no next value.

.SS* Partial Evaluation and Combinators
.coNP Macros @ op and @ do
.synb
.mets (op << form +)
.mets (do << form +)
.syne
.desc
The
.code op
and
.code do
macro operators are similar.

Like the lambda operator, the
.code op
operator creates an anonymous function based on its syntax.
The difference is that the arguments of the function are implicit, or
optionally specified within the function body, rather than as a formal
parameter list before the body.

Also, the
.meta form
arguments of
.code op
are implicitly turned into a DWIM expression,
which means that argument evaluation follows Lisp-1 rules.  (See the
.code dwim
operator).

The
.code do
operator is like the
.code op
operator with the following difference:
the
.meta form
arguments of
.code op
are not implicitly treated as a DWIM expression,
but as an ordinary expression. In particular, this means that operator
syntax is permitted. Note that the syntax
.code "(op @1)"
makes sense, since
the argument can be a function, which will be invoked, but
.code "(do @1)"
doesn't
make sense because it will produce a Lisp-2 form like
.code "(#:arg1 ...)"
referring
to nonexistent function
.codn #:arg1 .
Because it accepts operators,
.code do
can be used with imperative constructs
which are not functions, like set: like set: for instance
.code "(do set x)"
produces
an anonymous function which, if called with one argument, stores that argument
into
.codn x .

The argument forms are arbitrary expressions, within which a special
convention is permitted:
.RS
.meIP >> @ num
A number preceded by a
.code @
is a metanumber. This is a special syntax
which denotes an argument. For instance
.code @2
means that the second argument of
the anonymous function is to be substituted in place of the
.codn @2 .
.code op
generates a function which has a number of required arguments equal to the
highest value of
.meta num
appearing in a
.cblk
.meti >> @ num
.cble
construct in the body. For instance
.code "(op car @3)"
generates a three-argument function (which passes its third
argument to
.codn car ,
returning the result, and ignores its first two arguments).
There is no way to use
.code op
to generate functions which have optional arguments.
.meIP < @rest
If the meta-symbol
.meta @rest
appears in the
.code op
syntax, it explicitly denotes the list of trailing arguments,
allowing them to be placed anywhere in the expression.
.RE

.IP
Functions generated by
.code op
are always variadic; they always take additional arguments after
any required ones, whether or not the
.meta @rest
syntax is used.

If the body does not contain
any
.meta @num
or
.meta @rest
syntax, then
.code @rest
is implicitly inserted.  What this means is that, for example, since
the form
.code "(op foo)"
does not contain any numeric positional arguments like
.codn @1 ,
and does not contain
.codn @rest ,
it is actually a shorthand for
.codn "(op foo . @rest)" :
a function which applies all of its arguments to
.codn foo .
If the body does contain at least one
.meta @num
or
.metn @rest ,
then
.meta @rest
isn't implicitly inserted. The notation
.code "(op foo @1)"
denotes a function which takes any number of arguments, and ignores
all but the first one, which is passed to
.codn foo .

The actions of
.code op
be understood by these examples, which show
how
.code op
is rewritten to lambda.  However, note that the real translator
uses generated symbols for the arguments, which are not equal to any
symbols in the program.

.cblk
  (op) -> invalid

  (op +) -> (lambda rest [+ . rest])

  (op + foo) -> (lambda rest [+ foo . rest])

  (op @1 @2) -> (lambda (arg1 arg2 . rest) [arg1 arg2])

  (op @1 . @rest) -> (lambda (arg1 . rest) [arg1 . @rest])

  (op @1 @rest) -> (lambda (arg1 . rest) [arg1 @rest])

  (op @1 @2) -> (lambda (arg1 arg2 . rest) [arg1 arg2])

  (op foo @1 (@2) (bar @3)) -> (lambda (arg1 arg2 arg3 . rest)
                                  [foo arg1 (arg2) (bar arg3)])

  (op foo @rest @1) -> (lambda (arg1 . rest) [foo rest arg1])

  (do + foo) -> (lambda rest (+ foo . rest))

  (do @1 @2) -> (lambda (arg1 arg2 . rest) (arg1 arg2))

  (do foo @rest @1) -> (lambda (arg1 . rest) (foo rest arg1))
.cble

Note that if argument
.meta @n
appears, it is not necessary
for arguments
.meta @1
through
.meta @n-1
to appear. The function will have
.code n
arguments:

.cblk
  (op @3) -> (lambda (arg1 arg2 arg3 . rest) [arg3])
.cble

The
.code op
and
.code do
operators can be nested, in any combination. This raises the
question: if a metanumber like
.code @1
or
.code @rest
occurs in an
.code op
that is nested
within an
.codn op ,
what is the meaning?

A metanumber always belongs with the inner-most op or do operator. So for
instance
.code "(op (op @1))"
means that an
.code "(op @1)"
expression is nested
within an
.code op
expression which itself contains no meta-syntax.
The
.code @1
belongs with the inner op.

There is a way for an inner
.code op
to refer to an outer op metanumber argument. This is
expressed by adding an extra
.code @
prefix for every level of escape. For example in
.code "(op (op @@1))"
the
.code @@1
belongs to the outer
.codn op :
it is the same as
.code @1
appearing in the outer
.codn op .
That is to say,
in the expression
.codn "(op @1 (op @@1))" ,
the
.code @1
and
.code @@1
are the same thing:
both are parameter 1 of the lambda function generated by the outer
.codn op .
By contrast, in the expression
.code "(op @1 (op @1))"
there are two different parameters:
the first
.code @1
is argument of the outer function, and the second
.code @1
is the first argument of the inner function. Of course, if there
are three levels of nesting, then three
.code @
meta-prefixes are needed to insert
a parameter from the outermost
.code op
into the innermost
.codn op .

Note that meta-numbers and meta-symbols belonging to an
.code op
can be used in the dot position of a function call, such as:

.cblk
  [(op list 1 . @1) 2] -> (1 . 2)
.cble

Even though the notation
.code @1
produces a compound form, which the dot notation then splices into
the surrounding form, the expander for the
.code op
and
.code do
macro takes recognizes and takes care of this special case.

The
.code op
syntax interacts with quasiliterals which are nested within it.
The metanumber notation as well as
.code @rest
are recognized without requiring an additional
.code @
escape:

.cblk
  (apply (op list `@1-@rest`) '(1 2 3)) -> "1-2 3"

  (apply (op list `@@1-@@rest`) '(1 2 3)) -> "1-2 3"
.cble

This is because the
.code op
macro traverses the code structure produced by the literal without recognizing
it specially, and there imposes its own meaning on these elements.

Though they produce the same result, the above two examples differ in that
.code @rest
embeds a metasymbol into the quasiliteral structure, whereas
.code @@rest
embeds the Lisp expression
.code @rest
into the quasiliteral. In ordinary circumstances, the former refers to the
variable
.codn rest .
Contrast the previous example with:

.cblk
  (let ((rest "0"))
    `rest: @rest`) -> "rest: 0"

  (let ((rest "0"))
    `rest: @@rest`) -> ;; error: no such function or operator: sys:var
.cble

Under the
.code op
macro and its relatives, occurrences of
.code @rest
are replaced with syntax which refers to the trailing arguments
of the anonymous function. This happens before the interior of the
.code op
syntax undergoes expansion. Therefore the quasiliteral expander never
sees the
.codn @rest .

This convenient omission of the
.code @
character isn't supported for reaching the arguments of an outer
.code op
from a quasiliteral within a nested
.codn op :

.cblk
  ;; To reach @@1, @@@1 must be written.
  ;; @@1 Lisp expression introduced by @.
  (op ... (op ... `@@@1`))
.cble

.TP* Example:

.cblk
  ;; Take a list of pairs and produce a list in which those pairs
  ;; are reversed.

  (mapcar (op list @2 @1) '((1 2) (a b)))   ->   ((2 1) (b a))
.cble

.coNP Macros @, ap @, ip @ ado and @ ido.
.synb
.mets (ap << form +)
.mets (ip << form +)
.mets (ado << form +)
.mets (ido << form +)
.syne
.desc
The
.code ap
macro is based on the
.code op
macro and has identical argument
conventions.

The
.code ap
macro analyzes its arguments and produces a function
.metn f ,
in exactly the same same way as the
.code op
macro.  However, instead of returning
.metn f ,
directly, it returns a different function
.metn g ,
which is a one-argument function  which accepts a list,
and then applies the list as arguments to
.metn f .

In other words, the following equivalence holds:

.cblk
  (ap form ...) <--> (apf (op form ...))
.cble

The
.code ap
macro nests properly with
.code op
and
.codn do ,
in any combination, in regard to the
.meta ...@@n
notation.

The
.code ip
macro is very similar to the
.code ap
macro, except that it is based
on the semantics of the function
.code iapply
rather than
.codn apply ,
according
to the following equivalence:

.cblk
  (ip form ...) <--> (ipf (op form ...))
.cble

The
.code ado
and
.code ido
macros are related to do macro in the same way that
.code ap
and
.code ip
are related to
.codn op .
They produce a one-argument function which works
as if by applying its arguments to the function generated by do,
according to the following equivalence:

.cblk
  (ado form ...) <--> (apf (do form ...))

  (ido form ...) <--> (ipf (do form ...))
.cble

See also: the
.code apf
and
.code ipf
functions.

.coNP Macros @ opip and @ oand
.synb
.mets (opip << clause *)
.mets (oand << clause *)
.syne
.desc
The
.code opip
and
.code oand
operators make it possible to chain together functions which are expressed
using the
.code op
syntax. (See the
.code op
operator for more information).

Both macros perform the same transformation except that
.code opip
translates its arguments to a call to the
.code chain
function, whereas
.code oand
translates its arguments in the same way to a call to the
.code chand
function.

More precisely, these macros perform the following rewrites:

.cblk
  (opip arg1 arg2 ... argn) -> [chain {arg1} {arg2} ... {argn}]
  (oand arg1 arg2 ... argn) -> [chand {arg1} {arg2} ... {argn}]
.cble

where the above
.code {arg}
notation denotes the following transformation applied to each argument:

.cblk
  (function ...) -> (op function ...)
  (operator ...) -> (do operator ...)
  (macro ...)    -> (do macro ...)
  (dwim ...)     -> (dwim ...)
  [...]          -> [...]
  atom           -> atom
.cble

In other words, compound forms whose leftmost symbol is a macro or operator
are translated to the
.code do
notation. Compound forms denoting function calls are translated to the
.code op
notation. Compound forms which are
.code dwim
invocations, either explicit or via the DWIM brackets notation, are
preserved, as are any forms which are atoms.

Note: the
.code opip
and
.code oand
macros use their macro environment in determining whether a form is a
macro call, thereby respecting lexical scoping.

.TP* Example:
Take each element from the list
.code "(1 2 3 4)"
and multiply it by three, then add 1.
If the result is odd, collect that into the resulting list:

.cblk
(mappend (opip (* 3)
               (+ 1)
               [iff oddp list])
         (range 1 4))
.cble

The above is equivalent to:

.cblk
(mappend (chain (op * 3)
                (op + 1)
                [iff oddp list])
         (range 1 4))
.cble

The
.code "(* 3)"
and
.code "(+ 1)"
terms are rewritten to
.code "(op * 3)"
and
.codn "(op + 1)" ,
respectively, whereas
.code "[iff oddp list]"
is passed through untransformed.

.coNP Macro @ ret
.synb
.mets (ret << form )
.syne
.desc
The
.code ret
macro's
.meta form
argument is treated similarly to the second and subsequent arguments of the
.code op
operator.

The
.code ret
macro produces a function which takes any number of arguments,
and returns the value specified by
.metn form .

.meta form
can contain
.code op
meta syntax like
.code @n
and
.codn @rest .

The following equivalence holds:

.cblk
  (ret x) <--> (op identity x))
.cble

Thus the expression
.code "(ret @2)"
returns a function similar to
.codn "(lambda (x y . z) y)" ,
and the expression
.code "(ret 42)"
returns a function similar to
.codn "(lambda (. rest) 42)" .

.coNP Macro @ aret
.synb
.mets (aret << form )
.syne
.desc
The
.code ret
macro's
.meta form
argument is treated similarly to the second and subsequent arguments of the
.code op
operator.

The
.code aret
macro produces a function which takes any number of arguments,
and returns the value specified by
.metn form .

.meta form
can contain
.code ap
meta syntax like
.meta @n
and
.codn @rest .

The following equivalence holds:

.cblk
  (aret x) <--> (ap identity x))
.cble

Thus the expression
.code "(aret @2)"
returns a function similar to
.codn "(lambda (. rest) (second rest))" ,
and the expression
.code "(aret 42)"
returns a function similar to
.codn "(lambda (. rest) 42)" .

.coNP Function @ dup
.synb
.mets (dup << func )
.syne
.desc
The
.code dup
function returns a one-argument function which calls the two-argument
function
.meta func
by duplicating its argument.

.TP* Example:

.cblk
  ;; square the elements of a list
  (mapcar [dup *] '(1 2 3)) -> (1 4 9)
.cble

.coNP Function @ flipargs
.synb
.mets (flipargs << func )
.syne
.desc
The
.code flipargs
function returns a two-argument function which calls the two-argument
function
.meta func
with reversed arguments.

.coNP Functions @ chain and @ chand
.synb
.mets (chain << func *)
.mets (chand << func *)
.syne
.desc
The
.code chain
function accepts zero or more functions as arguments, and returns
a single function, called the chained function, which represents the chained
application of those functions, in left to right order.

If
.code chain
is given no arguments, then it returns a variadic function which
ignores all of its arguments and returns
.codn nil .

Otherwise, the first function may accept any number of arguments. The second
and subsequent functions, if any, must accept one argument.

The chained function can be called with an argument list which is acceptable
to the first function. Those arguments are in fact passed to the first
function. The return value of that call is then passed to the second
function, and the return value of that call is passed to the third function
and so on. The final return value is returned to the caller.

The
.code chand
function is similar, except that it combines the functionality of
.code andf
into chaining. The difference between
.code chain
and
.code chand
is that
.code chand
immediately terminates and returns
.code nil
whenever any of the functions returns
.codn nil ,
without calling the remaining functions.

.TP* Example:

.cblk
  (call [chain + (op * 2)] 3 4) -> 14
.cble

In this example, a two-element chain is formed from the
.code +
function
and the function produced by
.code "(op * 2)"
which is a one-argument
function that returns the value of its argument multiplied by two.
(See the definition of the
.code op
operator).

The chained function is invoked using the
.code call
function, with the arguments
.code 3
and
.codn 4 .
The chained evaluation begins by passing
.code 3
and
.code 4
to
.codn + ,
which yields
.codn 7 .
This
.code 7
is then passed to the
.code "(op * 2)"
doubling function, resulting in
.codn 14 .

A way to write the above example without the use of the DWIM brackets and the
op operator is this:

.cblk
  (call (chain (fun +) (lambda (x) (* 2 x))) 3 4)
.cble

.coNP Function @ juxt
.synb
.mets (juxt << func *)
.syne
.desc
The
.code juxt
function accepts a variable number of arguments which are functions.  It
combines these into a single function which, when invoked, passes its arguments
to each of these functions, and collects the results into a list.

Note: the juxt function can be understood in terms of the following reference
implementation:

.cblk
  (defun juxt (funcs)
    (lambda (. args)
      (mapcar (lambda (fun)
                (apply fun args))
              funcs)))
.cble

.TP* Example:

.cblk
   ;; separate list (1 2 3 4 5 6) into lists of evens and odds,
   ;; which end up juxtaposed in the output list:

   [(op [juxt keep-if remove-if] evenp)
    '(1 2 3 4 5 6)] -> ((2 4 6) (1 3 5))

   ;; call several functions on 1, collecting their results:
   [[juxt (op + 1) (op - 1) evenp sin cos] 1]'
   -> (2 0 nil 0.841470984807897 0.54030230586814)
.cble

.coNP Functions @ andf and @ orf
.synb
.mets (andf << func *)
.mets (orf << func *)
.syne
.desc
The
.code andf
and
.code orf
functions are the functional equivalent of the
.code and
and
.code or
operators. These functions accept multiple functions and return a new function
which represents the logical combination of those functions.

The input functions should have the same arity. Failing that, there should
exist some common argument arity with which each of these can be invoked. The
resulting combined function is then callable with that many arguments.

The
.code andf
function returns a function which combines the input functions with
a short-circuiting logical conjunction. The resulting function passes its
arguments to the functions successively, in left to right order. As soon as any
of the functions returns
.codn nil ,
then nil is returned immediately, and the
remaining functions are not called.  Otherwise, if none of the functions return
.codn nil ,
then the value returned by the last function is returned. If the list of
functions is empty, then
.code t
is returned.  That is,
.code (andf)
returns a function
which accepts any arguments, and returns
.codn t .

The
.code orf
function combines the input functions with a short-circuiting logical
disjunction. The function produced by
.code orf
passes its arguments down to the
functions successively, in left to right order.  As soon as any function
returns a
.cod2 non- nil
value, that value is returned and the remaining functions are
not called. If all functions return
.codn nil ,
then
.code nil
is returned. The expression
.code (orf)
returns a function which accepts any arguments and returns
.codn nil .

.coNP Function @ notf
.synb
.mets (notf << function )
.syne
.desc
The
.code notf
function returns a function which is the Boolean negation
of
.metn function .

The returned function takes a variable number of arguments. When
invoked, it passes all of these arguments to
.meta function
and then inverts the result as if by application of the
.codn not .

.coNP Functions @ iff and @ iffi
.synb
.mets (iff < cond-func >> [ then-func <> [ else-func ]])
.mets (iffi < cond-func < then-func <> [ else-func ])
.syne
.desc
The
.code iff
function is the functional equivalent of the
.code if
operator. It accepts
functional arguments and returns a function.

The resulting function takes its arguments, if any, and applies them to
.metn cond-func .
If
.meta cond-func
yields true, then the arguments are passed to
.meta then-func
and the
resulting value is returned. Otherwise the arguments are passed to
.meta else-func
and the resulting value is returned.

If
.meta then-func
is omitted then
.code identity
is used as default. This omission is not permitted by
.codn iffi ,
only
.codn iff .

If
.meta else-func
needs to be called, but is omitted, then
.code nil
is returned.

The
.code iffi
function differs from
.code iff
only in the defaulting behavior with respect
to the
.meta else-func
argument. If
.meta else-func
is omitted in a call to
.code iffi
then the default function is
.codn identity .
This is useful in situations when one value is to be
replaced with another one when the condition is true, otherwise
preserved.

The following equivalences hold between
.code iffi
and
.codn iff :

.cblk
  (iffi a b c)            <--> (iff a b c)

  (iffi a b)              <--> (iff a b identity)

  [iffi a b nilf]         <--> [iff a b]

  [iffi a identity nilf]  <--> [iff a]
.cble

The following equivalences illustrate
.code iff
with both optional arguments omitted:

.cblk
  [iff a]  <--->  [iff a identity nilf]  <--->  a
.cble

.coNP Functions @ tf and @ nilf
.synb
.mets (tf << arg *)
.mets (nilf << arg *)
.syne
.desc
The
.code tf
and
.code nilf
functions take zero or more arguments, and ignore them.
The
.code tf
function returns
.codn t ,
and the
.code nilf
function returns
.codn nil .

Note: the following equivalences hold between these functions and the
.code ret
operator, and
.code retf
function.

.cblk
  (fun tf) <--> (ret t) <--> (retf t)
  (fun nilf) <--> (ret nil) <--> (ret) <--> (retf nil)
.cble

In Lisp-1-style code,
.code tf
and
.code nilf
behave like constants which can replace uses of
.code "(ret t)"
and
.codn "(ret nil)" :

.cblk
  [mapcar (ret nil) list] <--> [mapcar nilf list]
.cble

.TP* Example:

.cblk
  ;; tf and nilf are useful when functions are chained together.
  ;; test whether (trunc n 2) is odd.

  (defun trunc-n-2-odd (n)
    [[chain (op trunc @1 2) [iff oddp tf nilf]] n])
.cble

In this example, two functions are chained together, and
.code n
is passed
through the chain such that it is first divided by two via the
function denoted by
.code "(op trunc @1 2)"
and then the result is passed into the
function denoted by
.codn "[iff oddp tf nilf]" .
The
.code iff
function passes its argument into
.codn oddp ,
and if
.code oddp
yields true, it passes the same argument to
.codn tf .
Here
.code tf
proves its utility by ignoring that value and returning
.codn t .
If the argument (the divided value) passed into
.code iff
is even, then iff passes it into the
.code nilf
function, which ignores the value and returns
.codn nil .

.coNP Function @ retf
.synb
.mets (retf << value )
.syne
.desc
The
.code retf
function returns a function. That function can take zero or
more arguments. When called, it ignores its arguments and returns
.metn value .

See also: the
.code ret
macro.

.TP* Example:

.cblk
  ;; the function returned by (retf 42)
  ;; ignores 1 2 3 and returns 42.
  (call (retf 42) 1 2 3) -> 42
.cble

.coNP Functions @ apf and @ ipf
.synb
.mets (apf << function )
.mets (ipf << function )
.syne
.desc
The
.code apf
function returns a one-argument function which accepts
a list. When the function is called, it treats the list as
arguments which are applied to
.meta function
as if by apply. It returns whatever
.meta function
returns.

The
.code ipf
function is similar to
.codn apf ,
except that the returned
function applies arguments as if by
.code iapply
rather than
.codn apply .

See also: the
.code ap
macro.

.TP* Example:

.cblk
  ;; Function returned by [apf +] accepts the
  ;; (1 2 3) list and applies it to +, as
  ;; if (+ 1 2 3) were called.

  (call [apf +] '(1 2 3)) -> 6
.cble

.coNP Function @ callf
.synb
.mets (callf < main-function << arg-function *)
.syne
.desc
The
.code callf
function returns a function which applies its arguments to each
.metn arg-function ,
juxtaposing the return values of these calls to form arguments
which are then passed to
.metn main-function .
The return value of
.meta main-function
is returned.

The following equivalence holds, except for the order of evaluation of
arguments:

.cblk
  (callf fm f0 f1 f2 ...) <--> (chain (juxt f0 f1 f2 ...) (apf fm))
.cble

.TP* Example:

.cblk
  ;; Keep those pairs which are two of a kind

  (keep-if [callf eql first second] '((1 1) (2 3) (4 4) (5 6)))
  -> ((1 1) (4 4))
.cble

.coNP Function @ mapf
.synb
.mets (mapf < main-function << arg-function *)
.syne
.desc
The
.code mapf
function returns a function which distributes its arguments
into the
.metn arg-function -s.
That is to say, each successive argument of the returned
function is associated with a successive
.metn arg-function .

Each
.meta arg-function
is called, passed the corresponding argument. The return
values of these functions are then passed as arguments
to
.meta main-function
and the resulting value is returned.

If the returned function is called with fewer arguments than there
are
.metn arg-function -s,
then only that many functions are used. Conversely, if the function is
called with more arguments than there are
.metn arg-function -s,
then those arguments are ignored.

The following equivalence holds:

.cblk
  (mapf fm f0 f1 ...) <--> (lambda (. rest)
                              [apply fm [mapcar call (list f0 f1 ...) rest]])
.cble

.TP* Example:

.cblk
  ;; Add the squares of 2 and 3
  [[mapf + [dup *] [dup *]] 2 3] -> 13

.cble

.SS* Input and Output (Streams)
\*(TL supports input and output streams of various kinds, with
generic operations that work across the stream types.

In general, I/O errors are usually turned into exceptions. When the description
of error reporting is omitted from the description of a function, it can be
assumed that it throws an error.

.coNP Special variables @, *stdout* @, *stddebug* @, *stdin* @ *stderr* and @ *stdnull*
.desc
These variables hold predefined stream objects. The
.codn *stdin* ,
.code *stdout*
and
.code *stderr*
streams closely correspond to the underlying operating system streams.
Various I/O functions require stream objects as arguments.

The
.code *stddebug*
stream goes to the same destination as
.codn *stdout* ,
but is a separate object which can be redirected independently, allowing
debugging output to be separated from normal output.

The
.code *stdnull*
stream is a special kind of stream called a null stream.
This stream is not connected to any device or file.  It is similar to
the
.code /dev/null
device on Unix, but does not involve the operating system.

.coNP Special variable @ *print-flo-format*
.desc
The
.code *print-flo-format*
variable determines the conversion format which is applied when
a floating-point value is converted to decimal text by the
functions
.codn print ,
.codn pprint ,
.codn prinl ,
.codn pprinl ,
.code tostring
and
.codn tostringp .

The default value is
.codn "~s" .

The format string must specify the consumption of exactly one argument.

The conversion string may use embedded width and precision values:
for instance,
.code "~3,4f"
is a valid value for
.codn *print-flo-format* .

.coNP Special variable @ *print-flo-precision*
.desc
The
.code *print-flo-precision*
special variable specifies the default floating-point printing
precision which is used when the
.code ~a
or
.code ~s
conversion specifier of the
.code format
function is used for printing a floating-point value, and no precision
is specified.

Note that since the default value of the variable
.code *print-flo-format*
is the string
.codn "~s" ,
the
.code *printf-flo-precision*
variable, by default, also determines the precision which applies when
floating-point values are converted to decimal text by the functions
.codn print ,
.codn pprint ,
.codn prinl ,
.codn pprinl ,
.code tostring
and
.codn tostringp .

The default value of
.code *print-flo-precision*
is that of the
.code flo-dig
variable.

Note: to print floating-point values in such a way that their values
can be precisely recovered from the printed representation, it is
recommended to override
.code *print-flo-precision*
to the value of the
.code flo-max-dig
variable.

.coNP Special variable @ *print-flo-digits*
.desc
The
.code *print-flo-precision*
special variable specifies the default floating-point printing
precision which is used when the
.code ~f
or
.code ~e
conversion specifier of the
.code format
function is used for printing a floating-point value, and no precision
is specified.

Its default value is
.codn 3 .

.coNP Special variable @ *print-base*
.desc
The
.code *print-base*
variable controls the base (radix) used for printing integer values.
It applies when the functions
.codn print ,
.codn pprint ,
.codn prinl ,
.codn pprinl ,
.code tostring
and
.code tostringp
process an integer value.
It also applies when the
.code ~a
and
.code ~s
conversion specifiers of the
.code format
function are used for printing an integer value.

The default value of the variable is
.codn 10 .

Meaningful values are:
.codn 2 ,
.codn 8 ,
.code 10
and
.codn 16 .

When base 16 is selected, hexadecimal digits are printed as upper-case
characters.

.coNP Function @ format
.synb
.mets (format < stream-designator < format-string << format-arg *)
.syne
.desc
The
.code format
function performs output to a stream given by
.metn stream-designator ,
by interpreting the actions implicit in a
.metn format-string ,
incorporating material pulled from additional arguments given by
.cblk
.meti << format-arg *.
.cble
Though the function is simple to invoke, there is complexity in format string
language, which is documented below.

The
.meta stream-designator
argument can be a stream object, or one of the values
.code t
or
.codn nil .
The value
.code t
serves as a shorthand for
.codn *stdout* .
The value
.code nil
means that the function will send output into a newly instantiated string
output stream, and then return the resulting string.

.TP* "Format string syntax:"

Within
.metn format-string ,
most characters represent themselves. Those
characters are simply output. The character
.code ~
(tilde) introduces formatting
directives, which are denoted by a single character, usually a letter.

The special sequence
.code ~~
(tilde-tilde) encodes a single tilde. Nothing is
permitted between the two tildes.

The syntax of a directive is generally as follows:

.cblk
.mets <> ~[ width ] <> [, precision ] < letter
.cble

In other words, the
.code ~
(tilde) character, followed by a
.meta width
specifier, a
.meta precision
specifier introduced by a comma,
and a
.metn letter ,
such that
.meta width
and
.meta precision
are independently optional: either or both may be omitted.
No whitespace is allowed between these elements.

The
.meta letter
is a single alphabetic character which determines the
general action of the directive. The optional width and precision
are specified as follows:

.RS
.meIP < width
The width specifier consists of an optional
.code <
(left angle bracket) character or
.code ^
(caret)
character followed by an optional width specification.

If the leading
.code <
character is present, then the printing will be left-adjusted within
this field. If the
.code ^
character is present, the printing will be centered within the field.
Otherwise it will be right-adjusted by default.

The width can be specified as a decimal integer with an optional leading
minus sign, or as the character
.codn * .
The
.code *
notation means that instead of digits, the value of the next argument is
consumed, and expected to be an integer which specifies the width. If the
width, specified either way, is negative, then the field will be left-adjusted.
If the value is positive, but either the
.code <
or
.code ^
prefix character is present in the width
specifier, then the field is adjusted according to that character.

The padding calculations for alignment and centering take into account
character display width, as defined by the
.code display-width
function. For instance, a character string containing four Chinese
characters (kanji) has a display width of 8, not 4.

The width specification does not restrict the printed portion of a datum.
Rather, for some kinds of conversions, it is the precision specification that
performs such truncation.  A datum's display width (or that of its printed
portion, after such truncation is applied) can equal or exceed the specified
field width.  In this situation it overflows the field: the printed portion is
rendered in its entirety without any padding applied on either side for
alignment or centering.

.meIP < precision
The precision specifier is introduced by a leading comma. If this comma appears
immediately after the directive's
.code ~
character, then it means that
.meta width
is being omitted; there is only a precision field.

The precision specifier may begin with these optional characters:
.RS
.coIP 0
(the "leading zero flag"),
.coIP +
(print a sign for positive values")
.IP space
(print a space in place of a positive sign).
.RE

The precision specifier itself is either a decimal integer that does not
begin with a zero digit, or the
.code *
character.

The precision field's components have a meaning which depends on the type of
object printed and the conversion specifier.

For integer arguments, the precision value specifies the minimum number of digits
to print.  If the precision field has a leading zero flag, then the integer is
padded with zeros to the required number of digits, otherwise the number is
padded with spaces instead of zeros.  If zero or space padding is present, and
a leading positive or negative sign must be printed, then it is placed before
leading zeros, or after leading spaces, as the case may be.

For floating-point values, the meaning of the precision value depends on which
specific conversion specifier
.cod1 ( f ,
.codn e ,
.code a
or
.codn s )
is used. The details are
documented in the description of each of these, below. The leading zero flag is
ignored for floating-point values regardless of the conversion specifier.

For integer or floating-point arguments, if the precision specifier has a
.code +
sign
among the special characters, then a
.code +
sign is printed for positive numbers. If
the precision specifier has a leading space instead of a
.code +
sign, then the
.code +
sign is rendered as a space for positive numbers. If there is no leading space
or
.codn + ,
then a sign character is omitted for positive numbers. Negative
numbers are unconditionally prefixed with a
.code -
sign.

For all other objects, the precision specifies the maximum number of
print positions to occupy, taking into account the display width of each
character of the printed representation of the object, as according
to the
.code display-width
function.  The object's printed representation is truncated, if necessary, to
the maximum number of characters which will not exceed the specified number of
print positions.

.RE

.TP* "Format directives:"
.RS
Format directives are case sensitive, so that for example
.code ~x
and
.code ~X
have a
different effect, and
.code ~A
doesn't exist whereas
.code ~a
does. They are:

.coIP a
Prints any object in an aesthetic way, as if by the
.code pprint
function.
The aesthetic notation violates read-print consistency: this notation
is not necessarily readable if it is implanted in \*(TX source code.
The field width specifier is honored, including the left-right adjustment
semantics.

When this specifier is used for floating-point values, the precision specifies
the maximum number of total significant figures, which do not include any
digits in the exponent, if one is printed. Numbers are printed in exponential
notation if their magnitude is small, or else if their exponent exceeds their
precision. If the precision is not specified, then it is obtained from
the
.code *print-flo-precision*
special variable, whose default value is the same as that of the
.code flo-dig
variable.
Floating point values which are integers are
printed without a trailing
.code .0
(point zero).

.coIP s
Prints any object in a standard way, as if by the print function.  Objects for
which read-print consistency is possible are printed in a way such that
if their notation is implanted in \*(TX source, they are readable.
The field width specifier is honored, including the left-right adjustment
semantics. The precision field is treated very similarly to the
.code ~a
format directive, except that non-exponentiated floating point numbers that
would be mistaken for integers include a trailing
.code .0
for the sake of read-print
consistency. Objects truncated by precision may not have read-print
consistency. For instance, if a string object is truncated, it loses its
trailing closing quote, so that the resulting representation is no longer
a properly formed string object. For integer objects, the
.code *print-base*
variable is honored. Effectively, an integer is printed by the
.code s
directive as if by the
.codn b ,
.codn o ,
.codn d ,
or
.code x
directive, depending on the value of the variable.

.coIP d
Requires an argument of integer or character type type. The integer
value or character code is printed in decimal.

.coIP x
Requires an argument of character or integer type. The integer value or
character code is printed in hexadecimal, using lower-case letters
for the digits
.code a
through
.codn f .
Width and precision semantics
are as described for the
.code a
format directive, for integers.

.coIP X
Like the
.code x
directive, but the hexadecimal digits
.code a
through
.code f
are rendered in upper case.

.coIP o
Like the
.code x
directive, but octal is used instead of hexadecimal.

.coIP b
Like the
.code x
directive, but binary is used instead of hexadecimal.

.coIP f
The
.code f
directive prints numbers in a fixed point decimal notation, with
a fixed number of digits after the decimal point. It requires a numeric
argument. (Unlike
.codn x ,
.code X
and
.codn o ,
it does not allow an argument of character type).
The precision specifier gives the number of digits past the decimal point.
The number is rounded off to the specified precision, if necessary.
Furthermore, that many digits are always printed, regardless of the actual
precision of the number or its type.  If it is omitted, then the value
is obtained from the special variable
.codn *print-flo-digits* ,
whose default value is three: three digits past the decimal point. A precision
of zero means no digits pas the decimal point, and in this case the decimal
point is suppressed (regardless of whether the numeric argument is
floating-point or integer).

.coIP e
The
.code e
directive prints numbers in exponential notation. It requires
a numeric argument. (Unlike
.codn x ,
.code X
and
.codn o ,
it does not allow an argument of character type).
The precision specifier gives the number of digits past the decimal point
printed in the exponential notation, not counting the digits in the exponent.
Exactly that many digits are printed, regardless of the precision of the
number.  If the precision is omitted, then the number of digits after the
decimal point is obtained from the value of the special variable
.codn *print-flo-digits* ,
whose default value is three. If the precision is zero, then a decimal portion
is truncated off entirely, including the decimal point.

.coIP p
The
.code p
directive prints a numeric representation in hexadecimal of the bit pattern
of the object, which is meaningful to someone familiar with the internals
of \*(TX.  If the object is a pointer to heaped data, that value
has a correspondence to its address.
.RE

.coIP !
The
.code !
directive establishes hanging indentation, and turns on the stream's
indentation mode. Subsequent lines printed within the execution of the
same
.code format
call will be automatically indented. If no width is specified, then
the directive sets the hanging indentation to the current printing
column position. If a width is specified, then it represents an offset
(positive or negative). If the
.code <
prefix character is present, the hanging indentation is set to the
specified offset relative to the current printing column.
If the
.code <
prefix is present on the width field, then the offset is applied
relative to the indentation which was saved on entry into the
.code format
function.

The indentation mode and indentation column are automatically restored to their
previous values when
.code format
function terminates, naturally or via an exception or non-local jump.

The effect of a precision field (even if zero) combined with the
.code !
directive is currently not specified, and reserved for future extension.
The precision field is processed syntactically, and no error occurs, however.

.PP

.coNP Function @ fmt
.synb
.mets (fmt < format-string << format-arg *)
.syne
.desc
The
.code fmt
function provides a short-hand for formatting to a string, according
to the following equivalence which holds between
.code fmt
and
.codn format :

.cblk
  (fmt s arg ...)  <-->  (format nil s arg ...)
.cble

.coNP Functions @, print @, pprint @, prinl @, pprinl @ tostring and @ tostringp
.synb
.mets (print < obj <> [ stream ])
.mets (pprint < obj <> [ stream ])
.mets (prinl < obj <> [ stream ])
.mets (pprinl < obj <> [ stream ])
.mets (tostring << obj )
.mets (tostringp << obj )
.syne
.desc
The
.code print
and
.code pprint
functions render a printed character representation of the
.meta obj
argument into
.metn stream .
If a stream argument is not supplied, then
the destination is the stream currently stored in the
.code *stdout*
variable. The
.code print
function renders in a way which strives for read-print
consistency: an object is printed in a notation which is recognized as
a similar object of the same kind when it appears in \*(TX source code.
The
.code pprint
function ("pretty print") does not strive for read-print consistency.
For instance it prints a string object simply by dumping its characters, rather
than by adding the surrounding quotes and rendering escape syntax for
special characters. Both functions return
.metn obj .

The
.code prinl
and
.code pprinl
functions are like
.code print
and
.codn pprint ,
except that they issue a newline character after printing the object.
These functions also return
.metn obj .

The
.code tostring
and
.code tostringp
functions are like
.code print
and
.codn pprint ,
but they do not accept a stream argument. Instead they print to a freshly
instantiated string stream, and return the resulting string.

The following equivalences hold between calls to the
.code format
function and calls to the above functions:

.cblk
  (format stream "~s" obj)  <-->  (print obj stream)
  (format t "~s" obj)       <-->  (print obj)
  (format t "~s\en" obj)     <-->  (prinl obj)
  (format nil "~s" obj)     <-->  (tostring obj)
.cble

For
.codn pprint ,
.code tostringp
and
.codn pprinl ,
the equivalence is produced by using
.code ~a
in format rather than
.codn ~s .

Note: for characters, the print function behaves as follows: most control
characters in the Unicode
.code C0
and
.code C1
range are rendered using the
.code #\ex
notation,
using two hex digits. Codes in the range
.code D800
to
.codn DFFF ,
and the codes
.code FFFE
and
.code FFFF
are printed in the
.code #\exNNNN
with four hexadecimal digits, and
character above this range are printed using the same notation, but with six
hexadecimal digits. Certain characters in the
.code C0
range are printed using
their names such as
.code #\enul
and
.codn #\ereturn ,
which are documented
in the Character Literals section.
The
.code DC00
character is printed as
.codn #\epnul .
All other characters are printed as
.cblk
.meti >> #\e char
.cble
where
.meta char
is the actual character.

Caution: read-print consistency is affected by trailing material. If additional
digits are printed immediately after a number without intervening whitespace,
they extend that number. If hex digits are printed after the character
.codn x ,
which is rendered as
.codn #\ex ,
they look like a hex character code.

.coNP Function @ tprint
.synb
.mets (tprint < obj <> [ stream ])
.syne
.desc
The
.code tprint
function prints a representation of
.meta obj
on
.metn stream .

If the stream argument is not supplied, then
the destination is the stream currently stored in the
.code *stdout*
variable.

For all object types except lists and vectors,
.code tprint
behaves like
.codn pprinl .

If
.code obj
is a list or vector, then
.code tprint
recurses: the
.code tprint
function is applied to each element.  An empty list or vector
results in no output at all.  This effectively means that an arbitrarily nested
structure of lists and vectors is printed flattened, with one element on each
line.

.coNP Function @ display-width
.synb
.mets (display-width << char )
.mets (display-width << string )
.syne
.desc
The
.code display-width
function calculates the number of places occupied by the printed representation
of
.meta char
or
.meta string
on a monospace display which renders certain characters, such as the East Asian
kanji and other characters, using two places.

For a
.meta string
argument, this value is the sum of the individual display width of the
string's constituent characters. The display width of an empty string is zero.

Control characters are assigned a display width of zero, regardless of
their display control semantics, if any.

Characters marked by Unicode as being wide or full width, have a display
width of two. Other characters have a display width of one.

.coNP Function @ streamp
.synb
.mets (streamp << obj )
.syne
.desc
The
.code streamp
function returns
.code t
if
.meta obj
is any type of stream.  Otherwise it returns
.codn nil .

.coNP Function @ real-time-stream-p
.synb
.mets (real-time-stream-p << obj )
.syne
.desc
The
.code real-time-streamp-p
function returns
.code t
if
.meta obj
is a stream marked as
"real-time".  If
.meta obj
is not a stream, or not a stream marked as "real-time",
then it returns
.codn nil .

Only certain kinds of streams accept the real-time attribute: file streams and
tail streams. This attribute controls the semantics of the application of
.code lazy-stream-cons
to the stream.  For a real-time stream,
.code lazy-stream-cons
returns a stream with "naive" semantics which returns data as soon as it is
available, at the cost of generating spurious
.code nil
item when the stream
terminates. The application has to recognize and discard that
.code nil
item.
The ordinary lazy streams read ahead by one line and suppress this extra
item, so their representation is more accurate.

When \*(TX starts up, it automatically marks the
.code *std-input*
stream as real-time, if it is connected to a TTY device (a device for which
the POSIX function
.code isatty
reports true). This is only supported on platforms that have this function.
The behavior is overridden by the
.code -n
command line option.

.coNP Function @ open-file
.synb
.mets (open-file < path <> [ mode-string ])
.syne
.desc
The
.code open-file
function creates a stream connected to the file
which is located at the given
.metn path ,
which is a string.

The
.meta mode-string
argument is a string which uses the same
conventions as the mode argument of the C language
.code fopen
function, with greater permissiveness, and some extensions.

The syntax of mode-string is described by the following
grammar. Note that it permits no whitespace characters:

.cblk
.mets < mode-string := [ < mode ] [ < options ]
.mets < mode := { < selector [ + ] | + }
.mets < selector := { r | w | a }
.mets < options := { b | l | u | < digit }
.mets < digit := { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 }
.cble

If the
.meta mode-string
argument is omitted, the behavior is the same as an empty
mode string.

The
.meta mode
part of the mode string generates the following possibilities:
.RS
.meIP empty
If the
.meta mode
is missing, then a default mode is implied. The default
is specific to the particular stream-opening function. In
the case of
.codn open-file ,
the default mode is
.codn r .
.coIP +
A
.meta mode
consisting of just the
.code +
character is equivalent to
.codn r+ .
.coIP r
This
.meta mode
means that the file is opened for reading.
.coIP r+
The file is opened for reading and writing.  It is not created
if it doesn't exist.
.coIP w
The file is opened for writing. If it exists, it is truncated
to zero length. If it doesn't exist, it is created.
.coIP w+
The file is opened for reading and writing. If it exists, it
is truncated to zero length. If it doesn't exist, it is created.
.coIP a
The file is opened for writing. If it doesn't exist, it is
created. If it exists, the current position is advanced to
one byte past the end of the file, so that newly written data
are appended.
.coIP a+
The file is opened for reading and writing. If it doesn't exist,
it is created. The read position is at the beginning of the file,
but writes are appended to the end regardless of the position.
.RE
.IP
The meanings of the option characters are:
.RS
.coIP b
The file is opened in binary mode: no line ending translation takes place.
In the absence of this option, files are opened in text mode, in which newline
characters in the stream are an abstract indication of the end of a line,
translate to a system-specific way of terminating lines in text files.
.coIP l
Specifies that the stream will be line buffered.  This means that an implicit
flush operation takes place whenever the newline character is output.
.coIP u
Specifies that the stream will be unbuffered.  It is erroneous for both
.code l
and
.code u
to be specified.
.coIP i
Specifies that the stream will have the real-time
property set. For a description of the semantics, see the
.code real-time-stream-p
function. Briefly, this property affects the semantics of lazy lists which draw
input from the stream.
In addition, for a stream opened for writing or reading and writing, the
.code i
mode letter specifies that the stream will be line buffered, unless
specified as unbuffered with
.codn u .
.meIP digit
A decimal digit specifies the the stream buffer size
as binary exponential buffer size order, such that
.code 0
specifies 1024 bytes,
.code 1
specifies 2048 and so forth up to
.code 9
specifying 524288 bytes. If no such digit is specified, then the
stream uses a default buffer size. It is erroneous for the
size order digit to be present together with the option
.codn u .
.RE

.coNP Function @ open-tail
.synb
.mets (open-tail < path >> [ mode-string <> [ seek-to-end-p ]])
.syne
.desc
The
.code open-tail
function creates a tail stream connected to the file which is
located at the given
.metn path .
The
.meta mode-string
argument is a string which uses
the same conventions as the mode argument of the C language
.code fopen
function. If this argument is omitted, then
.str r
is used.
See the
.code open-file
function for a discussion of modes.

The
.code seek-to-end-p
argument is a Boolean which determines whether the initial
read/write position is at the start of the file, or just past the end.
It defaults to
.codn nil .
This argument only makes a difference if the file exists
at the time
.code open-tail
is called. If the file does not exist, and is later
created, then the tail stream will follow that file from the beginning.  In
other words,
.meta seek-to-end-p
controls whether the tail stream reads all the
existing data in the file, if any, or whether it reads only newly added data
from approximately the time the stream is created.

A tail stream has special semantics with regard to reading at the end
of file. A tail stream never reports an end-of-file condition; instead
it polls the file until more data is added. Furthermore, if the file
is truncated, or replaced with a smaller file, the tail stream follows
this change: it automatically opens the smaller file and starts reading from
the beginning (the
.meta seek-to-end-p
flag only applies to the initial open).
In this manner, a tail stream can dynamically growing rotating log files.

Caveat: since a tail stream can re-open a new file which has the same
name as the original file, it behave incorrectly if the program
changes the current working directory, and the path name is relative.

.coNP Function @ open-directory
.synb
.mets (open-directory << path )
.syne
.desc
The
.code open-directory
function tries to create a stream which reads the
directory given by the string argument
.metn path .
If a filesystem object exists
under the path, is accessible, and is a directory, then the function
returns a stream. Otherwise, a file error exception is thrown.

The resulting stream supports the get-line operation. Each call to the
.code get-line
operation retrieves a string representing the next directory
entry. The value
.code nil
is returned when there are no more directory entries.
The
.code .
and
.code ..
entries in Unix filesystems are not skipped.

.coNP Function @ make-string-input-stream
.synb
.mets (make-string-input-stream << string )
.syne
.desc
This function produces an input stream object. Character read operations on the
stream object read successive characters from
.metn string .
Output operations and byte operations are not supported.

.coNP Function @ make-string-byte-input-stream
.synb
.mets (make-string-byte-input-stream << string )
.syne
.desc
This function produces an input stream object. Byte read operations on
this stream object read successive byte values obtained by encoding
.meta string
into UTF-8. Character read operations are not supported, and neither
are output operations.

.coNP Function @ make-string-output-stream
.synb
.mets (make-string-output-stream)
.syne
.desc
This function, which takes no arguments, creates a string output stream.
Data sent to this stream is accumulated into a string object.
String output streams supports both character and byte output operations.
Bytes are assumed to represent a UTF-8 encoding, and are decoded in order
to form characters which are stored into the string.

If an incomplete UTF-8 code is output, and a character output operation then
takes place, that code is assumed to be terminated and is decoded as invalid
bytes.  The UTF-8 decoding machine is reset and ready for the start of a new
code.

The
.code get-string-from-stream
function is used to retrieve the accumulated string.

If the null character is written to a string output stream, either via
a character output operation or as a byte operation, the resulting string
will appear to be prematurely terminated. \*(TX strings cannot contain null
bytes.

.coNP Function @ get-string-from-stream
.synb
.mets (get-string-from-stream << stream )
.syne
.desc
The
.meta stream
argument must be a string output stream. This function finalizes
the data sent to the stream and retrieves the accumulated character string.

If a partial UTF-8 code has been written to
.metn stream ,
and then this
function is called, the byte stream is considered complete and the partial
code is decoded as invalid bytes.

After this function is called, further output on the stream is not possible.

.coNP Function @ make-strlist-output-stream
.synb
.mets (make-strlist-output-stream)
.syne
.desc
This function is very similar to
.codn make-string-output-stream .
However, the stream object produced by this function does not produce a string,
but a list of strings.  The data is broken into multiple strings by newline
characters written to the stream. Newline characters do not appear in the
string list. Also, byte output operations are not supported.

.coNP Function @ get-list-from-stream
.synb
.mets (get-list-from-stream << stream )
.syne
.desc
This function returns the string list which has accumulated inside
a string output stream given by
.metn stream .
The string output stream is
finalized, so that further output is no longer possible.

.coNP Macro @ with-in-string-stream
.synb
.mets (with-in-string-stream >> ( stream-var << string )
.mets \ \  << body-form *)
.syne
.desc
The
.code with-in-string-stream
macro binds the symbol
.meta stream-var
as a variable, initializing it with a newly created
string input stream. The string input stream is
constructed from
.meta string
as if by the
.cblk
.meti (make-string-input-stream << string )
.cble
expression.

Then it evaluates the
.metn body-form -s
in the scope of the variable.

The value of the last
.meta body-form
is returned, or else
.code nil
if no forms are present.

The
.meta stream-var
argument must be a bindable symbol,
as defined by the
.code bindable
function.

The
.meta string
argument must be a form
which evaluates to a character string value.

.coNP Macro @ with-in-string-byte-stream
.synb
.mets (with-in-string-byte-stream >> ( stream-var << string )
.mets \ \  << body-form *)
.syne
.desc
The
.code with-in-string-byte-stream
macro binds the symbol
.meta stream-var
as a variable, initializing it with a newly created
string byte input stream. The string input stream is
constructed from
.meta string
as if by the
.cblk
.meti (make-string-byte-input-stream << string )
.cble
expression.

Then it evaluates the
.metn body-form -s
in the scope of the variable.

The value of the last
.meta body-form
is returned, or else
.code nil
if no forms are present.

The
.meta string
argument must be a form
which evaluates to a character string value.

.coNP Macro @ with-out-string-stream
.synb
.mets (with-out-string-stream <> ( stream-var ) << body-form *)
.syne
.desc
The
.code with-out-string-stream
macro binds the symbol specified
by the
.meta stream-var
argument as a variable, initializing it
with a newly created string output stream. The output
stream is created as if by the
.code make-string-output-stream
function.

Then it evaluates
.metn body-form -s
in the scope of that variable.

After these forms are evaluated, the string is extracted
from the string output stream, as if by the
.code get-string-from-stream
function, and returned as the result value
of the form.

.coNP Macro @ with-out-strlist-stream
.synb
.mets (with-out-strlist-stream <> ( stream-var ) << body-form *)
.syne
.desc
The
.code with-out-strlist-stream
macro binds the symbol specified
by the
.meta stream-var
argument as a variable, initializing it
with a newly created string list output stream. The output
stream is created as if by the
.code make-strlist-output-stream
function.

Then it evaluates
.metn body-form -s
in the scope of that variable.

After these forms are evaluated, the string list is extracted
from the string output stream, as if by the
.code get-strlist-from-stream
function, and returned as the result value
of the form.

.coNP Function @ close-stream
.synb
.mets (close-stream < stream <> [ throw-on-error-p ])
.syne
.desc
The
.code close-stream
function performs a close operation on
.metn stream ,
whose meaning is depends on the type of the stream. For some types of streams,
such as string streams, it does nothing. For streams which are connected
to operating system files or devices, will perform a close of the underlying
file descriptor, and dissociate that descriptor from the stream. Any buffered
data is flushed first.

.code close-stream
returns a Boolean true value if the close has occurred without
errors, otherwise
.codn nil .

For most streams, "without errors" means that any buffered output data is
flushed successfully.

For command and process pipes (see open-command and open-process), success also
means that the process terminates normally, with a successful error code, or an
unsuccessful one. An abnormal termination is considered an error, as
as is the inability to retrieve the termination status, as well as the situation
that the process continues running in spite of the close attempt.
Detecting these situations is platform specific.

If the
.meta throw-on-error-p
argument is specified, and isn't
.codn nil ,
then the
function throws an exception if an error occurs during the close operation
instead of returning
.codn nil .

.coNP Macro @ with-stream
.synb
.mets (with-stream >> ( stream-var << init-form )
.mets \ \  << body-form *)
.syne
.desc
The
.code with-stream
binds the variable whose name is given by the
.meta stream-var
argument, and macro arranges for the evaluation of
.metn body-form -s
in the scope of that variable.

The variable is initialized with the value produced
by the evaluation of
.meta init-form
which must be an expression which evaluates to a stream.

After each
.meta body-form
is evaluated, the stream is closed, as if by the
.cblk
.meti (close-stream << stream-var )
.cble
expression.

The value of the last
.meta body-form
then becomes the result value of the form,
or else
.code nil
if these forms are absent.

If the evaluation of the
.metn body-form -s
is abandoned, the stream is still closed. That is to say,
the closure of the stream is a protected action, as if by
the
.code unwind-protect
operator.

.coNP Functions @, get-error @ get-error-str and @ clear-error
.synb
.mets (get-error << stream )
.mets (get-error-str << stream )
.mets (clear-error << stream )
.syne
.desc
When a stream operation fails, the
.code get-error
and
.code get-error-str
functions may be used to inquire about a more detailed cause of the error.

Not all streams support these functions to the same extent. For instance,
string input streams have no persistent state. The only error which occurs
is the condition when the string has no more data.

The
.code get-error
inquires
.meta stream
about its error condition.

The function returns
.code nil
to indicate there is no error condition,
.code t
to indicate an end-of-data condition,
or else a value which is specific to the stream type indicating the
specific error type.

Note: for some streams, it is possible for the
.code t
value to be returned even though no operation has failed; that is to say, the
streams "know" they are at the end of the data even though no read operation
has failed. Code which depends on this will not work with streams which
do not thus indicate the end-of-data
.I a priori,
but by means of a read operation which fails.

The
.code get-error-str
function returns a text representation of the error code. The
.code nil
error code is represented as the string
.codn "no error" ;
the
.code t
error code as
.code "eof"
and other codes have a stream-specific representation.

The
.code clear-error
function removes the error situation from a stream. On some streams, it does
nothing. If an error has occurred on a stream, this function should be called
prior to re-trying any I/O or positioning operations.
The return value is the previous error code, or
.code nil
if there was no error, or the operation is not supported on the stream.

.coNP Functions @, get-line @ get-char and @ get-byte
.synb
.mets (get-line <> [ stream ])
.mets (get-char <> [ stream ])
.mets (get-byte <> [ stream ])
.syne
.desc
These fundamental stream functions perform input.  The
.meta stream
argument
is optional. If it is specified, it should be an input stream which supports
the given operation. If it is not specified, then the
.code *stdin*
stream is used.

The
.code get-char
function pulls a character from a stream which supports character
input.  Streams which support character input also support the
.code get-line
function which extracts a line of text delimited by the end of the stream or a
newline character and returns it as a string. (The newline character does not
appear in the string which is returned).

Character input from streams based on bytes requires UTF-8 decoding, so that
get-char actually may read several bytes from the underlying low level
operating system stream.

The
.code get-byte
function bypasses UTF-8 decoding and reads raw bytes from
any stream which supports byte input. Bytes are represented as integer
values in the range 0 to 255.

Note that if a stream supports both byte input and character input, then mixing
the two operations will interfere with the UTF-8 decoding.

These functions return
.code nil
when the end of data is reached.  Errors are
represented as exceptions.

See also:
.code get-lines

.coNP Function @ get-string
.synb
.mets (get-string >> [ stream >> [ count <> [ close-after-p ]]])
.syne
.desc
The
.code get-string
function reads characters from a stream, and assembles them into
a string, which is returned. If the
.meta stream
argument is omitted, then the
.code *stdin*
stream is used.

The stream is closed after extracting the data, unless
.meta close-after-p
is specified as
.codn nil .
The default value of this argument is
.codn t .

If the
.meta count
argument is missing, then all of the characters from the
stream are read and assembled into a string.

If present, the
.meta count
argument should be a positive integer indicating
a limit on how many characters to read. The returned string will be no
longer than
.metn count ,
but may be shorter.

.coNP Functions @ unget-char and @ unget-byte
.synb
.mets (unget-char < char <> [ stream ])
.mets (unget-byte < byte <> [ stream ])
.syne
.desc
These functions put back, into a stream, a character or byte which was
previously read.  The character or byte must match the one which was most
recently read. If the
.meta stream
argument is omitted, then the
.code *stdin*
stream is used.

If the operation succeeds, the byte or character value is returned.
A
.code nil
return indicates that the operation is unsupported.

Some streams do not support these operations; some support
only one of them.   In general, if a stream supports
.codn get-char ,
it supports
.codn unget-char ,
and likewise for
.code get-byte
and
.codn unget-byte .

Streams may require a pushed back byte or character to match
the character which was previously read from that stream
position, and may not allow a byte or character to be pushed
back beyond the beginning of the stream.

Space may be available for only one byte of pushback under the
.code unget-byte
operation.

The number of characters that may be pushed back by
.code unget-char
is not limited.

Pushing both a byte and a character, in either order, is also unsupported.
Pushing a byte and then reading a character, or pushing a character and
reading a byte, are unsupported mixtures of operations.

If the stream is binary, then pushing back a byte decrements its position,
except if the position is already zero. At that point, the position becomes
indeterminate.

The behavior of pushing back immediately after a
.code seek-stream
positioning operation is unspecified.

.coNP Functions @, put-string @, put-line @ put-char and @ put-byte
.synb
.mets (put-string < string <> [ stream ])
.mets (put-line >> [ string <> [ stream ]])
.mets (put-char < char <> [ stream ])
.mets (put-byte < byte <> [ stream ])
.syne
.desc
These functions perform output on an output stream. The
.meta stream
argument
must be an output stream which supports the given operation. If it is omitted,
then
.code *stdout*
is used.

The
.code put-char
function writes a character given by
.code char
to a stream. If the
stream is based on bytes, then the character is encoded into UTF-8 and multiple
bytes are written. Streams which support
.code put-char
also support put-line, and
.codn put-string .

The
.code put-string
function writes the characters of a string out to
the stream as if by multiple calls to put-char. The
.meta string
argument
may be a symbol, in which case its name is used as the string.

The
.code put-line
function is like
.codn put-string ,
but also writes an additional newline
character. The string is optional in
.codn put-line ,
and defaults to the empty string.

The
.code put-byte
function writes a raw byte given by the
.meta byte
argument
to
.metn stream ,
if
.meta stream
supports a byte write operation. The byte
value is specified as an integer value in the range 0 to 255.

All these functions return
.codn t .
On failure, they do not return, but throw exceptions of type
.codn file-error .

.coNP Functions @ put-strings and @ put-lines
.synb
.mets (put-strings < sequence <> [ stream ]])
.mets (put-lines < sequence <> [ stream ]])
.syne
.desc
These functions assume
.meta sequence
to be a sequence of strings, or of
symbols, or a mixture thereof. These strings are sent to the stream.  The
.meta stream
argument must be an output stream.  If it is omitted, then
.code *stdout*
is used.

The
.code put-strings
function iterates over
.meta sequence
and writes each element
to the stream as if using the
.code put-string
function.

The
.code put-lines
function iterates over
.code sequence
and writes each element
to the stream as if using the
.code put-line
function.

Both functions return
.codn t .

.coNP Function @ flush-stream
.synb
.mets (flush-stream <> [ stream ])
.syne
.desc
This function is meaningful for output streams which accumulate data
which is passed on to the operating system in larger transfer units.
Calling
.code flush-stream
causes all accumulated data inside
.meta stream
to be passed
to the operating system. If called on streams for which this function is not
meaningful, it does nothing, and returns
.codn nil .

If
.meta stream
is omitted, the current value of
.code *stdout*
is used.

.coNP Function @ seek-stream
.synb
.mets (seek-stream < stream < offset << whence )
.syne
.desc
The
.code seek-stream
function is meaningful for file streams. It changes the
current read/write position within
.metn stream .
It can also be used to determine the current position: see the notes about the
return value below. 

The
.meta offset
argument is a positive or negative integer which gives a
displacement that is measured from the point identified by the
.meta whence
argument.

Note that for text files, there isn't necessarily a 1:1 correspondence between
characters and positions due to line-ending conversions and conversions
to and from UTF-8.

The
.meta whence
argument is one of three keywords: :from-start, :from-current
and :from-end. These denote the start of the file, the current position
and the end of the file.

If
.meta offset
is zero, and
.meta whence
is
.codn :from-current ,
then
.code seek-stream
returns the current absolute position within the
stream, if it can successfully obtain it. Otherwise, it
returns
.code t
if it is successful.

If a character has been successfully put back into a text stream with
.code unget-char
and is still pending, then the position value is unspecified. If a
byte has been put back into a binary stream with
.codn unget-byte ,
and the previous position wasn't zero, then the position is decremented by one.

On failure, it throws an exception of type
.codn stream-error .

.coNP Function @ truncate-stream
.synb
.mets (truncate-stream < stream << length )
.syne
.desc
The
.code truncate-stream
causes the length of the underlying file associated with
.meta stream
to be set to
.meta length
bytes.

The stream must be a file stream, and must be open for writing.

.coNP Functions @ stream-get-prop and @ stream-set-prop
.synb
.mets (stream-get-prop < stream << indicator )
.mets (stream-set-prop < stream < indicator << value )
.syne
.desc
These functions get and set properties on a stream. Only certain properties
are meaningful with certain kinds of streams, and the meaning depends on
the stream. If two or more stream types support a property of the same name, it
is expected that the property has the same or very similar meaning for both
streams to the maximum extent that similarity is possible.

The
.code stream-set-prop
function sets a property on a stream. The
.meta indicator
argument is a symbol, usually a keyword symbol, denoting the property,
and
.meta value
is the property value. If the stream understands and accepts the
property, the function returns
.codn t .
Otherwise it returns
.codn nil .

The
.code stream-get-prop
function inquires about the value of a property on a
stream. If the stream understands the property, then it returns its current
value.  If the stream does not understand a property, nil is returned, which is
also returned if the property exists, but its value happens to be
.codn nil .

The
.code :name
property is widely supported by streams of various types. It associates
the stream with a name. This property is not always modifiable.

File, process and stream socket I/O streams have a
.code :fd
property which can be accessed, but not modified. It retrieves
the same value as the
.code stream-fd
function.

The "real time"
property supported by these streams, connected with the
.code real-time-stream-p
function, also appears as the
.code :real-time
property.

I/O streams also have a property called
.code :byte-oriented
which, if set, suppresses the decoding of UTF-8 on character input. Rather,
each byte of the file corresponds directly to one character. Bytes
in the range 1 to 255 correspond to the character code points U+0001
to U+00FF. Byte value 0 is mapped to the code point U+DC00.

The logging priority of the
.code *stdlog*
syslog stream is controlled by the
.code :prio
property.

If
.meta stream
is a catenated stream (see the function
.codn make-catenated-stream )
then these functions transparently operate on the current head stream of the
catenation.

.coNP Functions @ make-catenated-stream and @ cat-streams
.synb
.mets (make-catenated-stream << stream *)
.mets (cat-streams << stream-list )
.syne
.desc
The
.code make-catenated-stream
function takes zero or more arguments which
are input streams of the same type, and combines
them into a single virtual stream called a catenated stream.

The
.code cat-streams
function takes a single list of input streams of
the same type, and similarly combines them into a catenated stream.

A catenated stream does not support seeking operations or output,
regardless of the capabilities of the streams in the list.

If the stream list is not empty, then the leftmost element of the
list is called the head stream.

The
.codn get-char ,
.codn get-byte ,
.codn get-line ,
.code unget-char
and
.code unget-byte
functions delegate
to the corresponding operations on the head stream, if it exists.
If the stream list is empty, they return
.code nil
to the caller.

If the
.codn get-char ,
.code get-byte
or
.code get-line
operation on the head stream yields
.codn nil ,
and there are more lists in the stream, then the stream is closed, removed from
the list, and the next stream, if any, becomes the head list. The operation is
then tried again.  If any of these operations fail on the last list, it is not
removed from the list, so that a stream remains in place which can take the
.code unget-char
or
.code unget-byte
operations.

In this manner, the catenated streams appear to be a single stream.

Note that the operations can fail due to being unsupported. It is
the caller's responsibility to make sure all of the streams in the list
are compatible with the intended operations.

If the stream list is empty then an empty catenated stream is produced.
Input operations on this stream yield
.codn nil ,
and the
.code unget-char
and
.code unget-byte
operations throw an exception.

.coNP Function @ catenated-stream-p
.synb
.mets (catenated-stream-p << obj )
.syne
.desc
The
.code catenated-stream-p
function returns
.code t
if
.meta obj
is a catenated stream. Otherwise it returns
.codn nil .

.coNP Function @ catenated-stream-push
.synb
.mets (catenated-stream-push < new-stream << cat-stream )
.syne
.desc
The
.code catenated-stream-push
function pushes
.meta new-stream
to the front of the stream list inside
.metn cat-stream .

If an
.code unget-byte
or
.code unget-char
operation was successfully performed on
.meta cat-stream
previously to a call to
.codn catenated-stream-push ,
those operations were forwarded to the front stream.
If those bytes or characters are still pending,
they are pending inside that stream, and thus
are logically preceded by the contents
of
.metn new-stream .

.coNP Functions @ open-files and @ open-files*
.synb
.mets (open-files < path-list <> [ alternative-stream ])
.mets (open-files* < path-list <> [ alternative-stream ])
.syne
.desc
The
.code open-files
and
.code open-files*
functions create a list of streams by invoking
the open-file function on each element of
.metn path-list .
These streams are turned
into a catenated stream as if applied as arguments to
.codn make-catenated-stream .

The effect is that multiple files appear to be catenated together into a single
input stream.

If the optional
.meta alternative-stream
argument is supplied, then if
.meta path-list
is empty,
.meta alternative-stream
is returned instead of an empty catenated stream.

The difference between
.code open-files
and
.code open-files*
is that
.code open-files
creates all of the
streams up-front. So if any of the paths cannot be opened, the operation throws.
The
.code open-files*
variant is lazy: it creates a lazy list of streams out of the
path list. The streams are opened as needed: before the second stream is opened,
the program has to read the first stream to the end, and so on.

.TP* Example:

Collect lines from all files that are given as arguments on the command line. If
there are no files, then read from standard input:

.cblk
   @(next (open-files *args* *stdin*))
   @(collect)
   @line
   @(end)
.cble

.coNP Function @ abs-path-p
.synb
.mets (abs-path-p << path )
.syne
.desc
The
.code abs-path-function
tests whether the argument
.meta path
is an absolute path, returning a
.code t
or
.code nil
indication.

An absolute path is a string which either begins with a slash or backslash
character, or which begins with an alphanumeric word, followed by a colon,
followed by a slash or backslash.

Examples of absolute paths:

.cblk
  /etc
  c:/tmp
  ftp://user@server
  disk0:/home
  Z:\eUsers
.cble

Examples of strings which are not absolute paths.

.cblk
.mets < (the < empty < string)
  .
  abc
  foo:bar/x
  $:\eabc
.cble

.coNP Functions @ read and @ iread
.synb
.mets (read >> [ source >> [ error-stream >> [ error-retval <> [ name ]]]])
.mets (iread >> [ source >> [ error-stream >> [ error-retval <> [ name ]]]])
.syne
.desc
The
.code read
function converts text denoting \*(TL structure, into the
corresponding data structure. The
.meta source
argument may be either a character
string, or a stream.  If it is omitted, then
.code *stdin*
is used as the stream.

The source must provide the text representation of one complete \*(TL object.

Multiple calls to read on the same stream will extract successive objects
from the stream. To parse successive objects from a string, it is necessary
to convert it to a string stream.

The optional
.meta error-stream
argument can be used to specify a stream to which
parse errors diagnostics are sent. If absent, the diagnostics are suppressed.

The optional
.meta name
argument can be used to specify the file name which is used for reporting
errors. If this argument is missing, the name is taken from the name
property of the
.meta source
argument if it is a stream, or else the word
.code string
is used as the name if
.meta source
is a string.

If there are no parse errors, the function returns the parsed data
structure. If there are parse errors, and the
.meta error-retval
parameter is
present, its value is returned. If the
.meta error-retval
parameter
is not present, then an exception of type
.code syntax-error
is thrown.

The
.code iread
function ("interactive read") is similar to
.code read
except that it parses a modified version of the syntax. The modified
syntax does not support the application of the dot and dotdot operators
on a toplevel expression. For instance, if the input is
.code a.b
or
.code "a .. b"
then
.code iread
will only read the
.code a
token whereas
.code read
will read the entire expression.

This modified syntax allows
.code iread
to return immediately when an expression is recognized, which is the
expected behavior if the input is being read from an interactive terminal.
By contrast,
.code read
waits for more input after seeing a complete expression, because of the
possibility that the expression will be further extended by means of the dot or
dotdot operators. An explicit end-of-input signal must be given from the
terminal to terminate the expression.

.coNP Function @ record-adapter
.synb
.mets (record-adapter < regex >> [ stream <> [ include-match ]])
.syne
.desc
The
.code record-adapter
function returns a new stream object which acts as an
.I adapter
to the existing
.metn stream .

If an argument is not specified for
.metn stream ,
then the
.code *std-input*
stream is used.

With the exception of
.metn get-line ,
all operations on the returned adapter transparently delegate to the original
.meta stream
object.

When the
.code get-line
function is used on the adapter, it behaves differently. A string is
extracted from
.metn stream ,
and returned. However, the string isn't a line delimited by a newline
character, but rather a record delimited by
.metn regex .
This record is extracted as if by a call to the
.code read-until-match
function, invoked with the
.metn regex ,
.meta stream
and
.meta include-match
arguments.

All behavior which is built on the
.code get-lines
functions is affected by the record-delimiting semantics of a record adapter's
.code get-line
implementation. Notably, the
.code get-lines
and
.code lazy-stream-cons
functions return a lazy list of delimited records rather than of lines.

.SS* Stream Output Indentation
\*(TL streams provide support for establishing hanging indentations
in text output. Each stream which supports output has a built-in state variable
called indentation mode, and another variable indicating the current
indentation amount. When indentation mode is enabled, then prior to the
first character of every line, the stream prepends the indentation: space
characters equal in number to the current indentation value.
This logic is implemented by the
.code put-char
and
.code put-string
functions, and all functions based on these. The
.code put-byte
function does not interact with indentation. The column position tracking
will be incorrect if byte and character output are mixed, affecting
the placement of indentation.

Indentation mode takes on three numeric values, given by the three
variables
.codn indent-off ,
.codn indent-data ,
and
.codn indent-code .
As far as stream output is concerned, the code and data modes behave
the same way: both represent the "indentation turned on" state.
The difference between them influences the behavior of the
.code width-check
function. This function isn't used by any stream output routines.
It is used by the object printing functions like
.code print
and
.code pprint
to break up long lines.

.coNP Variables @, indent-off @ indent-data and @ indent-code
.desc
These variables hold integer values representing output stream
indentation modes. The value of
.code indent-off
is zero.

.coNP Functions @, get-indent-mode @ set-indent-mode and @ test-set-indent-mode
.synb
.mets (get-indent-mode << stream )
.mets (set-indent-mode < stream << new-mode )
.mets (test-set-indent-mode < stream < compare-mode << new-mode )
.syne
.desc
These functions retrieve and manipulate the stream indent mode.
The
.code get-indent-mode
retrieves the current indent mode of
.metn stream .

The
.code set-indent-mode
function sets the indent mode of
.meta stream
to
.meta new-mode
and returns the previous mode.

The
.code test-set-indent-mode
function sets the indent mode of
.meta stream
to
.meta new-mode
if, and only if,
its current mode is equal to
.metn compare-mode .
Whether or not it changes the mode, it returns the previous mode.

Note: it is encouraged to save and restore the indentation mode,
and in a way that is exception safe.
If a block of code sets up indentation on a stream such as
.code *stdout*
and is terminated by an exception, the indentation will remain in
effect and affect subsequent output. The
.code with-resources
macro or
.code unwind-protect
operator may be used.

.coNP Functions @, get-indent @ set-indent and @ inc-indent
.synb
.mets (get-indent << stream )
.mets (set-indent < stream << new-indent )
.mets (inc-indent < stream << indent-delta )
.syne
.desc
These functions manipulate the indentation value of the stream.
The indentation takes effect the next time a character is output
following a newline character.

The
.code get-indent
function retrieves the current indentation amount.

The
.code set-indent
function sets
.metn stream 's
indentation to the value
.meta new-indent
and returns the previous value.
Negative values are clamped to zero.

The
.code inc-indent
function sets
.metn stream 's
indentation relative to the current printing column position,
and returns the old value.
The indentation is calculated by adding
.meta indent-delta
to the current column position.
If a negative indentation results, it is clamped to zero.

.coNP Function @ width-check
.synb
.mets (width-check < stream << alt-char )
.syne
.desc
The
.code width-check
function examines the state of the stream, taking into consideration
the current printing column position, the indentation state, and
indentation amount. It makes a decision either to introduce a line
break by printing a newline character, or else to print the
.meta alt-char
character.

If a decision is made not to emit a line break, but
.meta alt-char
is
.codn nil ,
then the function has no effect at all.

The return value is always
.codn t .

.SS* Coprocesses
.coNP Functions @ open-command and @ open-process
.synb
.mets (open-command < system-command <> [ mode-string ])
.mets (open-process < program < mode-string <> [ argument-list ])
.syne
.desc
These functions spawn external programs which execute concurrently
with the \*(TX program. Both functions return a unidirectional stream for
communicating with these programs: either an output stream, or an input
stream, depending on the contents of
.metn mode-string .

In
.codn open-command ,
the
.meta mode-string
argument is optional, defaulting to
the value
.str r
if it is missing.  See the
.code open-file
function for a discussion of modes.

The
.code open-command
function accepts, via the
.meta system-command
string parameter, a
system command, which is in a system-dependent syntax. On a POSIX system, this
would be in the POSIX Shell Command Language.

The
.code open-process
function specifies a program to invoke via the
.meta command
argument. This is subject to the operating system's search strategy.
On POSIX systems, if it is an absolute or relative path, it is treated as
such, but if it is a simple base name, then it is subject to searching
via the components of the PATH environment variable. If open-process
is not able to find
.metn program ,
or is otherwise unable to execute
the program, the child process will exit, using the value of the C variable
.code errno
as its exit status. This value can be retrieved via
.codn close-stream .

The
.meta mode-string
argument follows the convention used by the POSIX
.code popen
function.

The
.meta argument-list
argument is a list of strings which specifies additional
optional arguments to be passed passed to the program. The
.meta program
argument
becomes the first argument, and
.meta argument-string
become the second and
subsequent arguments. If
.meta argument-strings
is omitted, it defaults to empty.

If a coprocess is open for writing
.cblk
.meti >> ( mode-string
.cble
is specified as
.strn w ),
then
writing on the returned stream feeds input to that program's standard input
file descriptor. Indicating the end of input is performed by closing the
stream.

If a coprocess is open for reading
.cblk
.meti >> ( mode-string
.cble
is specified as
.strn r ),
then
the program's output can be gathered by reading from the returned stream.
When the program finishes output, it will close the stream, which can be
detected as normal end of data.

The standard input and error file descriptors of an input coprocess
are obtained from the streams stored in the
.code *stdin*
and
.code *stderr*
special variables, respectively. Similarly, the standard output and error
file descriptors of an output coprocess are obtained from the
.code *stdout*
and
.code *stderr*
special variables.  These variables must contain streams on which the
.code fileno
function is meaningful, otherwise the operation will fail.
What this functionality means is that re-binding the special variables
for standard streams has the effect of redirection. For example,
the following two expressions achieve the same effect of creating
a stream which reads the output of the
.code cat
program, which reads and produces the contents of the file
.codn text-file .

.cblk
  ;; redirect input by rebinding *stdin*
  (let ((*stdin* (open-file "text-file")))
    (open-command "cat"))

  ;; redirect input using POSIX shell redirection syntax
  (open-command "cat < text-file")
.cble

The following is erroneous:

.cblk
  ;; (let ((*stdin* (make-string-input-stream "abc")))
       (open-command "cat"))
.cble

A string input or output stream doesn't have an operating system file
descriptor; it cannot be passed to a coprocess.

The streams
.codn *stdin* ,
.code *stdout*
and
.code *stderr*
are not synchronized with their underlying file descriptors prior to
the execution of a coprocess. It is up to the program to ensure that
previous output to
.code *stdout*
or
.code *stderr*
is flushed, so that the output of the coprocess isn't re-ordered
with regard to output produced by the program. Similarly,
input buffered in
.code *stdin*
is not available to the coprocess, even though it has not
yet been read by the program. The program is responsible for preventing this
situation also.

If a coprocess terminates abnormally or unsuccessfully, an exception is raised.

.SS* Symbols and Packages
A package is an object which serves as a container of symbols.

A symbol which exists inside a package is said to be interned in that package.
A symbol can be interned in at most one package at a time.

Each symbol has a name, which is a string. It is not necessarily unique:
two distinct symbols can have the same name.  However, a symbol name is unique
within a package, because it serves as the key which associates the
symbol with the package. Two symbols cannot be in the same package if they
have the same name.  Moreover, a symbol cannot exist in more than one package
at at time, although it can be relocated from one package to another.  A
symbols exist which is not entered into any package: such a symbol is
called "uninterned".

Packages are held in a global list which can be used to search for a package by
name. The
.code find-package
function performs this lookup.  A package may be
deleted from the list with the
.code delete-package
function, but it continues
to exist until the program loses the last reference to that package.

.coNP Variables @, user-package @ keyword-package and @ system-package
.desc
These variables hold predefined packages. The
.code user-package
is the one
in which symbols are read when a \*(TX program is being scanned.
The
.code keyword-package
holds keyword symbols, which are printed with
a leading colon. The
.code system-package
is for internal symbols, helping
the implementation avoid name clashes with user code in some situations.

.coNP Function @ make-sym
.synb
.mets (make-sym << name )
.syne
.desc
The
.code make-sym
function creates and returns a new symbol object. The argument
.metn name ,
which must be a string, specifies the name of the symbol.  The symbol
does not belong to any package (it is said to be "uninterned").

Note: an uninterned symbol can be interned into a package with the
.code rehome-sym
function. Also see the
.code intern
function.

.coNP Function @ gensym
.synb
.mets (gensym <> [ prefix ])
.syne
.desc
The
.code gensym
function is similar to make-sym. It creates and returns a new
symbol object. If the
.meta prefix
argument is omitted, it defaults to
.strn g .
Otherwise it must be a string.

The difference between
.code gensym
and
.code make-sym
is that
.code gensym
creates the name
by combining the prefix with a numeric suffix.

The numeric suffix is a decimal digit string, taken from the value of
the variable
.codn *gensym-counter* ,
after incrementing it.

Note: the variation in name is not the basis of the uniqueness assurance
offered by
.code make-sym
and
.codn gensym ;
the basis is that the returned symbol is a freshly instantiated object.
.code make-sym
still returns unique symbols even if repeatedly called with the same
string.

.coNP Special variable @ *gensym-counter*
.desc
This variable is initialized to 0. Each time the
.code gensym
function is called,
it is incremented. The incremented value forms the basis of the numeric
suffix which
.code gensym
uses to form the name of the new symbol.

.coNP Function @ make-package
.synb
.mets (make-package << name )
.syne
.desc
The
.code make-package
function creates and returns a package named
.metn name ,
where
.meta name
is a string. It is an error if a package by that name exists already.

.coNP Function @ packagep
.synb
.mets (packagep << obj )
.syne
.desc
The
.code packagep
function returns
.code t
if
.meta obj
is a package, otherwise it returns
.codn nil .

.coNP Function @ find-package
.synb
.mets (find-package << name )
.syne
.desc
The argument
.meta name
should be a string. If a package called
.meta name
exists,
then it is returned. Otherwise
.code nil
is returned.

.coNP Function @ package-alist
.synb
.mets (package-alist)
.syne
.desc
The
.code package-alist
function returns an association list
which contains an entry about each existing
package.

Each element of the list is a cons cell
whose
.code car
field is the name of a package and whose
.code cdr
is a package object.

.coNP Function @ package-name
.synb
.mets (package-name << package )
.syne
.desc
The
.code package-name
function retrieves the name of a package.

.coNP Function @ package-symbols
.synb
.mets (package-symbols << package )
.syne
.desc
The
.code package-symbols
function returns a list of all the symbols
which are interned in
.metn package .

.coNP Function @ intern
.synb
.mets (intern < name <> [ package ])
.syne
.desc
The argument
.meta name
should be a symbol. The optional argument
.meta package
should be a package. If
.meta package
is not supplied, then the value
taken is that of
.codn *user-package* .

The
.code intern
function searches
.meta package
for a symbol called
.metn name .
If that symbol is found, it is returned. If that symbol is not found,
then a new symbol called
.meta name
is created and inserted into
.metn package ,
and that symbol is returned. In this case, the package becomes the
symbol's home package.

.coNP Function @ rehome-sym
.synb
.mets (rehome-sym < symbol <> [ package ])
.syne
.desc
The arguments
.meta symbol
and
.meta package
must be a symbol and package object,
respectively. If
.meta package
is not given, then it defaults to the value of
.codn *user-package* .

The
.code rehome-sym
function moves
.meta symbol
into
.metn package .
If
.meta symbol
is already in a package, it is first removed from that package.
If a symbol of the same name exists in
.meta package
that symbol is first removed
from
.metn package .

.coNP Function @ symbolp
.synb
.mets (symbolp << obj )
.syne
.desc
The
.code symbolp
function returns
.code t
if
.meta obj
is a symbol, otherwise it returns
.codn nil .

.coNP Function @ symbol-name
.synb
.mets (symbol-name << symbol )
.syne
.desc
The
.code symbol-name
function returns the name of
.metn symbol .

.coNP Function @ symbol-package
.synb
.mets (symbol-package << symbol )
.syne
.desc
The
.code symbol-package
function returns the home package of
.metn symbol .

.coNP Function @ keywordp
.synb
.mets (keywordp << obj )
.syne
.desc
The
.code keywordp
function returns
.code t
if
.meta obj
is a keyword symbol, otherwise it
returns
.codn nil .

.coNP Function @ bindable
.synb
.mets (bindable << obj )
.syne
.desc
The
.code bindable
function returns
.code t
if
.meta obj
is a bindable symbol, otherwise it returns
.codn nil .

All symbols are bindable, except for keyword symbols, and the
special symbols
.code t
and
.codn nil .

.SS* Pseudo-random Numbers
.coNP Special variable @ *random-state*
.desc
The
.code *random-state*
variable holds an object which encapsulates the state
of a pseudo-random number generator. This variable is the default argument
value for the
.code random-fixnum
and
.codn "random functions" ,
for the convenience of writing programs which are not concerned about the
management of random state.

On the other hand, programs can create and manage random states, making it
possible to obtain repeatable sequences of pseudo-random numbers which do not
interfere with each other. For instance objects or modules in a program can
have their own independent streams of random numbers which are repeatable,
independently of other modules making calls to the random number functions.

When \*(TX starts up, the
.code *random-state*
variable is initialized with
a newly created random state object, which is produced as if by
the call
.codn "(make-random-state 42)" .

.coNP Special variable @ *random-warmup*
.desc
The
.code *random-warmup*
special variable specifies the value which is used by
.code make-random-state
in place of a missing
.meta warmup-period
argument.

To "warm up" a pseudo-random number generator (PRNG) means to obtain some
values from it which are discarded, prior to use.  The number of values
discarded is the
.IR "warm-up period" .

The WELL PRNG used in \*(TX produces 32-bit values, natively. Thus each
warm-up iteration retrieves and discards a 32-bit value. The PRNG has
a state space consisting of a vector of sixteen 32-bit words, making
the state space 4096 bits wide.

Warm up is required because PRNG-s, in particular PRNG-s with large state
spaces and long periods, produce fairly predictable sequences of values in the
beginning, before transitioning into chaotic behavior. This problem is worse
for low complexity seeds, such as small integer values.

The sequences are predictable in two ways. Firstly, some initial values
extracted from the PRNG may exhibit patterns ("problem 1"). Secondly, the initial values
from sequences produced from similar seeds (for instance consecutive integers)
may be similar or identical ("problem 2").

.TP* Notes:

The default value of .code *random-warmup* is only 8.  This is insufficient to
ensure good initial PRNG behavior for seeds even as large as 64 bits or more.
That is to say, even if as many as eight bytes' worth of true random bits are
used as the seed, the PRNG will exhibit predictable behaviors, and a poor
distribution of values.

Applications which critically depend on good PRNG behavior should choose
large warm-up periods into the hundreds or thousands of iterations.
If a small warm-up period is used, it is recommended to use larger seeds
which initialize more of the 4096 bit state space.

\*(TX's PRNG implementation addresses "problem 1" first problem by padding the
unseeded portions of the state space with random values (from a static table
that doesn't change). For instance, if the integer 1 is used to seed the space,
then one 32 bit word of the space is set to the value 1. The remaining 15 are
populated from the random table. This helps to ensure that a good PRNG sequence
is obtained immediately. However, it doesn't address "problem 2": that
similar seed values generate similar sequences, when the warm-up period is
small. For instance, if 65536 different random state objects are created, from
each of the 16-bit seeds in the range [0, 65536), and then a random 16-bit
value is extracted from each state, only 1024 unique values result.

.coNP Function @ make-random-state
.synb
.mets (make-random-state >> [ seed <> [ warmup-period ])
.syne
.desc
The
.code make-random-state
function creates and returns a new random state,
an object of the same kind as what is stored in the
.code *random-state*
variable.

The seed, if specified, must be either an integer value, an
existing random state object, or a vector returned from a call
to the function
.codn random-state-get-vec .

Note that the sign of the seed is ignored, so that negative seed
values are equivalent to their additive inverses.

If seed is not specified, then
.code make-random-state
produces a seed based
on some information in the process environment, such as current
time of day. It is not guaranteed that two calls to
.code (make-random-state)
that are separated by less than some minimum increment of real time produce
different seeds.  The minimum time increment depends on the platform.

On a platform with a millisecond-resolution real-time clock, the minimum
time increment is a millisecond. Calls to make-random-state less than
a millisecond apart may predictably produce the same seed.

If an integer seed is specified, then the integer value is mapped to a
pseudo-random sequence, in a platform-independent way.

If an existing random state is specified as a seed, then it is duplicated. The
returned random state object is a distinct object which is in the same
state as the input object. It will produce the same remaining pseudo-random
number sequence, as will the input object.

If a vector is specified as a seed, then a random state is constructed
which duplicates the random state object which was captured in that vector
representation by the
.code random-state-get-vec
function.

The
.meta warm-up-period
argument specifies the number of values which are immediately obtained and
discarded from the newly-seeded generator before it is returned.
Warm-up is not performed when
.meta seed
is an existing random state object, and this argument is ignored in that
case. If the parameter is required, but the argument is missing, then
the value of the
.code *random-warmup*
special variable is used. This variable has a default value which may be too
small for serious applications of pseudo-random numbers; see the Notes under
.codn *random-warmup* .

.coNP Function @ random-state-p
.synb
.mets (random-state-p << obj )
.syne
.desc
The
.code random-state-p
function returns
.code t
if
.meta obj
is a random state, otherwise it
returns
.codn nil .

.coNP Function @ random-state-get-vec
.synb
.mets (random-state-get-vec <> [ random-state ])
.syne
.desc
The
.code random-state-get-vec
function converts a random state into a vector of integer values.
If the
.meta random-state
argument, which must be a random state object, is omitted,
then the value of the
.code *random-state*
is used.

.coNP Functions @, random-fixnum @ random and @ rand
.synb
.mets (random-fixnum <> [ random-state ])
.mets (random < random-state << modulus )
.mets (rand < modulus <> [ random-state ])
.syne
.desc
All three functions produce pseudo-random numbers, which are positive integers.

The numbers are obtained from a WELL 512 PRNG, whose state is stored in the
random state object.

The
.code random-fixnum
function produces a random fixnum integer: a reduced range
integer which fits into a value that does not have to be heap-allocated.

The
.code random
and
.code rand
functions produce a value in the range [0,
.metn modulus ).
They differ only in the order of arguments. In the
.code rand
function, the random state
object is the second argument and is optional. If it is omitted, the global
.code *random-state*
object is used.

The
.meta modulus
argument must be a positive integer. If
.meta modulus
is 1, then the function returns zero without altering the state of the
pseudo-random number generator.

.SS* Time
.coNP Functions @ time and @ time-usec
.synb
.mets (time)
.mets (time-usec)
.syne
.desc
The
.code time
function returns the number of seconds that have elapsed since
midnight, January 1, 1970, in the UTC timezone: a point in
time called
.IR "the epoch" .

The
.code time-usec
function returns a cons cell whose
.code car
field holds the seconds measured in the same way, and whose
.code cdr
field extends the precision by giving
number of microseconds as an integer value between 0 and 999999.

.coNP Functions @ time-string-local and @ time-string-utc
.synb
.mets (time-string-local < time << format )
.mets (time-string-utc < time << format )
.syne
.desc
These functions take the numeric time returned by the
.code time
function, and convert it to a textual representation in a flexible way,
according to the contents of the
.meta format
string.

The
.code time-string-local
function converts the time to the local timezone of
the host system. The
.code time-string-utc
function produces time in UTC.

The
.meta format
argument is a string, and follows exactly the same conventions as
the format string of the C library function
.codn strftime .

The
.meta time
argument is an integer representing seconds obtained from the
time function or from the
.code car
field of the cons returned by the
.code time-usec
function.

.coNP Functions @ time-fields-local and @ time-fields-utc
.synb
.mets (time-fields-local << time )
.mets (time-fields-utc << time )
.syne
.desc
These functions take the numeric time returned by the time function,
and convert it to a list of seven fields.

The
.code time-string-local
function converts the time to the local timezone of
the host system. The
.code time-string-utc
function produces time in UTC.

The fields returned as a list consist of six integers, and a Boolean value.
The six integers represent the year, month, day, hour, minute and second.
The Boolean value indicates whether daylight savings time is in effect
(always
.code nil
in the case of
.codn time-fields-utc ).

The
.meta time
argument is an integer representing seconds obtained from the
.code time
function or from the
.code time-usec
function.

.coNP Structure @ time
.synb
  (defstruct time nil
    year month day hour min sec dst)
.syne
.desc
The
.code time
structure represents a time broken down into individual fields.
The structure almost directly corresponds to the
.code "struct tm"
type in the ISO C language.  There are differences.
Whereas the
.code "struct tm"
member
.code tm_year
represents a year since 1900, the
.code year
slot of the
.code time
structure represents the absolute year, not relative to 1900.
Furthermore, the
.code month
slot represents a one-based numeric month, such that 1 represents
January, whereas the C member
.code tm_mon
uses a zero-based month.  The
.code dst
slot is a \*(TL Boolean value. The remaining slots
.codn hour ,
.codn min ,
and
.code sec
correspond directly to
.codn tm_hour ,
.codn tm_min ,
and
.codn tm_sec .

.coNP Functions @ time-struct-local and @ time-struct-utc
.synb
.mets (time-struct-local << time )
.mets (time-struct-utc << time )
.syne
.desc
These functions take the numeric time returned by the time function,
and convert it to an instance of the
.code time
structure.

The
.code time-struct-local
function converts the time to the local timezone of
the host system. The
.code time-struct-utc
function produces time in UTC.

The
.meta time
argument is an integer representing seconds obtained from the
.code time
function or from the
.code time-usec
function.

.coNP Methods @ time-local and @ time-utc
.synb
.mets << time-struct .(time-local)
.mets << time-struct .(time-utc)
.syne
.desc
The
.code time
structure has two methods called
.code time-local
and
.codn time-utc .

The
.code time-local
function considers the slots of the
.code time
structure instance
.meta time-struct
to be local time, and returns its integer representation
as the number of seconds since the epoch.

The
.code time-utc
function is similar, except it considers
the slots of
.meta time-struct
to be in the UTC time zone.

Note: these functions work by converting the slots into arguments
which are applied to
.code make-time
or
.codn make-time-utc .

.coNP Functions @ make-time and @ make-time-utc
.synb
.mets (make-time < year < month < day < hour < minute < second << dst-advice )
.mets (make-time-utc < year < month < day < hour < minute < second << dst-advice )
.syne
.desc
The
.code make-time
function returns a time value, similar to the one returned by the
.code time
function.  The
.code time
value is constructed not from the system clock, but
from a date and time specified as arguments. The
.meta year
argument is a calendar year, like 2014.
The
.meta month
argument ranges from 1 to 12.
The
.meta hour
argument is a 24-hour time, ranging from 0 to 23.
These arguments represent a local time, in the current time zone.

The
.meta dst-advice
argument specifies whether the time is expressed in
daylight savings time (DST). It takes on three possible values:
.codn nil ,
the keyword
.codn :auto ,
or else the symbol
.codn t .
Any other value has the same interpretation as
.codn t .

If
.meta dst-advice
is
.codn t ,
then the time is assumed to be expressed in DST.
If the argument is
.codn nil ,
then the time is assumed not to be in DST.
If
.meta dst-advice
is
.codn :auto ,
then the function tries to determine whether
DST is in effect in the current time zone for the specified date and time.

The
.code make-time-utc
function is similar to
.codn make-time ,
except that
it treats the time as UTC rather than in the local time zone.
The
.meta dst-advice
argument is supported by
.code make-time-utc
for function
call compatibility with
.codn make-time .
It may or may not have any effect
on the output (since the UTC zone by definition doesn't have daylight
savings time).

.SS* Environment Variables and Command Line

Note that environment variable names, their values, and command line
arguments are all regarded as being externally encoded in UTF-8. \*(TX performs
the encoding and decoding automatically.

.coNP Special variables @ *args* and @ *args-full*
.desc
The
.code *args*
variable holds a list of strings representing the remaining
arguments which follow any options processed by the \*(TX executable,
and the script name.

The
.code *args-full*
variable holds the original, complete list of arguments passed
from the operating system.

The
.code *args*
variable is available to to \*(TL expressions invoked from the
command line via the
.codn -p ,
.code -e
and other such options. During these evaluations,
.code *args*
holds all the remaining options, after the invoking option and its
argument expression. In other words, code executed from the command line
has access to the remaining arguments which follow it.
Furthermore, this code may modify the value of
.codn *args* .
Such a modification is visible to the option processing code.
That is to say code executed from the command line can rewrite the remaining
list of arguments, and that list takes effect.

.coNP Function @ env
.synb
.mets (env)
.syne
.desc
The
.code env
function retrieves the list of environment variables. Each
variable is represented by a single entry in the list: a string which
contains an
.code =
(equal) character somewhere, separating the variable name
from its value.

See also: the
.code env-hash
function.

.coNP Function @ env-hash
.synb
.mets (env-hash)
.syne
.desc
The
.code env-hash
function constructs and returns an
.code :equal-based
hash.  The hash is
populated with the environment variables, represented as key-value pairs. 

.coNP Functions @, getenv @ setenv and @ unsetenv
.synb
.mets (getenv << name )
.mets (setenv < name < value <> [ overwrite-p ])
.mets (unsetenv << name )
.syne
.desc
These functions provide access to, as well as manipulation of, environment
variables. Of these three,
.code setenv
and
.code unsetenv
might not be available on some platforms, or
.code unsetenv
might be be present in a simulated form which sets the variable
.meta name
to the empty string rather than deleting it.

The
.code getenv
function searches the environment for the environment variable whose name
is
.metn name .
If the variable is found, its value is returned. Otherwise
.code nil
is returned.

The
.code setenv
function creates or modifies the environment variable indicated by
.metn name .
The
.meta value
string argument specifies the new value for the variable.
If
.meta value
is
.codn nil ,
then
.code setenv
behaves like
.codn unsetenv ,
except that it observes the
.meta overwrite-p
argument. That is to say, the meaning of a null
.meta value
is that the variable is to be removed.

If the
.meta overwrite-p
argument is specified, and is true,
then the variable is overwritten if it already exists.
If the argument is false, then the variable is not modified if it
already exists.  If the argument is not specified, it defaults
to the value
.metn t ,
effectively giving rise to a two-argument form of
.code setenv
which creates or overwrites environment variables.

A variable removal is deemed to be an overwrite.
Thus if both
.meta value
and
.meta overwrite-p
are
.codn nil ,
then
.code setenv
does nothing.

The
.code setenv
function unconditionally returns
.meta value
regardless of whether or not it overwrites or removes an existing variable.

The
.code unsetenv
function removes the environment variable
specified by
.metn name ,
if it exists. On some platforms, it instead sets the environment variable
to the empty string.

Note: supporting removal semantics in
.code setenv
allows for the following simple save/modify/restore pattern:

.cblk
  (let* ((old-val (getenv "SOME-VAR")))
    (unwind-protect
      (progn (setenv "SOME-VAR" new-val)
             ...)
      (setenv "SOME-VAR" old-val)))
.cble

This works in the case when
.code SOME-VAR
exists, as well as in the case that it doesn't exist.
In both cases, its previous value or, respectively, non-existence,
is restored by the
.code unwind-protect
cleanup form.

.SS* System Programming
.coNP Accessor @ errno
.synb
.mets (errno <> [ new-errno ])
.mets (set (errno) << new-value )
.syne
.desc
The
.code errno
function retrieves the current value of the C library error variable
.codn errno .
If the argument
.meta new-errno
is present and is not
.codn nil ,
then it
specifies a value which is stored into
.codn errno .
The value returned is the prior value.

The place form of
.code errno
does not take an argument.

.coNP Function @ exit
.synb
.mets (exit << status )
.syne
.desc
The
.code exit
function terminates the entire process (running \*(TX image), specifying
the termination status to the operating system. Values of
.meta status
may be
.codn nil ,
.codn t ,
or an integer value.  The value
.code nil
corresponds to the C constant
.codn EXIT_FAILURE ,
and
.code t
corresponds to
.codn EXIT_SUCCESS .
These are platform-independent
indicators of failed or successful termination. The numeric value 0 also
indicates success.

.coNP Function @ abort
.synb
.mets (abort)
.syne
.desc
The
.code abort
function terminates the entire process (running \*(TX image), specifying
an abnormal termination status to the process.

Note:
.code abort
calls the C library function
.code abort
which works by raising the
.code SIG_ABRT
signal, known in \*(TX as the
.code sig-abrt
variable. Abnormal termination of the process is this signal's
default action.

.coNP Functions @ at-exit-call and @ at-exit-do-not-call
.synb
.mets (at-exit-call << function )
.mets (at-exit-do-not-call << function )
.syne
.desc
The
.code at-exit-call
function registers
.meta function
to be called when the process terminates normally.
Multiple functions can be registered, and the same function
can be registered more than once. The registered
functions are called in reverse order of their
registrations.

The
.code at-exit-do-not-call
function removes all previous
.code at-exit-call
registrations of
.metn function .

The
.code at-exit-call
function returns
.metn function .

The
.code at-exit-do-not-call
function returns
.code t
if it removed anything,
.code nil
if no registrations of
.meta function
were found.

.coNP Function @ usleep
.synb
.mets (usleep << usec )
.syne
.desc
The
.code usleep
function suspends the execution of the program for at least
.meta usec
microseconds.

The return value is
.code t
if the sleep was successfully executed. A
.code nil
value indicates premature wakeup or complete failure.

Note: the actual sleep resolution is not guaranteed, and depends on granularity
of the system timer.  Actual sleep times may be rounded up to the nearest 10
millisecond multiple on a system where timed suspensions are triggered by a 100
Hz tick.

.coNP Functions @ mkdir and @ ensure-dir
.synb
.mets (mkdir < path <> [ mode ])
.mets (ensure-dir < path <> [ mode ])
.syne
.desc
.code mkdir
tries to create the directory named
.meta path
using the POSIX
.code mkdir
function.
An exception of type
.code file-error
is thrown if the function fails. Returns
.code t
on success.

The
.meta mode
argument specifies the request numeric permissions
for the newly created directory. If omitted, the requested permissions are
.code #o777
(511): readable and writable to everyone. The requested permissions
are subject to the system
.codn umask .

The function
.code ensure-dir
is similar to
.code mkdir
except that it attempts to create all the missing parent directories
as necessary, and does not throw an error if the directory exists.

.coNP Function @ chdir
.synb
.mets (chdir << path )
.syne
.desc
.code chdir
changes the current working directory to
.metn path ,
and returns
.metn t ,
or else throws an exception of type
.codn file-error .

.coNP Function @ pwd
.synb
.mets (pwd)
.syne
.desc
The
.code pwd
function retrieves the current working directory.
If the underlying
.code getcwd
C library function fails with an
.code errno
other than
.codn ERANGE ,
an exception will be thrown.

.coNP Function @ remove-path
.synb
.mets (remove-path < path <> [ throw-on-error-p ])
.syne
.desc
The
.code remove-path
function tries to remove the filesystem object named
by
.metn path ,
which may be a file, directory or something else.

If successful, it returns
.codn t .

A failure to remove the object results in an exception of type
.codn file-error ,
unless
.meta throw-on-error-p
is present, and its value is
.codn nil .
In that case, failure is indicated by a
.code nil
return value.

.coNP Function @ rename-path
.synb
.mets (rename-path < from-path << to-path )
.syne
.desc
The
.code remove-path
function tries to rename filesystem path
.metn from-path ,
which may refer to a file, directory or something else, to the path
.metn to-path .

If successful, it returns
.codn t .

A failure results in an exception of type
.codn file-error .

.coNP Functions @ sh and @ run
.synb
.mets (sh << system-command )
.mets (run < program <> [ argument-list ])
.syne
.desc
The
.code sh
function executes
.meta system-command
using the system command interpreter.
The run function spawns a
.metn program ,
searching for it using the
system PATH.  Using either method, the executed process receives environment
variables from the parent.

\*(TX blocks until the process finishes executing. If the program terminates
normally, then its integer exit status is returned. The value zero indicates
successful termination.

The return value
.code nil
indicates an abnormal termination, or the inability
to run the process at all.

In the case of the
.code run
function, if the child process is created successfully
but the program cannot be executed, then the exit status will be an
.code errno
value from the failed
.code exec
attempt.

The standard input, output and error file descriptors of an executed
command are obtained from the streams stored in the
.codn *stdin* ,
.code *stdout*
and
.code *stderr*
special variables, respectively. For a detailed description of the
behavior and restrictions, see the
.code open-command
function, whose description of this mechanism applies to the
.code run
and
.code sh
function also.

Note: as of \*(TX 120, the
.code sh
function is implemented using
.code run
and not by means of the
.code system
C library function, as previously. The
.code run
function is used to invoke the system interpreter by name. On Unix-like
systems, the string
.code /bin/sh
is assumed to denote the system interpreter, which is expected to
support a pair of arguments
.cblk
.meti -c < command
.cble
to specify the command to be executed. On MS Windows, the interpreter
is assumed to be the relative path name
.code cmd.exe
and expected to support
.cblk
.meti /C < command
.cble
as a way of specifying a command to execute.

.SS* Unix Filesystem Manipulation

.coNP Structure @ stat
.synb
.mets (defstruct stat nil
.mets \ \  dev ino mod nlink uid gid
.mets \ \  rdev size blksize blocks atime
.mets \ \  mtime ctime)
.syne
.desc
The
.code stat
structure defines the type of object which is returned
by the
.codn stat ,
.codn lstat ,
and
.code fstat
functions.  The slots are the direct counterparts of the
members of POSIX C structure
.codn "struct stat" .
For instance the slot
.code dev
corresponds to
.codn st_dev .

.coNP Functions @, stat @ lstat and @ fstat
.synb
.mets (stat << path )
.mets (lstat << path )
.mets (fstat << stream )
.syne
.desc
The
.code stat
function inquires the filesystem about the existence of an object
denoted by the string
.metn path .
If the object is not found or cannot be
accessed, an exception is thrown.

Otherwise, information is retrieved about the object. The information takes
the form of a structure of type
.codn stat .

If
.meta path
refers to a symbolic link, the
.code stat
function retrieves information about the target of the link, if it exists,
or else throws an exception of type
.codn file-error .

The
.code lstat
function behaves the same as
.code stat
or objects which are not symbolic links. For a symbolic link, it retrieves
information about the link itself, rather than its target.

The
.code fstat
function retrieves information about the file system object associated with
the open stream
.metn stream .
The stream must be of a kind from which the
.code fileno
function can retrieve a file descriptor, otherwise an exception of type
.code file-error
is thrown.

.coNP Variables @, s-ifmt @, s-iflnk @, s-ifreg @, s-ifblk ... , @ s-ixoth
.desc
The following variables exist, having integer values. These are bitmasks
which can be applied against the value given by the
.code mode
slot of the
.code stat
structure returned by the function
.codn stat :
.codn s-ifmt ,
.codn s-ifsock ,
.codn s-iflnk ,
.codn s-ifreg ,
.codn s-ifblk ,
.codn s-ifdir ,
.codn s-ifchr ,
.codn s-ififo ,
.codn s-isuid ,
.codn s-isgid ,
.codn s-isvtx ,
.codn s-irwxu ,
.codn s-irusr ,
.codn s-iwusr ,
.codn s-ixusr ,
.codn s-irwxg ,
.codn s-irgrp ,
.codn s-iwgrp ,
.codn s-ixgrp ,
.codn s-irwxo ,
.codn s-iroth ,
.code s-iwoth
and
.codn s-ixoth .

These variables correspond to the C language constants from POSIX:
.codn S_IFMT ,
.codn S_IFLNK ,
.code S_IFREG
and so forth.

The
.code logtest
function can be used to test these against values of mode.
For example
.code "(logtest mode s-irgrp)"
tests for the group read permission.

.coNP Function @ umask
.synb
.mets (umask << mask )
.syne
.desc
The
.code umask
function provides access to the Unix C library function of the same name,
which controls which permissions are denied
when files are newly created. If
.meta mask
is a
.code fixnum
integer, this succeeds and returns
.codn t .

.coNP Functions @, makedev @ minor and @ major
.synb
.mets (makedev < minor << major )
.mets (minor << dev )
.mets (major << dev )
.syne
.desc
The parameters
.metn minor ,
.meta major
and
.meta dev
are all integers.  The
.code makedev
function constructs a combined device number from a minor and major pair (by
calling the Unix
.code makedev
function).  This device number is suitable as an
argument to the
.code mknod
function (see below). Device numbers also appear as values of the
.code dev
slot of the
.code stat
structure.

The
.code minor
and
.code major
functions extract the minor and major device number
from a combined device number.

.coNP Function @ chmod
.synb
.mets (chmod < path << mode )
.syne
.desc
The
.code chmod
function changes the permissions of the filesystem objects
specified by
.metn path .
It is a direct wrapper for the POSIX C library function of the same name.

The permissions are specified by
.metn mode ,
an integer argument.

The existing permissions may be obtained using the
.code stat
function.

The function throws a
.code file-error
exception if an error occurs, otherwise it returns
.codn t .

.TP* Example:
.cblk
  ;; Set permissions of foo.txt to "rw-r--r--"
  ;; (owner can read and write; group owner
  ;; and other users can only read).

  ;; numerically:
  (chmod "foo.txt" #o644)

  ;; symbolically:
  (chmod "foo.txt" (logior s-irusr s-iwusr
                           s-irgrp
                           s-iroth))
.cble

.coNP Function @ mknod
.synb
.mets (mknod < path < mode <> [ dev ])
.syne
.desc
The
.code mknod
function tries to create an entry in the filesystem: a file,
FIFO, or a device special file, under the name
.metn path .
If it is successful,
it returns
.codn t ,
otherwise it throws an exception of type
.codn file-error .

The
.meta mode
argument is a bitwise or combination of the requested permissions,
and the type of object to create: one of the constants
.codn s-ifreg ,
.codn s-ififo ,
.codn s-ifchr ,
.code s-ifblk
or
.codn s-ifsock .
The permissions are subject to the system
.codn umask .

If a block or character special device
.cod2 ( s-ifchr
or
.codn s-ifblk )
is being
created, then the
.meta dev
argument specifies the major and minor numbers
of the device. A suitable value can be constructed from a major and minor
pair using the
.code makedev
function.

.TP* Example:

.cblk
   ;; make a character device (8, 3) called /dev/foo
   ;; requesting rwx------ permissions

   (mknod "dev/foo" (logior #o700 s-ifchr) (makedev 8 3))
.cble

.coNP Functions @ symlink and @ link
.synb
.mets (symlink < target << path )
.mets (link < target << path )
.syne
.desc
The
.code symlink
function creates a symbolic link called
.meta path
whose contents
are the absolute or relative path
.metn target .
.meta target
does not actually have to exist.

The link function creates a hard link. The object at
.meta target
is installed
into the filesystem at
.meta path
also.

If these functions succeed, they return
.codn t .
Otherwise they throw an exception
of type
.codn file-error .

.coNP Function @ readlink
.synb
.mets (readlink << path )
.syne
.desc
If
.meta path
names a filesystem object which is a symbolic link, the
.code readlink
function reads the contents of that symbolic link and returns it
as a string.  Otherwise, it fails by throwing an exception of type
.codn file-error .

.SS* Unix Filesystem Object Existence, Type and Access Tests

The following functions all accept, as the
.meta path
argument, either a character string, or a structure returned by the
.code stat
or
.code lstat
functions.

If the
.meta path
argument is a string, then
.code stat
is used to retrieve information about it, except in the case of
the
.code path-symlink-p
function, which uses
.codn lstat .
The subsequent test is then based on the result of this call.

If the
.meta path
argument is the result of a
.code stat
or
.code lstat
call, then the testing is based on that object.

Some of the accessibility tests (functions which determine whether the
calling process has certain access rights) may not be perfectly accurate, since
they are based strictly on portable information available via
.codn stat ,
together with the basic, portable POSIX APIs for inquiring about
security credentials, such as
.codn geteuid .
They ignoring any special permissions which may exist such as operating system
and file system specific extended attributes (for example, file immutability
connected to a "secure level" and such) and special process capabilities
not reflected in the basic credentials.

.coNP Function @ path-exists-p
.synb
.mets (path-exists-p << path )
.syne
.desc
The
.code path-exists-p
function returns
.code t
if
.meta path
is a string which resolves to a filesystem object.
Otherwise it returns
.codn nil .
If the
.meta path
names a dangling symbolic link, it is considered nonexistent.

If
.meta path
is an object returned by
.code stat
or
.codn lstat ,
.code path-exists-p
unconditionally returns
.codn t .

.coNP Functions @, path-file-p @, path-dir-p @, path-symlink-p @, path-blkdev-p @, path-chrdev-p @ path-sock-p and @ path-pipe-p
.synb
.mets (path-file-p << path )
.mets (path-dir-p << path )
.mets (path-symlink-p << path )
.mets (path-blkdev-p << path )
.mets (path-chrdev-p << path )
.mets (path-sock-p << path )
.mets (path-pipe-p << path )
.syne
.desc
.code path-file-p
tests whether
.meta path
exists and is a regular file.

.code path-dir-p
tests whether
.meta path
exists and is a directory.

.code path-symlink-p
tests whether
.meta path
exists and is a symbolic link.

Similarly,
.code path-blkdev-p
tests for a block device,
.code path-chrdev-p
for a character device,
.code path-sock-p
for a socket and
.code path-pipe-p
for a named pipe.

.coNP Functions @, path-setgid-p @ path-setuid-p and @ path-sticky-p
.synb
.mets (path-setgid-p << path )
.mets (path-setuid-p << path )
.mets (path-sticky-p << path )
.syne
.desc
.code path-setgid-p
tests whether
.meta path
exists and has the set-group-ID permission set.

.code path-setuid-p
tests whether
.meta path
exists and has the set-user-ID permission set.

.code path-sticky-p
tests whether
.meta path
exists and has the "sticky" permission bit set.

.coNP Functions @ path-mine-p and @ path-my-group-p
.synb
.mets (path-mine-p << path )
.mets (path-my-group-p << path )
.syne
.desc
.code path-mine-p
tests whether
.meta path
exists, and is effectively owned by the calling process; that is,
has a user ID equal to the effective user ID of the process.

.code path-my-group-p
tests whether
.meta path
exists, and is effectively owned by a group to which the calling process
belongs. This means that the group owner is either the same as the
effective group ID of the calling process, or else is among the
supplementary group IDs of the calling process.

.coNP Function @ path-readable-to-me-p
.synb
.mets (path-readable-to-me-p << path )
.syne
.desc
.code path-readable-to-me-p
tests whether the calling process can read the
object named by
.metn path .
If necessary, this test examines the effective user ID of the
calling process, the effective group ID, and the list of supplementary groups.

.coNP Function @ path-writable-to-me-p
.synb
.mets (path-writable-to-me-p << path )
.syne
.desc
.code path-writable-to-me-p
tests whether the calling process can write the
object named by
.metn path .
If necessary, this test examines the effective user ID of the
calling process, the effective group ID, and the list of supplementary groups.

.coNP Function @ path-read-writable-to-me-p
.synb
.mets (path-read-writable-to-me-p << path )
.syne
.desc
.code path-readable-to-me-p
tests whether the calling process can both read and write the
object named by
.metn path .
If necessary, this test examines the effective user ID of the
calling process, the effective group ID, and the list of supplementary groups.

.coNP Function @ path-executable-to-me-p
.synb
.mets (path-executable-to-me-p << path )
.syne
.desc
.code path-executable-to-me-p
tests whether the calling process can execute the
object named by
.metn path ,
or perform a search (name lookup, not implying sequential readability) on it,
if it is a directory.
If necessary, this test examines the effective user ID of the
calling process, the effective group ID, and the list of supplementary groups.

.coNP Functions @ path-private-to-me-p and @ path-strictly-private-to-me-p
.synb
.mets (path-private-to-me-p << path )
.mets (path-strictly-private-to-me-p << path )
.syne
.desc
The
.code path-private-to-me-p
function reports whether the calling process can rely on the
object indicated by
.code path
to be, respectively, private or strictly private to the security context
implied by its effective user ID.

"Private" means that beside the effective user ID of the calling process and
the superuser, no other user ID has write access to the object, and thus its
contents may be trusted to be be free from tampering by any other user.

"Strictly private" means that not only is the object private, as above,
but users other than the effective user ID of the calling process
and superuser also not not have read access.

The rules which the function applies are as follows:

A file to be examined is initially assumed to be strictly private.

If the file is not owned by the effective user ID of the caller, then
it is not private.

If the file grants write permission to "others", then it is not private.

If the file grants read permission to "others", then it is not strictly
private.

If the file grants write permission to the group owner, then it is not
private, unless either the group is empty, or else the group has exactly one
member, who is the owner of the file.

If the file grants read permission to the group owner, then it is not
strictly private, unless either the group is empty, or else the group has
exactly one member, who is the owner of the file.

Note that this interpretation of "private" and "strictly private" is vulnerable
to the following time-of-check to time-of-use race condition with regard to the
group check.  At the time of the check, the group might be empty or contain
only the caller as a member. But by the time the file is subsequently accessed,
the group might have been innocently extended by the system administrator to
include additional users, who can maliciously modify the file.

Also note that the function is vulnerable to a time-of-check to time-of-use
race if
.meta path
is a string rather than a
.code stat
structure. If the directory which contains the file is writable to others, the
file can pass the check at the time the function is called, but before it is
used, the file can be replaced by another file with different permissions.
To guard against this race, one must open the file, and then use
.code fstat
on the stream, using the structure returned by fstat to perform the check,
with the understanding that it applies only to the open file, and not
necessarily to whatever object may now be retrieved by the original
directory entry.

.coNP Functions @ path-newer and @ path-older
.synb
.mets (path-newer < left-path << right-path )
.mets (path-older < left-path << right-path )
.syne
.desc
The
.code path-newer
function compares two paths or stat results by modification time.
It returns
.code t
if
.meta left-path
exists, and either
.meta right-path
does not exist, or has a modification time stamp in the past
relative to
.metn left-path .

The
.code path-older
function is equivalent to
.code path-newer
with the arguments reversed.

.coNP Function @ path-same-object
.synb
.mets (path-same-object < left-path << right-path )
.syne
.desc
The
.code path-same-object
function returns
.code t
if
.meta left-path
and
.meta right-path
resolve to the same filesystem object: the same inode number on the same
device.

.SS* Unix Credentials

.coNP Functions @, getuid @, geteuid @ getgid and @ getegid
.synb
.mets (getuid)
.mets (geteuid)
.mets (getgid)
.mets (getegid)
.syne
.desc
These functions directly correspond to the POSIX C library functions
of the same name. They retrieve the real user ID, effective user ID,
real group ID and effective group ID, respectively, of the calling
process.

.coNP Functions @, setuid @, seteuid @ setgid and @ setegid
.synb
.mets (setuid << uid )
.mets (seteuid << uid )
.mets (setgid << gid )
.mets (setegid << gid )
.syne
.desc
These functions directly correspond to the POSIX C library functions
of the same name. They set the real user ID, effective user ID,
real group ID and effective group ID, respectively, of the calling
process.
On success, they return
.codn t .
On failure, they throw an exception of type
.codn system-error .

.coNP Function @ getgroups
.synb
.mets (getgroups)
.syne
.desc
The
.code getgroups
function retrieves the list of supplementary group IDs of the calling
process by calling the same-named POSIX C library function.

Whether or not the effective group ID retrieved by
.code getegid
is included in this list is system-dependent. Programs should not
depend on its presence or absence.

.coNP Function @ setgroups
.synb
.mets (setgroups << gid-list )
.syne
.desc
The
.code setgroups
function corresponds to a C library function found in some Unix
operating systems, complementary to the
.code getgroups
function. The argument to
.meta gid-list
must be a list of numeric group IDs.
If the function is successful, this list is installed as the list of
supplementary group IDs of the calling process, and the value
.code t
is returned.
On failure, it throws an exception of type
.codn system-error .

.coNP Functions @ getresuid and @ getresgid
.synb
.mets (getresuid)
.mets (getresgid)
.syne
.desc
These functions directly correspond to the POSIX C library functions
of the same names available in some Unix operating systems.
Each function retrieves a three element list of numeric IDs.
The
.code getresuid
function retrieves the real, effective and saved user ID of
the calling process.
The
.code getresgid
function retrieves the real, effective and saved group ID of
the calling process.

.coNP Functions @ setresuid and @ setresgid
.synb
.mets (setresuid < real-uid < effective-uid << saved-uid )
.mets (setresgid < real-gid < effective-gid << saved-gid )
.syne
.desc
These functions directly correspond to the POSIX C library functions of the
same names available in some Unix operating systems.  They change the real,
effective and saved user ID or group ID, respectively, of the calling process.

A value of -1 for any of the IDs specifies that the ID is not to be changed.

Only privileged processes may arbitrarily change IDs to different values.

Unprivileged processes are restricted in the following way:
each of the new IDs that is replaced must have a new value which is equal to
one of the existing three IDs.

.SS* Unix Password Database

.coNP Structure @ passwd
.synb
.mets (defstruct passwd nil
.mets \ \  name passwd uid gid
.mets \ \  gecos dir shell)
.syne
.desc
The
.code passwd
structure corresponds to the C type
.codn "struct passwd" .
Objects of this struct are produced by the password database
query functions
.codn getpwent ,
.codn getpwuid ,
and
.codn getpwnam .

.coNP Functions @, getpwent @ setpwent and @ endpwent
.synb
.mets (getpwent)
.mets (setpwent)
.mets (endpwent)
.syne
.desc
The first time
.code getpwent
function is called, it returns the first password database entry.
On subsequent calls it returns successive entries.
Entries are returned as instances of the
.code passwd
structure.  If the function cannot retrieve an entry for any reason,
it returns
.codn nil .

The
.code setpwent
function rewinds the database scan.

The
.code endpwent
function releases the resources associated with the scan.

.coNP Function @ getpwuid
.synb
.mets (getpwuid << uid )
.syne
.desc
The
.code getpwuid
searches the password database for an entry whose user ID field
is equal to the numeric
.metn uid .
If the search is successful, then a
.code passwd
structure representing the database entry is returned.
If the search fails,
.code nil
is returned.

.coNP Function @ getpwnam
.synb
.mets (getpwnam << name )
.syne
.desc
The
.code getpwnam
searches the password database for an entry whose user name
is equal to
.metn name .
If the search is successful, then a
.code passwd
structure representing the database entry is returned.
If the search fails,
.code nil
is returned.

.SS* Unix Group Database

.coNP Structure @ group
.synb
.mets (defstruct group nil
.mets \ \  name passwd gid mem)
.syne
.desc
The
.code group
structure corresponds to the C type
.codn "struct group" .
Objects of this struct are produced by the password database
query functions
.codn getgrent ,
.codn getgrgid ,
and
.codn getgrnam .

.coNP Functions @, getgrent @ setgrent and @ endgrent
.synb
.mets (getgrent)
.mets (setgrent)
.mets (endgrent)
.syne
.desc
The first time
.code getgrent
function is called, it returns the first group database entry.
On subsequent calls it returns successive entries.
Entries are returned as instances of the
.code passwd
structure.  If the function cannot retrieve an entry for any reason,
it returns
.codn nil .

The
.code setgrent
function rewinds the database scan.

The
.code endgrent
function releases the resources associated with the scan.

.coNP Function @ getgrgid
.synb
.mets (getgrgid << gid )
.syne
.desc
The
.code getgrgid
searches the group database for an entry whose group ID field
is equal to the numeric
.metn gid .
If the search is successful, then a
.code group
structure representing the database entry is returned.
If the search fails,
.code nil
is returned.

.coNP Function @ getgrnam
.synb
.mets (getgrnam << name )
.syne
.desc
The
.code getgrnam
searches the group database for an entry whose group name
is equal to
.metn name .
If the search is successful, then a
.code group
structure representing the database entry is returned.
If the search fails,
.code nil
is returned.

.SS* Unix Password Hashing
.coNP Function @ crypt
.synb
.mets (crypt < key << salt )
.syne
.desc
The
.code crypt
function is a wrapper for the Unix C library function of the same name.
It calculates a hash over the
.meta key
and
.meta salt
arguments, which are strings. The hash is returned as a string.

The
.meta key
and
.meta salt
arguments are converted into UTF-8 prior to being passed into the underlying
platform function. The hash value is assumed to be UTF-8 and converted to
Unicode characters, though it is not expected to contain anything but 7
bit ASCII characters.

Note: the underlying C library function uses a static buffer for its return
value. The return value of the \*(TL function is a copy of that buffer.

.SS* Unix Signal Handling

On platforms where certain advanced features of POSIX signal handling are
available at the C API level, \*(TX exposes signal-handling functionality.

A \*(TX program can install a \*(TL function (such as an anonymous.
.codn lambda ,
or the function object associated with a named function) as the handler for
a signal.

When that signal is delivered, \*(TX will intercept it with its own safe,
internal handler, mark the signal as deferred (in a \*(TX sense) and then
dispatch the registered function at a convenient time.

Handlers currently are not permitted to interrupt the execution of most
\*(TX internal code.  Immediate, asynchronous execution of handlers is
currently enabled only while \*(TX is blocked on I/O operations or sleeping.
Additionally, the
.code sig-check
function can be used to dispatch and clear deferred
signals. These handlers are then safely called if they were subroutines of
.codn sig-check ,
and not asynchronous interrupts.

.coNP Variables @, sig-hup @, sig-int @, sig-quit @, sig-ill @, sig-trap @, sig-abrt @, sig-bus @, sig-fpe @, sig-kill @, sig-usr1 @, sig-segv @, sig-usr2 @, sig-pipe @, sig-alrm @, sig-term @, sig-chld @, sig-cont @, sig-stop @, sig-tstp @, sig-ttin @, sig-ttou @, sig-urg @, sig-xcpu @, sig-xfsz @, sig-vtalrm @, sig-prof @, sig-poll @, sig-sys @, sig-winch @, sig-iot @, sig-stkflt @, sig-io @ sig-lost and @ sig-pwr
.desc
These variables correspond to the C signal constants
.codn SIGHUP ,
.code SIGINT
and so forth.
The variables
.codn sig-winch ,
.codn sig-iot ,
.codn sig-stkflt ,
.codn sig-io ,
.code sig-lost
and
.code sig-pwr
may not be available since a system may lack the corresponding signal
constants. See notes for the function
.codn log-authpriv .

The highest signal number is 31.

.coNP Functions @ set-sig-handler and @ get-sig-handler
.synb
.mets (set-sig-handler < signal-number << handling-spec )
.mets (get-sig-handler << signal-number )
.syne
.desc
The
.code set-sig-handler
function is used to specify the handling for a signal, such
as the installation of a handler function. It updates the signal handling for
a signal whose number is
.meta signal-number
(usually one of the constants like
.codn sig-hup ,
.code sig-int
and so forth), and returns the previous value.  The
.code get-sig-handler
function returns the current value.

The
.meta signal-number
must be an integer the range 1 to 31.

Initially, all 31 signal handling specifications are set to the value
.codn t .

The
.meta handling-spec
parameter may be a function. If a function is specified,
then the signal is enabled and connected to that function until another
call to
.code set-sig-handler
changes the handling for that signal.

If
.meta handling-spec
is the symbol
.codn nil ,
then the function previously associated
with the signal, if any, is removed, and the signal is disabled. For a signal
to be disabled means that the signal is set to the
.code SIG_IGN
disposition (refer to the C API).

If
.meta handling-spec
is the symbol
.codn t ,
then the function previously associated
with the signal, if any, is removed, and the signal is set to its default
disposition. This means that it is set to
.code SIG_DFL
(refer to the C API).
Some signals terminate the process if they are generated while the
handling is configured to the default disposition.

Note that the certain signals like
.code sig-quit
and
.code sig-kill
cannot be ignored or handled.
Please observe the signal documentation in the IEEE POSIX standard, and your
platform.

A signal handling function must take two arguments. It is of the form:

.cblk
.mets (lambda >> ( signal << async-p ) ...)
.cble

The
.meta signal
argument is an integer indicating the signal number for which the
handler is being invoked. The
.meta asyncp-p
argument is a Boolean value.
If it is
.codn t ,
it indicates that the handler is being invoked
asynchronously\(emdirectly in a signal handling context.  If it is
.codn nil ,
then it
is a deferred call.  Handlers may do more things in a deferred call, such
as terminate by throwing exceptions, and perform I/O.

The return value of a handler is normally ignored. However if it invoked
asynchronously (the
.meta async-p
argument is true), then if the handler returns
a
.cod2 non- nil
value, it is understood that the handler
requesting that it be deferred. This means that the signal will be marked
as deferred, and the handler will be called again at some later
time in a deferred context, whereby
.meta async-p
is
.codn nil .
This is not guaranteed, however;
it's possible that another signal will arrive before that happens,
possibly resulting in another async call, so the handler must
be prepared to deal with an async call at any time.

If a handler is invoked synchronously, then its return value is ignored.

In the current implementation, signals do not queue. If a signal is delivered
to the process again, while it is marked as deferred, it simply stays deferred;
there is no counter associated with a signal, only a Boolean flag.

.coNP Function @ sig-check
.synb
.mets (sig-check)
.syne
.desc
The
.code sig-check
function tests whether any signals are deferred, and for each
deferred signal in turn, it executes the corresponding handler.  For a signal to
be deferred means that the signal was caught by an internal handler in
\*(TX and the event was recorded by a flag.  If a handler function is removed
while a signal is deferred, the deferred flag is cleared for that signal.

Calls to the
.code sig-check
function may be inserted into CPU-intensive code that
has no opportunity to be interrupted by signals, because it doesn't invoke any
I/O functions.

.coNP Function @ raise
.synb
.mets (raise << signal )
.syne
.desc
The
.code raise
function sends
.meta signal
to the process.
It is a wrapper for the C function of the same name.

The return value is
.code t
if the function succeeds, otherwise
.codn nil .

.coNP Function @ kill
.synb
.mets (kill < process-id <> [ signal ])
.syne
.desc
The
.code kill
function is used for sending a signal to a process group or process.
It is a wrapper for the POSIX
.code kill
function.

If the
.meta signal
argument is omitted, it defaults to the same value as
.codn sig-term .

The return value is
.code t
if the function succeeds, otherwise
.codn nil .

.SS* Unix Processes

.coNP Functions @ fork and @ wait
.synb
.mets (fork)
.mets (wait >> [ pid <> [ flags ]])
.syne
.desc
The
.code fork
and
.code wait
functions are interfaces to the Unix functions
.code fork
and
.codn waitpid .

The
.code fork
function creates a child process which is a replica of the parent. Both
processes return from the function. In the child process, the return value is
zero. In the parent, it is an integer representing the process ID of the child.
If the function fails to create a child, it returns
.code nil
rather than an integer. In this case, the
.code errno
function can be used to inquire about the cause.

The
.code wait
function, if successful, returns a cons cell consisting of a pair of integers.
The
.code car
of the cons is the process ID of the process or group which was successfully
waited on, and the
.code cdr
is the status. If
.code wait
fails, it returns
.codn nil .
The
.code errno
function can be used to inquire about the cause.

The
.meta process-id
argument, if not supplied, defaults to -1, which means that
.code wait
waits for any process, rather than a specific process. Certain other
values have special meaning, as documented in the POSIX standard
for the
.code waitpid
function.

The
.meta flags
argument defaults to zero. If it is specified as nonzero, it should be
a bitwise combination (via the
.code logior
function) of the variables
.codn w-nohang ,
.code w-untraced
and
.codn w-continued .
If
.code w-nohang
is used, then
.code wait
returns a cons cell whose
.code car
specifies a process ID value of zero in the situation that at least
one of the processes designated by
.code process-id
exist and are children of the calling process, but have not changed state.
In this case, the status value in the
.code cdr
is unspecified.

Status values may be inspected with the functions
.codn w-ifexited ,
.codn w-exitstatus ,
.codn w-ifsignaled ,
.codn w-termsig ,
.codn w-coredump ,
.codn w-ifstopped ,
.code w-stopsig
and
.codn w-ifcontinued .

.coNP Functions @, w-ifexited @, w-exitstatus @, w-ifsignaled @, w-termsig @, w-coredump @ w-ifstopped and @ w-stopsig
.synb
.mets (w-ifexited << status )
.mets (w-exitstatus << status )
.mets (w-ifsignaled << status )
.mets (w-termsig << status )
.mets (w-coredump << status )
.mets (w-ifstopped << status )
.mets (w-stopsig << status )
.mets (w-ifcontinued << status )
.syne
.desc
These functions analyze process exit values produced by the
.code wait
function.

They are closely based on the
POSIX macros
.codn WIFEXITED ,
.codn WEXITSTATUS ,
and so on.

The
.meta status
value is either an integer, or a cons cell. In this case, the cons
cell is expected to have an integer in its
.code cdr
which is used as the status.

The
.codn w-ifexited ,
.codn w-ifsignaled ,
.codn w-coredump ,
.code w-ifstopped
and
.code w-ifcontinued
functions have Lisp Boolean return semantics, unlike their C language
counterparts: they return
.code t
or
.codn nil ,
rather than zero or nonzero. The others return integer values.

.coNP Function @ exec
.synb
.mets (exec < file <> [ args ])
.syne
.desc
The exec function replaces the process image with the executable specified
by string argument
.metn file .
The executable is found by searching the system path.

The
.meta file
argument becomes the first argument of the executable, argument zero.

If
.meta args
is specified, it is a list of strings. These are passed as the additional
arguments of the executable.

If
.code exec
fails, an exception of type
.code file-error
is thrown.

.coNP Function @ exit*
.synb
.mets (exit* << status )
.syne
.desc
The
.code exit*
function terminates the entire process (running \*(TX image), specifying
the termination status to the operating system. The
.meta status
argument is treated exactly like that of the
.code exit
function. Unlike that function, this one exits the process immediately,
cleaning up only low-level operating system resources such as closing file
descriptors and releasing memory mappings, without performing user-space
cleanup.

.code exit*
is implemented using a call to the POSIX function
.codn _exit .

.coNP Functions @ getpid and @ getppid
.synb
.mets (getpid)
.mets (getppid)
.syne
.desc
These functions retrieve the current process ID and the parent process ID
respectively. They are wrappers for the POSIX functions
.code getpid
and
.codn getppid .

.coNP Function @ daemon
.synb
.mets (daemon < nochdir-p << noclose-p )
.syne
.desc
This is a wrapper for the function
.code daemon
which originated in BSD Unix.

It returns
.code t
if successful,
.code nil
otherwise, and the
.code errno
variable is set in that case.

.SS* Unix File Descriptors

.coNP Function @ open-fileno
.synb
.mets (open-fileno < file-descriptor <> [ mode-string ])
.syne
.desc
The
.code open-fileno
function creates a \*(TX stream over a file descriptor. The
.meta file-descriptor
argument must be an integer denoting a valid file descriptor.

For a description of
.metn mode-string ,
see the
.code open-file
function.

.coNP Function @ fileno
.synb
.mets (fileno << stream )
.syne
.desc
The
.code fileno
function returns the underlying file descriptor of
.metn stream ,
if it has one. Otherwise, it returns
.codn nil .

This is equivalent to querying the stream using
.code stream-get-prop
for the
.code :fd
property.

.coNP Function @ dupfd
.synb
.mets (dupfd < old-fileno <> [ new-fileno ])
.syne
.desc
The
.code dupfd
function provides an interface to the POSIX functions
.code dup
or
.codn dup2 ,
when called with one or two arguments, respectively.

.coNP Function @ pipe
.synb
.mets (pipe)
.syne
.desc
The
.code pipe
function, if successful, returns a pair of integer file descriptors
as a cons cell pair. The descriptor in the
.code car
field of the pair is the read end of the pipe.
The
.code cdr
holds the write end.

If the function fails, it throws an exception of type
.codn file-error .

.coNP Function @ poll
.synb
.mets (poll < poll-list <> [ timeout ])
.syne
.desc
The
.code poll
function suspends execution while monitoring one or more file descriptors
for specified events. It is a wrapper for the same-named POSIX function.

The
.meta poll-list
argument is a list of
.code cons
pairs. The
.code car
of each pair is either an integer file descriptor, or else a stream
object which has a file descriptor (the
.code fileno
function can be applied to that stream to retrieve a descriptor).
The
.code cdr
of each pair is an integer bit mask specifying the events, whose
occurrence the file descriptor is to be monitored for. The variables
.codn poll-in ,
.codn poll-out ,
.code poll-err
and several others are available which hold bitmask values corresponding
to the constants
.codn POLLIN ,
.codn POLLOUT ,
.code POLLERR
used with the C language
.code poll
function.

The
.meta timeout
argument, if absent, defaults to the value -1, which specifies an indefinite
wait. A nonnegative value specifies a wait with a timeout, measured in
milliseconds.

The function returns a list of pairs representing the descriptors or streams
which were successfully polled. If the function times out, it returns an
empty list. If an error occurs, an exception is thrown.

The returned list is similar in structure to the input list. However, it holds
only entries which polled positive. The
.code cdr
of every pair now holds a bitmask of the events which were to have occurred.

.SS* Unix Itimers
Itimers ("interval timers") can be used in combination with signal handling to
execute asynchronous actions. Itimers deliver delayed, one-time signals,
and also periodically recurring signals. For more information, consult the
POSIX specification.

.coNP Variables @, itimer-real @ itimer-virtual and @ itimer-prof
.desc
These variables correspond to the POSIX constants
.codn ITIMER_REAL ,
.code ITIMER_VIRTUAL
and
.codn ITIMER_PROF .
Their values are suitable as the
.meta timer
argument of the
.code getitimer
and
.code setitimer
functions.

.coNP Functions @ getitimer and @ setitimer
.synb
.mets (getitimer << timer )
.mets (setitimer < timer < interval << value )
.syne
.desc
The
.code getitimer
function returns the current value of the specified timer,
which must be
.codn itimer-real ,
.code itimer-virtual
or
.codn itimer-prof .

The current value consists of a list of two integer values, which
represents microseconds. The first value is the timer interval,
and the second value is the timer's current value.

Like
.codn getitimer ,
the
.code setitimer
function also retrieves the specified timer.
In addition, it stores a new value in the timer,
which is given by the two arguments, expressed in microseconds.

.SS* Unix Syslog

On platforms where a Unix-like syslog API is available, \*(TX exports this
interface. \*(TX programs can configure logging via the
.code openlog
function,
control the logging mask via
.code setlogmask
and generate logs via
.codn syslog ,
or using special syslog streams.

.coNP Variables @, log-pid @, log-cons @, log-ndelay @, log-odelay @ log-nowait and @ log-perror
.desc
These variables take on the values of the corresponding C preprocessor
constants from the
.code <syslog.h>
header:
.codn LOG_PID ,
.codn LOG_CONS ,
etc.
These integer values represent logging options used in the
.meta options
argument to the
.code openlog
function.

Note:
.code LOG_PERROR
is not in POSIX, and so
.code log-perror
might not be available.
See notes about
.code LOG_AUTHPRIV
in the documentation for
.codn log-authpriv .

.coNP Special variables @, log-user @, log-daemon @ log-auth and @ log-authpriv
.desc
These variables take on the values of the corresponding C preprocessor
constants from the
.code <syslog.h>
header:
.codn LOG_USER ,
.codn LOG_DAEMON ,
.code LOG_AUTH
and
.codn LOG_AUTHPRIV .
These are the integer facility codes specified in the
.code openlog
function.

Note:
.code LOG_AUTHPRIV
is not in POSIX, and so
.code log-authpriv
might not be available.
For portability use code like
.code "(or (symbol-value 'log-authpriv) 0)"
to evaluate to 0 if
.code log-authpriv
doesn't exist, or else check for its existence
using
.codn "(boundp 'log-authpriv)" .

.coNP Special variables @, log-emerg @, log-alert @, log-crit @, log-err @, log-warning @, log-notice @ log-info and @ log-debug

These variables take on the values of the corresponding C preprocessor
constants from the
.code <syslog.h>
header:
.codn LOG_EMERG ,
.codn LOG_ALERT ,
etc.
These are the integer priority codes specified in the
.code syslog
function.

.coNP The @ *stdlog* special variable
.desc
The
.code *stdlog*
variable holds a special kind of stream: a syslog stream.  Each
newline-terminated line of text sent to this stream becomes a log message.

The stream internally maintains a priority value that is applied
when it generates messages. By default, this value is that of
.codn log-info .
The stream holds the priority as the value of the
.code :prio
stream property, which may be changed with the
.code stream-set-prop
function.

The latest priority value which has been configured on the stream is used
at the time the newline character is processed and the log message
is generated, not necessarily the value which was in effect at the time the
accumulation of a line began to take place.

Messages sent to
.code *stdlog*
are delimited by newline characters. That is to say, each line of
text written to the stream is a new log.

.coNP Function @ openlog
.synb
.mets (openlog < id-string >> [ options <> [ facility ]])
.syne
.desc
The
.code openlog
function is a wrapper for the
.code openlog
C function, and the
arguments have the same semantics. It is not necessary to use
.code openlog
in order
to call the
.code syslog
function or to write data to
.codn *stdlog* .
The call is necessary in order to override the default identifying string, to
set options, such as having the PID (process ID) recorded in log messages, and
to specify the facility.

The
.meta id-string
argument is mandatory.

The
.meta options
argument is a bitwise mask (see the logior function) of option
values such as
.code log-pid
and
.codn log-cons .
If it is missing, then a value of 0 is
used, specifying the absence of any options.

The
.meta facility
argument is one of the values
.codn log-user ,
.code log-daemon
or
.codn log-auth .
If it is missing, then
.code log-user
is assumed.

.coNP Function @ closelog
.synb
.mets (closelog)
.syne
.desc
The
.code closelog
function is a wrapper for the C function
.codn closelog .

.coNP Function @ setlogmask
.synb
.mets (setlogmask << bitmask-integer )
.syne
.desc
The
.code setlogmask
function interfaces to the corresponding C function, and has the
same argument and return value semantics. The
.meta bitmask-integer
argument is a mask of priority
values to enable. The return value is the prior value. Note that if the
argument is zero, then the function doesn't set the mask to zero; it only
returns the current value of the mask.

Note that the priority values like
.code log-emerg
and
.code log-debug
are integer
enumerations, not bitmasks. These values cannot be combined directly to create
a bitmask. Rather, the
.code mask
function should be used on these values.

.TP* Example:

.cblk
  ;; Enable LOG_EMERG and LOG_ALERT messages,
  ;; suppressing all others
  (setlogmask (mask log-emerg log-alert))
.cble

.coNP Function @ syslog
.synb
.mets (syslog < priority < format << format-arg *)
.syne
.desc
This function is the interface to the
.code syslog
C function. The
.code printf
formatting capabilities of the function are not used;
the
.meta format
argument follows the conventions of the \*(TL 
.code format
function instead. Note in particular that
the
.code %m
convention for interpolating the value of strerror(errno) which is
available in some versions of the
.code syslog
C function is currently not supported.

Note that syslog messages are not newline-terminated.

.SS* Unix Path Globbing

On platforms where the POSIX
.code glob
function is available \*(TX provides this functionality in
the form of a like-named function, and some numeric constants.
\*(TX also provides access the
.code fnmatch
function, where available.

.coNP Variables @, glob-err @, glob-mark @, glob-nosort @, glob-nocheck @, glob-noescape @, glob-period @, glob-altdirfunc @, glob-brace @, glob-nomagic @, glob-tilde @ glob-tilde-check and @ glob-onlydir
.desc
These variables take on the values of the corresponding C preprocessor
constants from the
.code <glob.h>
header:
.codn GLOB_ERR ,
.codn GLOB_MARK ,
.codn GLOB_NOSORT ,
etc.

These values are passed as the optional second argument of the
.code glob
function. They are bitmasks and so multiple values can be combined
using the
.code logior
function.

Note that the
.codn glob-period ,
.codn glob-altdirfunc ,
.codn glob-brace ,
.codn glob-nomagic ,
.codn glob-tilde ,
.code glob-tilde-check
and
.code glob-onlydir
variables may not be available. They are extensions in the GNU C library
implementation of
.codn glob .

.coNP Function @ glob
.synb
.mets (glob < pattern >> [ flags <> [ error-func ]])
.syne
.desc
The
.code glob
function is a interface to the Unix function of the same name.
The
.meta pattern
argument must be a string, which holds a glob pattern: a pattern which
matches zero or more path names, similar to a regular expression.
The function tries to expand the pattern and return a list of strings
representing the matching path names in the file system.

If there are no matches, then an empty list is returned.

The optional
.meta flags
argument defaults to zero. If given, it may be a bitwise combination of the
values of the variables
.codn glob-err ,
.codn glob-mark ,
.code glob-nosort
and others.

If the
.meta error-func
argument is specified, it gives a callback function which is invoked
when
.code glob
encounters errors accessing paths. The function takes two arguments:
the pathname and the
.code errno
value which occurred for that pathname. The function's return value is
Boolean. If the function returns true, then
.code glob
will terminate.

The
.meta error-func
may terminate the traversal by a nonlocal exit, such as by throwing
an exception or performing a block return.

The
.meta error-func
may not re-enter the
.code glob
function. This situation is detected and diagnosed by an exception.

The
.meta error-func
may not capture a continuation across the error boundary. That is to say,
code invoked from the error may not capture a continuation up to a prompt
which surrounds the
.code glob
call. Such an attempt is detected and diagnosed by an exception.

Details of the semantics of the
.code glob
function, and the meaning of all the
.meta flags
arguments are given in the documentation for the C function.

.coNP Variables @, fnm-pathname @, fnm-noescape @, fnm-period @, fnm-leading-dir @ fnm-casefold and @ fnm-extmatch
.desc
These variables take on the values of the corresponding C preprocessor
constants from the
.code <fnmatch.h>
header:
.codn FNM_PATHNAME ,
.codn FNM_NOESCAPE ,
.codn FNM_PERIOD ,
etc.

These values are bit masks which may be combined with the
.code logior
function to form the optional third
.meta flags
argument of the
.code fnmatch
function.

Note that the
.codn fnm-leading-dir ,
.code fnm-case-fold
and
.code fnm-extmatch
may not be available. They are GNU extensions, found in the GNU C library.

.coNP Function @ fnmatch
.synb
.mets (fnmatch < pattern < string <> [ flags ]])
.syne
.desc
The
.code fnmatch
function, if available, provides access
to the like-named POSIX C library function.
The
.meta pattern
argument specifies a POSIX-shell-style file pattern matching expression.
Its exact features and dialect are controlled by
.metn flags .
If
.meta string
matches
.meta pattern
then
.code t
is returned. If there is no match, then
.code nil
is returned. If the C function indicates that an error has occurred,
an exception is thrown.

.SS* Unix Filesystem Traversal

On platforms where the POSIX
.code nftw
function is available \*(TX provides this functionality in
the form of the analogous Lisp function
.codn ftw ,
accompanied by some numeric constants.

.coNP Variables @, ftw-phys @, ftw-mount @, ftw-chdir @ ftw-depth and @ ftw-actionretval
.desc
These variables hold numeric values that may be combined into a single
bitmask bitmask value using the
.code logior
function. This value is suitable as the
.meta flags
argument of the
.code ftw
function.

These variables corresponds to the C constants
.codn FTW_PHYS ,
.codn FTW_MOUNT ,
et cetera.

Note that
.code ftw-actionretval
is a GNU extension that is not available on all platforms. If the platform's
.code nftw
function doesn't have this feature, then this variable is not defined.

.coNP Variables @, ftw-f @, ftw-d @, ftw-dnr @, ftw-ns @, ftw-sl @ ftw-dp and @ ftw-sln
.desc
These variables provide symbolic names for the integer values that are
passed as the
.code type
argument of the callback function called by
.codn ftw .
This argument classifies the kind of file system node visited, or
error condition encountered.

These variables correspond to the C constants
.codn FTW_F ,
.codn FTW_D ,
et cetera.

Not all of them are present. If the underlying platform doesn't have
a given constant, then the corresponding variable doesn't exist in \*(TX.

.coNP Variables @, ftw-continue @, ftw-stop @ ftw-skip-subtree and @ ftw-skip-siblings
.desc
These variables are defined if the variable
.code ftw-actionretval
is defined.

If the value of
.code ftw-actionretval
is included in the
.meta flags
argument of
.codn ftw ,
then the callback function can use the values of these variables
as return codes. Ordinarily, the callback returns zero to continue
the search and nonzero to stop.

These variables correspond to the C constants
.codn FTW_CONTINUE ,
.codn FTW_STOP ,
et cetera.

.coNP Function @ ftw
.synb
.mets (ftw < path < callback-func >> [ flags <> [ nopenfd ]])
.mets >> [ callback-func < path < type < stat-struct < level << base ]
.syne
.desc
The
.code ftw
function provides access to the
.code nftw
POSIX C library function.

Note that the
.meta flags
and
.meta nopenfd
arguments are reversed with respect to the C language interface.
They are both optional;
.meta flags
defaults to zero, and
.meta nopenfd
defaults to 20.

Also note that, unlike in the C function, multiple
paths may be processed by passing a list
for the
.meta path
argument.

The
.code nftw
function walks the filesystem, as directed by the
.meta path
string and
.meta flags
bitmask arguments.

For each visited entry, it calls the supplied
.meta callback-func
function, which receives five arguments.

This function can continue the traversal by returning any non-integer value,
or the integer value zero.
If
.code ftw-actionretval
is included in the
.meta flags
bitmask, then the only integer code which continues the traversal without
any special semantics is
.code ftw-continue
and only
.code ftw-stop
stops the traversal.  (Non-integer return values behave like
.codn ftw-continue ).

The
.meta path
argument of the callback function gives the path of the
visited filesystem object. 

The
.meta type
argument is an integer code which indicates the kind of
object that is visited, or an error situation in visiting
that filesystem entry.  See the documentation for
.code ftw-f
and
.code ftw-d
for possible values.

The
.meta stat-struct
argument provides information about the filesystem object
as a
.code stat
structure, the same kind of object as what is returned by the
.code stat
function.

The
.meta level
argument is an integer value representing the directory level
depth. This value is obtained from the C structure
.code FTW
in the
.code nftw
C API.

The
.meta base
argument indicates the length of the directory part of the
.code path
argument. Characters in excess of this length are thus the base name of the
visited object, and the expression
.cblk
.meti >> [ path << base ..:]
.cble
calculates the base name.

The
.code ftw
function returns
.code t
upon successful completion and
.code nil
on failure. If
.code ftw
is terminated by a return value from
.metn callback-func ,
then that value is returned. Such a value is always a nonzero integer.

If the
.meta path
passed to
.code ftw
is a list, then all of the paths contained in that
list are walked, as if by recursive application of
.code ftw
to each element of the list taken as the
.meta path
argument, the other argument values being the same.
The traversal stops when any recursive
invocation of
.code ftw
returns a value other than
.code t
or
.codn nil ,
and that value is returned. If
.code t
or
.code nil
is returned, the traversal continues with the
application of
.code ftw
to the next list element, if any.
If the list is completely traversed, and some recursive
invocations of
.code ftw
return
.codn t ,
then the return value is
.codn t .
If all recursive invocations return
.code nil
then
.code nil
is returned.
If the list is empty,
.code t
is returned.

The
.meta callback-func
may terminate the traversal by a nonlocal exit, such as by throwing
an exception or performing a block return.

The
.meta callback-func
may not re-enter the
.code ftw
function. This situation is detected and diagnosed by an exception.

The
.meta callback-func
may not capture a continuation across the callback boundary. That is to say,
code invoked from the callback may not capture a continuation up to a prompt
which surrounds the
.code ftw
call. Such an attempt is detected and diagnosed by an exception.

.SS* Unix Sockets

On platforms where the underlying system interface is available, \*(TX provides
a sockets library for communicating over Internet networks, or over Unix
sockets.

Stream as well as datagram sockets are supported.

The classic Version 4 of the Internet protocol is supported, as well
as IP Version 6.

Sockets are mapped to \*(TX streams. The
.code open-socket
function creates a socket of a specified type, in a particular address family.
This socket is actually a stream (always, even if it isn't used for
data transfer, but only as a passive contact point).

The functions
.codn sock-connect ,
.codn sock-bind ,
.codn sock-listen ,
.code sock-accept
and
.code sock-shutdown
are used for enacting socket communication scenarios.

Stream sockets use ordinary streams, re-using the same underlying framework
that is used for file I/O and process types.

Datagram socket streams are implemented using special datagram socket streams.
Datagram socket streams eliminate the need for operations analogous to the
.code sendto
and
.code recvfrom
socket API functions, even in server programs which handle multiple
clients. An overview of datagrams is treated in the following section,
Datagram Socket Streams.

The
.code getaddrinfo
function is provided for resolving host names and services to IPv4 and IPv6
addresses.

Several structure types are provided for representing socket addresses,
and options for
.codn getaddrinfo .

Various numeric constants are also provided:
.codn af-unix ,
.codn af-inet ,
.codn af-inet6 ,
.codn sock-stream ,
.code sock-dgram
and others.

.NP* Datagram Socket Streams

Datagram socket streams are a new paradigm unique to \*(TX which
attempts to unify the programming model of stream and datagram
sockets.

A datagram socket stream is created by the
.code open-socket
function, when the
.code sock-dgram
socket type is specified. Another way in which a datagram socket
is created is when
.code sock-accept
is invoked on a datagram socket, and returns a new socket.

I/O is performed on datagram sockets using the regular I/O functions.
None of the functions take or return peer addresses. There are no I/O
functions which are analogous to the C library
.code recvfrom
and
.code sendto
functions which are usually used for datagram programming.
Datagram I/O assumes that the datagram datagram socket is connected to a
specific remote peer, and that peer is implicitly used for all I/O.

Datagram streams solves the message framing problem essentially by
considering a single datagram to be an entire stream.  On input, a datagram
stream holds an entire datagram in a buffer. The stream ends
(experiences the EOF condition) after the last byte of this buffer
is removed by an input operation. Another datagram will be received and
buffered if the EOF condition is first explicitly cleared with the
.code clear-error
function, and then another input operation is attempted.
On output, a datagram stream gathers data into an ever-growing output buffer
which isn't subject to any automatic flushing. An explicit
.code flush-stream
operation sends the buffer contents to the connected peer as a new
datagram, and empties the buffer. Subsequent output operations prepare
data for a new datagram. The
.code close-stream
function implicitly flushes the stream in the same way, and thus also
potentially generates a datagram.

A client-style datagram stream can be explicitly connected to a peer with the
.code sock-connect
function. This is equivalent to connecting a
datagram socket using the C library
.code connect
function. Writes on the stream will be transmitted using the C library function
.codn send .
A client-style datagram stream can also be "soft-connected" to a
peer using the
.code sock-set-peer
function. Writes on the stream will transmit data using the C library function
.code sendto
to the peer address.

A datagram server program which needs
to communicate using multiple peers is implemented by means of the
.code sock-accept
function which, unlike the C library
.code accept
function, works with datagram sockets as well as stream sockets.
The server creates a datagram socket, and uses
.code sock-bind
to bind it to a local address. Optionally, it may also call
.code sock-listen
which is a no-op on datagram sockets. Supporting this function on datagram
sockets allows program code to be more easily changed between datagram and
stream operation.
The server then uses
.code sock-accept
to accept new clients. Note that this is not possible with the C
library function
.codn accept ,
which only works with stream sockets.

The
.code sock-accept
function receives a datagram from a client, and creates a new datagram
socket stream which is connected to that client, and whose input buffer
contains the received datagram. Input operations on this stream consume
the datagram. Note that clearing the EOF condition and trying to receive
another datagram is not recommended on datagram streams returned
by
.codn sock-accept ,
since they share the same underlying operating system socket, which is
not actually connected to a specific peer. The receive operation could
receive a datagram from any peer, without any indication which peer that is.
Datagram servers should issue a new
.code sock-accept
call should be issued for each client datagram, treating it as a new
stream.

Datagram sockets ignore almost all aspects of the
.meta mode-string
passed in
.code open-socket
and
.codn sock-accept .
The only attribute not ignored is the buffer size specified
with a decimal digit character; however, it cannot be the
only item in the mode string. The string must be syntactically
valid, as described under the
.code open-file
function. The buffer size attribute controls the size used by
the datagram socket for receiving a datagram: the capture size.
A datagram socket has obtains a default capture size if one isn't
specified by the
.metn mode-string .
The default capture size is 65536 bytes for a datagram socket created by
.codn open-socket .
If a size is not passed to
.code sock-accept
via its
.meta mode-string
argument when it is invoked on a datagram socket,
that socket's size is used as the capture size of the
newly created datagram socket which is returned.

.coNP Structure @ sockaddr
.synb
.mets (defstruct sockaddr nil)
.syne
.desc
The
.code sockaddr
structure represents the abstract base class for socket addresses, from which
several other types are derived:
.codn sockaddr-in ,
.code sockaddr-in6
and
.codn sockaddr-un .

.coNP Structure @ sockaddr-in
.synb
.mets (defstruct sockaddr-in sockaddr
.mets \ \  (addr 0) (port 0))
.syne
.desc
The
.code sockaddr-in
address represents a socket address used in the context of networking over
IP Version 4. It may be used with sockets in the
.code af-inet
address family.

The
.code addr
slot holds an integer denoting an abstract IPv4 address. For instance the hexadecimal
integer literal constant
.code #x7F000001
or its decimal equivalent
.code 2130706433
represents the loopback address, whose familiar "dot notation" is
.codn 127.0.0.1 .
Conversion of the abstract IP address to four bytes in network order, as
required, is handled internally.

The
.code port
slot holds the TCP or UDP port number, whose value ranges from 0 to 65535.
Zero isn't a valid port; the value is used for requesting an ephemeral port number
in active connections. Zero also appears in situations when the port number isn't required:
for instance, when the
.code getaddrinfo
function is used with the aim of looking up the address of a host, without
caring about the port number.

.coNP Structure @ sockaddr-in6
.synb
.mets (defstruct sockaddr-in6 sockaddr
.mets \ \  (addr 0) (port 0) (flow-info 0) (scope-id 0))
.syne
.desc
The
.code sockaddr-in6
address represents a socket address used in the context of networking over
IP Version 6. It may be used with sockets in the
.code af-inet6
address family.

The
.code addr
slot holds an integer denoting an abstract IPv6 address. IPv6 addresses are
pure binary integers up to 128 bits wide.

The
.code port
slot holds the TCP or UDP port number, whose value ranges from 0 to 65535.
In IPv6, the port number functions similarly to IPv6; see
.codn sockaddr-in .

The
.code flow-info
and
.code scope-id
are special IPv6 parameters corresponding to the
.code sin6_flowinfo
and
.code sin6_scope_id
members of the
.code sockaddr_in6
C language structure. Their meaning and use are beyond the scope of this document.

.coNP Structure @ sockaddr-un
.synb
.mets (defstruct sockaddr-un sockaddr
.mets \ \  path)
.syne
.desc
The
.code sockaddr-un
address represents a socket address used for inter-process communication
within a single operating system node, using the "Unix domain" sockets
of the
.code af-unix
address family.

This structure has only one slot,
.code path
which holds the rendezvous name for connecting pairs of socket endpoints.
This name appears in the filesystem.

When the
.code sockaddr-un
structure is converted to the C structure
.codn "struct sockaddr_un" ,
the
.code path
slot undergoes conversion to UTF-8. The resulting bytes are stored in the
.code sun_path
member of the C structure. If the resulting UTF-8 byte string
is larger than the
.code sun_path
array, it is silently truncated.

Note: Linux systems have support for "abstract" names which do not appear in
the filesystem. These abstract names are distinguished by starting with a null
byte. For more information, consult Linux documentation.
This convention is supported in the
.code path
slot of the
.code sockaddr-un
structure. If
.code path
contains occurrences of the pseudo-null character U+DC00, these translate
to null bytes in the
.code sun_path
member of the corresponding C structure
.codn "struct sockaddr_un" .
For example, the path
.str "\exDC00;foo"
is valid and represents an abstract address consisting of the three bytes
.str "foo"
followed by null padding bytes.

.coNP Structure @ addrinfo
.synb
.mets (defstruct addrinfo nil
.mets \ \ (flags 0) (family 0) (socktype 0))
.syne
.desc
The
.code addrinfo
structure is used in conjunction with the
.code getaddrinfo
function. If that function's
.meta hints
argument is specified, it is of this type.
The purpose of the argument is to narrow down
or possibly alter the selection of addresses which
are returned.

The
.code flags
slot holds a bitwise or combination (see the
.code logior
function) of
.code getaddrinfo
flags: values given by the variables.
.codn ai-passive ,
.codn ai-numerichost ,
.codn ai-v4mapped ,
.codn ai-all ,
.code ai-addrconfig
and
.codn ai-numericserv .
These correspond to the C constants
.codn AI_PASSIVE ,
.code AI_NUMERICHOST
and so forth.

The
.code family
slot holds an address family, which may be the value of
.codn af-unspec ,
.codn af-unix ,
.code af-inet
or
.codn af-inet6 .

The
.code socktype
slot holds, a socket type. Socket types are given
by the variables
.code sock-dgram
and
.codn sock-stream .

.coNP Function @ addrinfo
.synb
.mets (getaddrinfo >> [ node >> [ service <> [ hints ]]])
.syne
.desc
The
.code getaddrinfo
returns a list of socket addresses based on search criteria expressed
in its arguments.
That is to say, the returned list, unless empty, contains objects of type
.code sockaddr-in
and
.codn sockaddr-in6 .

The function is implemented directly in terms of the like-named C library
function. All parameters are optional.  Omitting any argument causes a null
pointer to be passed for the corresponding parameter of the C library function.

The
.meta node
and
.meta service
parameters may be character strings which specify a host name, and service.
The contents of these strings may be symbolic, like
.str www.example.com
and
.str ssh
or numeric, like
.str 10.13.1.5
and
.strn 80 .

If an argument is given for the
.code hints
parameter, it must be of type
.codn addrinfo .

The
.meta node
and
.meta service
parameters may also be given integer arguments.
An integer argument value in either of these parameters is converted to a null
pointer when calling the C
.code getaddrinfo
function. The integer values are then simply installed into every returned
address as the IP address or port number, respectively.  However, if both
arguments are numeric, then no addresses are returned, since the C library
function is then called with a null node and service.

.coNP Variables @, af-unix @ af-inet and @ af-inet6
.desc
These variables hold integers which give the values of address
families. They correspond to the C constants
.codn AF_UNIX ,
.code AF_INET
and
.codn AF_INET6 .
Address family values are used in the
.meta hints
argument of the
.code getaddrinfo
function, and in the
.code socket-open
function.
Note that unlike the C language socket addressing structures,
the \*(TX socket addresses do not contain an address family slot.
That is because they indicate their family via their type.
That is to say, an object of type
.code sockaddr-in
is an address which is implicitly associated with the
.code af-inet
family via its type.

.coNP Variables @ sock-stream and @ sock-dgram
.desc
These variables hold integers which give the values of address
families. They correspond to the C constants
.code SOCK_STREAM
and
.codn SOCK_DGRAM .

.coNP Variables @, ai-passive @, ai-numerichost @, ai-v4mapped @, ai-all @ ai-addrconfig and @ ai-numericserv
.desc
These variables hold integers which are bitmasks that combine
together via bitwise or, to express the
.code flags
slot of the
.code addrinfo
structure. They correspond to the C constants
.codn AI_PASSIVE ,
.codn AI_NUMERICHOST ,
.code AI_V4MAPPED
and so forth. They influence the behavior of the
.code getaddrinfo
function.

.coNP Variables @, inaddr-any @, inaddr-loopback @ in6addr-any and @ in6addr-loopback
.desc
These integer-valued variables provide constants for commonly used IPv4
and IPv6 address values.

The value of
.code inaddr-any
and
.code in6addr-any
is zero. This address is used in binding a passive socket to all of the
external interfaces of a host, so that it can accept connections or datagrams
from all attached networks.

The
.code inaddr-loopback
variable is IPv4 loopback address, the same integer as the hexadecimal
constant
.code #x7F000001.

The
.code in6addr-loopback
is the IPv6 loopback address. Its value is 1.

.TP* Example:

.cblk
  ;; Construct an IPv6 socket address suitable for binding
  ;; a socket to the loopback network, port 1234:
  (new sockaddr-in6 addr in6addr-loopback port 1234)

  ;; Mistake: IPv4 address used with IPv6 sockaddr.
  (new sockaddr-in6 addr inaddr-loopback)
.cble

.coNP Function @ open-socket
.synb
.mets (open-socket < family < type <> [ mode-string ])
.syne
.desc
The
.code open-socket
function creates a socket, which is a kind of stream.

The
.meta family
parameter specifies the address family of the socket. One of the
values
.codn af-inet ,
.code af-inet
or
.code af-inet6
should be used to create a Unix domain, Internet IPv4 or Internet IPv6
socket, respectively.

The
.meta type
parameter specifies the socket type, either
.code sock-stream
(stream socket) or
.code sock-dgram
(datagram socket).

The
.meta mode-string
specifies several properties of the stream; for a description of
.meta mode-string
parameters, refer to the
.code open-file
function. Note that the defaulting behavior for an omitted
.meta mode-string
argument is different under
.code open-socket
from other functions. Because sockets are almost always used for bidirectional
data flow, the default mode string is
.str r+b
rather than the usual
.strn r .

Rationale for including the
.str b
flag in the default mode string is that network protocols are usually defined
in a way that is independent of machine and operating system, down to the byte
level, even when they are textual. It doesn't make sense for the same \*(TX
program to see a network stream differently based on what platform it is
running on. Line ending conversion has to do with how a platform locally stores
text files, whereas network streams are almost always external formats.

Like other stream times, stream sockets are buffered and marked as no
non-real-time streams. Specifying the
.str i
mode in
.meta mode-string
marks a socket as a real-time-stream, and, if it is opened for writing
or reading and writing, changes it to use line buffering.

.coNP Function @ open-socket-pair
.synb
.mets (open-socket-pair < family < type <> [ mode-string ])
.syne
.desc
The
.code open-socket-pair
function provides an interface to the functionality of the
.code socketpair
C library function.

If successful, it creates and returns a list of two stream objects,
which are sockets that are connected together.

Note: the Internet address families
.code af-inet
and
.code af-inet6
are not supported.

The
.code mode-string
is applied to each stream. For a description, see
.code open-socket
and
.codn open-file .

.coNP Functions @ sock-family and @ sock-type
.synb
.mets (sock-family << socket )
.mets (sock-type << socket )
.syne
.desc
These functions retrieve the integer values representing the address family
and type of a socket. The argument to the
.meta socket
parameter must be a socket stream or a file or process stream. For a file stream,
both functions return
.codn nil .
An exception of type
.code type-error
is thrown for other stream types.

.coNP Accessor @ sock-peer
.synb
.mets (sock-peer << socket )
.mets (set (sock-peer << socket ) << address )
.syne
.desc
The
.code sock-peer
function retrieves the peer address
has most recently been assigned to
.metn socket .

Sockets which are not connected initially
have a peer address value of
.codn nil .
A socket which is connected to a remote peer
receives that peer's address as its
.codn sock-peer .

If a socket is connected to a remote peer via
a successful use of the
.code sock-connect
function, then its
.code sock-peer
address is set to match that of the peer.

Sockets returned by the
.code sock-accept
function are connected, and have the remote endpoint address as their
.code sock-peer
address.

Assigning an address to a
.code sock-peer
form is equivalent to using
.code sock-set-peer
to set the address.

Implementation note: the
.code sock-peer
function does not use the
.code getpeername
C library function; the association between a stream and
.code sockaddr
struct is maintained by \*(TX.

.coNP Function @ sock-set-peer
.synb
.mets (sock-set-peer < socket << address )
.syne
.desc
The
.code sock-set-peer
function stores
.meta address
into
.meta socket
as that socket's peer.

Subsequently, the
.code sock-peer
function will retrieve that address.

If
.meta address
is not an appropriate address object in the address family of
.metn socket ,
the behavior is unspecified.

.coNP Function @ sock-connect
.synb
.mets (sock-connect < socket < address <> [ timeout-usec ])
.syne
.desc
The
.code sock-connect
function connects a socket stream to a peer address.

The
.meta address
argument must be a
.code sockaddr
object of type matching the address family of the socket.

If the operation fails, an exception of type
.code socket-error
is thrown. Otherwise, the function returns
.metn socket .

If the
.meta timeout-usec
argument is specified, it must be a fixnum integer.
It denotes a connection timeout period in microseconds.
If the connection doesn't succeed within the specified timeout,
an exception of type
.code timeout-error
is thrown.

.coNP Function @ sock-bind
.synb
.mets (sock-bind < socket << address )
.syne
.desc
The
.code sock-connect
function binds a socket stream to a local address.

The
.meta address
argument must be a
.code sockaddr
object of type matching the address family of the socket.

If the operation fails, an exception of type
.code socket-error
is thrown. Otherwise, the function returns
.codn t .

Returns
.code t
if successful.

.coNP Function @ sock-listen
.synb
.mets (sock-listen < socket <> [ backlog ])
.syne
.desc
The
.code sock-listen
function prepares
.meta socket
for listening for connections. The
.meta backlog
parameter, if specified, requires an integer
argument. The default value is 16.

.coNP Function @ sock-accept
.synb
.mets (sock-accept < socket >> [ mode-string <> [ timeout-usec ]])
.syne
.desc
The
.code sock-accept
function waits for a client connection on
.metn socket ,
which must have been prepared for listening for
connections using
.code sock-bind
and
.codn sock-listen .

If the operation fails, an exception of type
.code socket-error
is thrown. Otherwise, the function returns a new socket
which is connected to the remote peer.

The peer's address may be retrieved from this socket using
.codn sock-peer .

The
.code mode-string
parameter is applied to the new socket just like the
similar argument in
.codn socket-open .
It defaults to
.strn r+ .

If the
.meta timeout-usec
argument is specified, it must be a fixnum integer.
It denotes a timeout period in microseconds.
If no peer connects for the specified timeout,
.code sock-accept
throws an exception of type
.codn timeout-error .

.coNP Variables @, shut-rd @ shut-wr and @ shut-rdwr
.desc
The values of these variables are useful as the second argument to the
.code sock-shutdown
function.

.coNP Function @ sock-shutdown
.synb
.mets (sock-shutdown < sock <> [ direction ])
.syne
.desc
The
.code sock-shutdown
function indicates that no further communication is to take place on
.meta socket
in the specified direction(s).

If the operation fails, an exception of type
.code socket-error
is thrown. Otherwise, the function returns
.codn t .

The
.code direction
parameter is one of the values given by the variables
.codn shut-rd ,
.code shut-rw
or
.codn shut-rdwr .
These values shut down communication in the read direction, write direction,
or both directions, respectively.

If the argument is omitted,
.code sock-shutdown
defaults to closing the write direction.

Notes: shutting down is most commonly requested in the write direction, to perform
a "half close". The communicating process thereby indicates that it has written
all the data which it intends to write.  When the shutdown action is processed on the
remote end, that end is unblocked from waiting on any further data, and
effectively experiences an "end of stream" condition on its own socket or
socket-like endpoint, while continuing to be able to transmit data.
Shutting down in the reading direction is potentially abrupt. If it is executed
before an "end of stream" indication is received from a peer, it results in an
abortive close.

.coNP Functions @ sock-recv-timeout and @ sock-send-timeout
.synb
.mets (sock-recv-timeout < sock << usec )
.mets (sock-send-timeout < sock << usec )
.syne
.desc
The
.code sock-recv-timeout
and
.code sock-send-timeout
functions configure, respectively, receive and send timeouts on socket
.metn sock .

The
.meta usec
parameter specifies the value, in microseconds. It must be a
.code fixnum
integer.

When a receive timeout is configured on a socket, then an
exception of type
.code timeout-error
is thrown when an input operation waits for at least
.code usec
microseconds without receiving input.

Similarly, when a send timeout is configured, then an
exception of type
.code timeout-error
is thrown when an output operation waits for at least
.code usec
microseconds for the availability of buffer space in the socket.

.coNP Functions @ str-inaddr and @ str-in6addr
.synb
.mets (str-inaddr address <> [ port ])
.mets (str-in6addr address <> [ port ])
.syne
.desc
The
.code str-inaddr
and
.code str-in6addr
functions convert an IPv4 and IPv6 address, respectively, to textual
notation which is returned as a character string.
The conversion is done in conformance with RFC 5952, section 4.

IPv6 addresses representing IPv6-mapped IPv4 addresses are printed
in the hybrid notation exemplified by
.codn ::ffff:192.168.1.1 .

The
.meta address
parameter must be a non-negative integer in the appropriate range
for the address type.

If the
.meta port
number argument is supplied, it is included in the returned character string,
according to the requirements in section 6 of RFC 5952 pertaining to IPv6
addresses (including IPv6-mapped IPv6 addresses) and section 3.2.3 of RFC 3986
for IPv4 addresses. In brief, IPv6 addresses with ports are expressed as
.code [address]:port
and IPv6 addresses follow the traditional
.code address:port
pattern.

.coNP Functions @ str-inaddr-net and @ str-in6addr-net
.synb
.mets (str-inaddr-net < address <> [ width ])
.mets (str-in6addr-net < address <> [ width ])
.syne
.desc
The functions
.code str-inaddr-net
and
.code str-in6addr-net
convert, respectively, IPv4 and IPv6 network prefix addresses to
the "slash notation". For IPv6 addresses, the requirements of section
2.3 of RFC 4291 are implemented. For IPv4, section 3.1 of RFC 4632 is followed.

The condensed portion of the IP address is always determined by measuring
the contiguous extent of all-zero bits in the least significant position
of the address. For instance an IPv4 address which has at least 24 zero bits
in the least significant position, so that the only nonzero bits are in the
highest octet, is always condensed to a single decimal number: the value of
the first octet.

If the
.meta width
parameter is specified, then its value is incorporated into the returned
textual notation as the width. No check is made whether this width is an
integer large enough to "covers" all the nonzero bits in the address.

If
.meta width
is omitted, then it is calculated as the number of bits in the address,
excluding the contiguous all-zero bits in the least significant position:
how many times the address can be shifted to the right before a 1 appears
in the least significant bit.

.SS* Unix Terminal Control

\*(TX provides access to the terminal control "termios" interfaces defined by
POSIX, and some of the extensions to it in Linux. By using termios, programs
can control serial devices, consoles and virtual terminals. Terminal control
in POSIX revolves around a C language structure called
.codn "struct termios" .
This is mirrored in a \*(TL structure also called
.codn termios .

Like-named \*(TL functions are provided which correspond to the C functions
.codn tcgetattr ,
.codn tcsetattr ,
.codn tcsendbreak ,
.codn tcdrain ,
.code tcflush
and
.codn tcflow .

These have somewhat different argument conventions. The TTY device is specified last,
so that it can conveniently default to the
.code *stdin*
stream. A TTY device can be specified as either a stream object or a numeric
file descriptor.

The functions
.codn cfgetispeed ,
.codn cfgetospeed ,
.code cfsetispeed
and
.code cfsetospeed
are not provided, because they are unnecessary. Device speed (informally, "baud rate")
is specified directly as a integer value in the
.code termios
structure. The \*(TL termios functions automatically convert between integer
values and the speed constants (like
.codn B38400 )
used by the C API.

All of the various termios-related constants are provided, including some non-standard
ones. They appear in lower case. For instance
.code IGNBRK
and
.code PARENB
are simply known as the predefined \*(TL variables
.code ignbrk
and
.codn parenb .

.coNP Structure @ termios
.synb
.mets (defstruct termios nil
.mets \ \ iflag oflag cflag lflag
.mets \ \ cc ispeed ospeed)
.syne
.desc
The
.code termios
structure represents the kernel level terminal device configuration.
It holds hardware related setting such as serial line speed, parity
and handshaking. It also holds software settings like translations,
and settings affecting input behaviors. The structure closely corresponds
to the C language
.code termios
structure which exists in the POSIX API.

The
.codn iflag ,
.codn oflag ,
.code cflag
and
.code lflag
slots correspond to the
.codn c_iflag ,
.codn c_oflag ,
.code c_cflag
and
.code c_lflag
members of the C structure. They hold integer values representing
bit fields.

The
.code cc
slot corresponds to the
.code c_cc
member of the C structure. Whereas the
C structure's
.code c_cc
member is an array of the C type
.codn cc_t ,
the
.code cc
slot is a vector of integers, whose values must have the same range as the
.code cc_t
type.

.coNP Variables @, ignbrk @, brkint @, ignpar @, parmrk @, inpck @, istrip @, inlcr @, igncr @, icrnl @, iuclc @, ixon @, ixany @, ixoff @ imaxbel and @ iutf8
.desc
These variables specify bitmask values for the
.code iflag
slot of the
.code termios
structure. They correspond to the C language preprocessor symbols
.codn IGNBRK ,
.codn BRKINT ,
.code IGNPAR
and so forth.

The
.code imaxbel
and
.code iutf8
variables are specific to Linux and may not be present.
Portable code should test for their presence with
.codn boundp .

The
.code iuclc
variable is a legacy feature not found on all systems.

Note: the
.code termios
methods
.code set-iflags
and
.code clear-iflags
provide a convenient means for setting and clearing combinations of
these flags.

.coNP Variables @, opost @, olcuc @, onlcr @, ocrnl @, onocr @, onlret @, ofill @, ofdel @, vtdly @, vt0 @, vt1 @, nldly @, nl0 @, nl1 @, crdly @, cr0 @, cr1 @, cr2 @, cr3 @, tabdly @, tab0 @, tab1 @, tab2 @, tab3 @, bsdly @, bs0 @, bs1 @, ffdly @ ff0 and @ ff1
.desc
These variables specify bitmask values for the
.code oflag
slot of the
.code termios
structure. They correspond to the C language preprocessor symbols
.codn OPOST ,
.codn OLCUC ,
.code ONLCR
and so forth.

The variable
.code ofdel
is Linux-specific. Portable programs should test for its presence using
.codn boundp .

The
.code olcuc
variable is a legacy feature not found on all systems.

Likewise, whether the following groups of symbols are present is
platform-specific:
.codn nldly ,
.code nl0
and
.codn nl1 ;
.codn crdly ,
.codn cr0 ,
.codn cr1 ,
.code cr2
and
.codn cr3 ;
.codn tabdly ,
.codn tab0 ,
.codn tab1 ,
.code tab2
and
.codn tab3 ;
.codn bsdly ,
.code bs0
and
.codn bs1 ;
and
.codn ffdly ,
.code ff0
and
.codn ff1 .

Note: the
.code termios
methods
.code set-oflags
and
.code clear-oflags
provide a convenient means for setting and clearing combinations of
these flags.

.coNP Variables @, csize @, cs5 @, cs6 @, cs7 @, cs8 @, cstopb @, cread @, parenb @, parodd @, hupcl @, clocal @, cbaud @, cbaudex @ cmspar and @ crtscts
.desc
These variables specify bitmask values for the
.code cflag
slot of the
.code termios
structure. They correspond to the C language preprocessor symbols
.codn CSIZE ,
.codn CS5 ,
.code CS6
and so forth.

The following are present on Linux, and may not be available
on other platforms. Portable code should test for them using
.codn boundp :
.codn cbaud ,
.codn cbaudex ,
.code cmspar
and
.codn crtscts .

Note: the
.code termios
methods
.code set-cflags
and
.code clear-cflags
provide a convenient means for setting and clearing combinations of
these flags.

.coNP Variables @, isig @, icanon @, echo @, echoe @, echok @, echonl @, noflsh @, tostop @, iexten @, xcase @, echoctl @, echoprt @, echoke @, flusho @ pendin and @ extproc
.desc
These variables specify bitmask values for the
.code lflag
slot of the
.code termios
structure. They correspond to the C language preprocessor symbols
.codn ISIG ,
.codn ICANON ,
.code ECHO
and so forth.

The following are present on Linux, and may not be available
on other platforms. Portable code should test for them using
.codn boundp :
.codn iexten ,
.codn xcase ,
.codn echoctl ,
.codn echoprt ,
.codn echoke ,
.codn flusho ,
.code pendin
and
.codn extproc .

Note: the
.code termios
methods
.code set-lflags
and
.code clear-lflags
provide a convenient means for setting and clearing combinations of
these flags.

.coNP Variables @, vintr @, vquit @, verase @, vkill @, veof @, vtime @, vmin @, vswtc @, vstart @, vstop @, vsusp @, veol @, vreprint @, vdiscard @, vwerase @ vlnext and @ veol2
.desc
These variables specify integer offsets into the vector stored in the
.code cc
slot of the
.code termios
structure. They correspond to the C language preprocessor symbols
.codn VINTR ,
.codn VQUIT ,
.code VERASE
and so forth.

The following are present on Linux, and may not be available
on other platforms. Portable code should test for them using
.codn boundp :
.codn vswtc ,
.codn vreprint ,
.codn vdiscard ,
.code vlnext
and
.codn veol2 .

.coNP Variables @, tcooff @, tcoon @ tcioff and @ tcion
.desc
These variables hold integer values suitable as the
.meta action
argument of the
.code tcflow
function. They correspond to the C language preprocessor symbols
.codn TCOOFF ,
.codn TCOON ,
.code TCIOFF
and
.codn TCION .

.coNP Variables @, tciflush @ tcoflush and @ tcioflush
.desc
These variables hold integer values suitable as the
.meta queue
argument of the
.code tcflush
function. They correspond to the C language preprocessor symbols
.codn TCIFLUSH ,
.code TCOFLUSH
and
.codn TCIOFLUSH .

.coNP Variables @, tcsanow @ tcsadrain and @ tcsaflush
.desc
These variables hold integer values suitable as the
.meta actions
argument of the
.code tcsetattr
function. They correspond to the C language preprocessor symbols
.codn TCSANOW ,
.code TCSADRAIN
and
.codn TCSAFLUSH .

.coNP Functions @ tcgetattr and @ tcsetattr
.synb
.mets (tcgetattr <> [ device ])
.mets (tcsetattr < termios < actions <> [ device ])
.syne
.desc
The
.code tcgetattr
and
.code tcsetattr
functions, respectively, retrieve and install the configuration
of the terminal driver associated with the specified device.

These functions are wrappers for the like-named POSIX C library functions,
but with different argument conventions, and operating using
a \*(TL structure.

The
.code tcgetattr
function, if successful, returns a new instance of the
.code termios
structure.

The
.code tcsetattr
function requires an instance of a
.code termios
structure as an argument to its
.meta termios
parameter.

A program may alter the settings of a terminal device by
retrieving them using
.codn tcgetattr ,
manipulating the structure returned by this function, and
then using
.code tcsetattr
to install the modified structure into the device.

The
.meta actions
argument of
.code tcsetattr
may be given as the value of one of the variables
.codn tcsanow ,
.code tcsadrain
or
.codn tcsaflush .
If it is omitted, the default is
.codn tcsadrain .

If an argument is given for
.meta device
it must be either a stream, or an integer file descriptor.
In either case, it is expected to be associated with a
terminal (TTY) device.

If the argument is omitted, it defaults to the stream currently
stored in the
.code *stdin*
stream special variable, expected to be associated with
a terminal device.

.TP* Notes:

The C
.code termios
structure usually does not have members for representing the input
and output speed. \*(TL does not use such members, in any case, even
if they are present. The speeds are encoded in the
.code cc_iflag
and
.code cc_lflag
bitmasks. When retrieving the settings, the
.code tcgetattr
function uses the POSIX functions
.code cfgetispeed
and
.code cfgetospeed
to retrieve the speed values from the C structure. These values
are installed as the
.code ispeed
and
.code ospeed
slots of the Lisp structure.   A reverse conversion takes place
when setting are installed using
.codn tcsetattr :
the speed values are taken from the slots, and installed into
the C structure using
.code cfsetispeed
and
.code cfsetospeed
before the structure is passed to the C
.code tcsetattr
function.

On Linux, TTY devices do not have a separate input and output speed.
The C
.code termios
structure stores only one speed which is taken as both the input
and output speed, with a special exception. The input speed may be
programmed as zero. In that case, it is independently represented.
speed may be programmed as zero.

.coNP Function @ tcsendbreak
.synb
.mets (tcsendbreak >> [ duration <> [ device ]])
.syne
.desc
The
.code tcsendbreak
function generates a break signal on serial devices. The
.meta duration
parameter specifies the length of the break signal in milliseconds.
If the argument is omitted, the value 500 is used.

The
.meta device
parameter is exactly the same as that of the
.code tcsetattr
function.

.coNP Function @ tcdrain
.synb
.mets (tcdrain <> [ device ])
.syne
.desc
The
.code tcdrain
function waits until all queued output on a terminal
device has been transmitted. It is a direct wrapper
for the like-named POSIX C function.

The
.meta device
parameter is exactly the same as that of the
.code tcsetattr
function.

.coNP Function @ tcflush
.synb
.mets (tcflush < queue <> [ device ])
.syne
.desc
The
.code tcflush
function discards either untransmitted output data,
or received and yet unread input data, depending on the
value of the
.meta queue
argument. It is a direct wrapper for the like-named
POSIX C function.

The
.meta queue
argument should be the value of one of the variables
.codn tciflush ,
.code tcoflush
and
.codn tcioflush ,
which specify the flushing of input data, output
data or both.

The
.meta device
parameter is exactly the same as that of the
.code tcsetattr
function.

.coNP Function @ tcflow
.synb
.mets (tcflow < action <> [ device ])
.syne
.desc
The
.code tcflow
function provides bi-directional flow control on the
specified terminal device. It is a direct wrapper
for the like-named POSIX C function.

The
.meta action
argument should be the value of one of the
variables
.codn tcooff ,
.codn tcoon ,
.code tcioff
and
.codn tcion .

The
.meta device
parameter is exactly the same as that of the
.code tcsetattr
function.

.coNP Methods @, set-iflags @, set-oflags @, set-cflags @, set-lflags @, clear-iflags @, clear-oflags @ clear-cflags and @ clear-lflags
.synb
.mets << termios .(set-iflags << flags *)
.mets << termios .(set-oflags << flags *)
.mets << termios .(set-cflags << flags *)
.mets << termios .(set-lflags << flags *)
.mets << termios .(clear-iflags << flags *)
.mets << termios .(clear-oflags << flags *)
.mets << termios .(clear-cflags << flags *)
.mets << termios .(clear-lflags << flags *)
.syne
.desc
These methods of the
.code termios
structure set or clear multiple flags of the four bitmask flag fields.

The
.meta flags
arguments specify zero or more integer values. These values
are combined together bitwise, as if by the
.code logior
function to form a single effective mask.
If there are no
.meta flags
arguments, then the effective mask is zero.

The
.code set-iflags
method sets, in the
.code iflag
member of the
.meta termios
structure, all of the bits which
are set in the effective mask. That is to say,
the effective mask is combined with the value in
.code iflag
by a
.code logior
operation, and the result is stored back into
.codn iflag .
Similarly, the
.codn set-oflags ,
.code set-cflags
and
.code set-lflags
methods operate on the
.codn oflag ,
.code cflag
and
.code lflag
slots of the structure.

The
.code clear-iflags
method clears, in the
.code iflag
member of the
.meta termios
structure, all of the bits which are
set in the effective mask. That is to say,
the effective mask is bitwise inverted as if
by the
.code lognot
function, and then combined with the
existing value of the
.code iflag
slot using
.codn logand .
The resulting value is stored back into the
.code iflag
slot.
Similarly, the
.codn clear-oflags ,
.code clear-cflags
and
.code clear-lflags
methods operate on the
.codn oflag ,
.code cflag
and
.code lflag
slots of the structure.

Note: the methods
.codn go-raw ,
.code go-cbreak
and
.code go-canon
are provided for changing the settings to raw, "cbreak" and canonical mode.
These methods should be preferred to directly manipulating the flag and
.code cc
slots.

.TP* Example

In this example,
.code tio
is assumed to be a variable holding an instance of a
.code termios
struct:

.cblk
  ;; clear the ignbrk, brkint, and various other flags:
  tio.(clear-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon)

  ;; set the csize and parenb flags:
  tio.(set-cflags csize parenb)
.cble

.coNP Methods @ go-raw and @ go-cbreak
.synb
.mets << termios .(go-raw)
.mets << termios .(go-cbreak)
.syne
.desc
The
.code go-raw
and
.code go-cbreak
methods of the
.code termios
structure manipulate the flag slots, as well as certain elements
of the
.code cc
slot, in order to prepare the terminal settings for, respectively,
"raw" and "cbreak" mode, described below.

Note that manipulating the
.code termios
structure doesn't actually put these settings into effect in
the terminal device; the settings represented by the structure must
be installed into the device using
.codn tcsetattr .
There is no way to reverse the effect of these methods.
To precisely restore the previous terminal settings, the program
should retain a copy of the original
.code termios
structure.

"Raw" mode refers to a configuration of the terminal device driver in which input
and output is passed transparently and without accumulation, conversion or
interpretation. Input isn't buffered into lines; as soon as a single byte is
received, it is available to the program. No special input characters such as
commands for generating an interrupt or process suspend request are processed
by the terminal driver; all characters are treated as input data.  Input isn't
echoed; the only output which takes place is that generated by program
output requests to the device.

"Cbreak" mode is named after a concept and function in the "curses" terminal
control library. It refers to a configuration of the terminal device driver
which is less transparent than "raw" mode. Input isn't buffered into lines,
and line editing commands are ordinary input characters, allowing
character-at-a-time input. However, most input translations are preserved,
except that the conversion of CR characters to NL is disabled.  The
signal-generating characters are processed in this mode. This latter feature of
the configuration is the likely inspiration for the word "cbreak". Unless
otherwise configured, the interrupt character corresponds to the Ctrl-C key,
and "break" is another term for an interactive interruption.

.coNP Methods @ string-encode and @ string-decode
.synb
.mets << termios .(string-encode)
.mets << termios .(string-decode << string )
.syne
.desc
The
.code string-encode
method converts the terminal state stored in a
.code termios
structure into a textual format, returning that representation
as a character string.

The
.code string-decode
method parses the character representation produced by
.code string-encode
and populates the
.meta termios
structure with the settings are encoded in that string.

If a string is passed to
.code string-decode
which wasn't produced by
.codn string-encode ,
the behavior is unspecified. An exception may or may not be
thrown, and the contents of
.meta termios
may or may not be affected.

Note: the textual representation produced by
.code string-encode
is intended to be identical to that produced by the
.code -g
option of the GNU Coreutils version of the
.code stty
utility, on the same platform. That is to say, the output of
.code "stty -g"
may be used as input into
.codn string-decode ,
and the output of
.code string-encode
may be used as an argument to
.codn stty .

.SS* Web Programming Support

.coNP Functions @ url-encode and @ url-decode
.synb
.mets (url-encode < string <> [ space-plus-p ])
.mets (url-decode < string <> [ space-plus-p ])
.syne
.desc
These functions convert character strings to and from a form which is suitable 
for embedding into the request portions of URL syntax.

Encoding a string for URL use means identifying in it certain characters that
might have a special meaning in the URL syntax and representing it using
"percent encoding": the percent character, followed by the ASCII value of the
character.  Spaces and control characters are also encoded, as are all byte
values greater than or equal to 127 (7F hex).  The printable ASCII characters
which are percent-encoded consist of this set:

.cblk
  :/?#[]@!$&'()*+,;=%
.cble

More generally, strings can consists of Unicode characters, but the URL
encoding consists only of printable ASCII characters. Unicode characters in the
original string are encoded by expanding into UTF-8, and applying
percent-encoding the UTF-8 bytes, which are all in the range
.codn \exx80-\exxFF .

Decoding is the reverse process: reconstituting the UTF-8 byte sequence
specified by the URL-encoding, and then decoding the UTF-8 sequence into the
string of Unicode characters.

There is an additional complication: whether or not to encode spaces as plus,
and to decode plus characters to spaces. In encoding, if spaces are not encoded
to the plus character, then they are encoded as
.codn %20 ,
since spaces are reserved
characters that must be encoded. In decoding, if plus characters are not
decoded to spaces, then they are left alone: they become plus characters in the
decoded string.

The
.code url-encode
function performs the encoding process. If the
.code space-plus-p
argument is omitted or specified as
.codn nil ,
then spaces are encoded as
.codn %20 .
If the argument is a value other than
.codn nil ,
then spaces are encoded as the
character
.code +
.codn (plus) .

The
.code url-decode
function performs the decoding process. If the
.code space-plus-p
argument is omitted or specified as
.codn nil ,
then
.code +
.code (plus)
characters in the
encoded data are retained as
.code +
characters in the decoded strings. Otherwise,
plus characters are converted to spaces.

.coNP Functions @, html-encode @ html-encode* and @ html-decode
.synb
.mets (html-encode << text-string )
.mets (html-decode << html-string )
.syne
.desc
The
.code html-encode
and
.code html-decode
functions convert between an HTML and raw
representation of of text.

The
.code html-encode
function returns a string which is based on the content of
.metn text-string ,
but in which all characters which have special meaning in HTML
have been replaced by HTML codes for representing those characters literally.
The returned string is the HTML-encoded verbatim representation of
.metn text-string .

The
.code html-decode
function converts
.metn html-string ,
which may contain HTML
character encodings, into a string which contains the actual characters
represented by those encodings.

The function composition
.code "(html-decode (html-encode text))"
returns a string which is equal to
.codn text .

The reverse composition
.code "(html-encode (html-decode html))"
does not necessarily return a string equal to
.codn html .

For instance if html is the string
.strn "<p>Hello, world&#33;</p>" ,
then
.code html-decode
produces
.strn "<p>Hello, world!</p>" .
From this,
.code html-encode
produces
.strn "&lt;p&gt;Hello, world!&lt;/p&gt;" .

The
.code html-encode*
function is similar to
.code html-encode
except that it does not encode the single and double quote characters
(ASCII 39 and 34, respectively). Text prepared by this function may not
be suitable for insertion into a HTML template, depending on the
context of its insertion. It is suitable as text placed between
tags but not necessary as tag attribute material.

.coNP Functions @ base64-encode and @ base64-decode
.synb
.mets (base64-encode < string <> [ column-width ])
.mets (base64-decode < string)
.syne
.desc
The
.code base64-encode
function converts the UTF-8 representation of
.meta string
to Base 64 and returns that representation as a string.

The
.code base64-decode
functions performs the opposite conversion; it extracts the
bytes encoded in a Base 64 string, and decodes them as UTF-8
to return a character string.

The Base 64 encoding divides the UTF-8 representation into groups of
six bits, each representing the values 0 to 63. Each value is then
mapped to the characters
.code A
to
.codn Z ,
.code a
to
.codn z ,
the digits
.code 0
to
.code 9
and the characters
.code +
and
.codn / .
One or two consecutive occurrences of the character
.code =
are added as padding so that the number of
non-whitespace characters is divisible by four. These characters map to
the code 0, but are understood not to contribute to the length of the
encoded message. The
.code base64-encode
function enforces this convention, but
.code base64-decode
doesn't require these padding characters.

Base64-encoding an empty string results in an empty string.

If the
.meta column-width
argument is passed to
.codn base64-encode ,
then the Base 64 encoded string, unless empty, contains newline
characters, which divide it into lines which are
.meta column-width
long, except possibly for the last line.

.SS* Filter Module
The filter module provides a trie (pronounced "try") data structure,
which is suitable for representing dictionaries for efficient filtering.
Dictionaries are unordered collections of keys, which are strings, which
have associated values, which are also strings.  A trie can be used to filter
text, such that keys appearing in the text are replaced by the corresponding
values. A trie supports this filtering operation by providing an efficient
prefix-based lookup method which only looks at each input character ones, and
which does not require knowledge of the length of the key in advance.

.coNP Function @ make-trie
.synb
.mets (make-trie)
.syne
.desc
The
.code make-trie
function creates an empty trie. There is no special data type for
a trie; a trie is some existing type such as a hash table.

.coNP Function @ trie-add
.synb
.mets (trie-add < trie < key << value )
.syne
.desc
The
.code trie-add
function adds the string
.meta key
to the trie, associating
it with
.metn value .
If
.meta key
already exists in
.metn trie ,
then the value is updated with
.metn value .

The
.meta trie
must not have been compressed with
.metn trie-compress .

A trie can contain keys which are prefixes of other keys. For instance
it can contain
.str dog
and
.strn dogma .
When a trie is used for matching
and substitution, the longest match is used. If the input presents
the text
.strn doggy ,
then the match is
.strn dog .
If the input is
.strn dogmatic ,
then
.str dogma
matches.

.coNP Function @ trie-compress
.synb
.mets (trie-compress << trie )
.syne
.desc
The
.code trie-compress
function changes the representation of
.meta trie
to a representation which occupies less space and supports faster lookups.
The new representation is returned.

The compressed representation of a trie does not support the
.code trie-add
function.

This function destructively manipulates
.metn trie ,
and may return an object
that is the same object as
.codn trie ,
or it may return a different object,
while at the same time still modifying the internals of
.metn trie .
Consequently, the program should not retain the input object
.codn trie ,
but use the returned object in its place.

.coNP Function @ trie-lookup-begin
.synb
.mets (trie-lookup-begin << trie )
.syne
.desc
The
.code trie-lookup-begin
function returns a context object for performing
an open-coded lookup traversal of a trie. The
.meta tri
argument
is expected to be a trie that was created by the
.code make-trie
function.

.coNP Function @ trie-lookup-feed-char
.synb
.mets (trie-lookup-feed-char < trie-context << char )
.syne
.desc
The
.code trie-lookup-feed-char
function performs a one character step in a trie
lookup. The
.meta trie-context
argument must be a trie context returned
by
.metn trie-lookup-begin ,
or by some previous call to
.codn trie-lookup-feed-char .
The
.meta char
argument is the next character to match.

If the lookup is successful (the match through the trie can continue
with the given character) then a new trie context object is returned.
The old trie context remains valid.

If the lookup is unsuccessful,
.code nil
is returned.

Note: determining whether a given string is stored in a trie can be
performed looking up every character of the string successively
with
.codn trie-lookup-feed-char ,
using the newly returned context
for each successive operation. If every character is found, it means
that either that exact string is found in the trie, or a prefix.
The ambiguity can be resolved by testing whether the trie has a value
at the last node using
.codn tree-value-at .
For instance, if
.str catalog
is inserted into an empty trie with value
.strn foo ,
then
.str cat
will look up successfully, being a prefix of
.strn catalog ;
however, the value at
.str cat
is
.codn nil ,
indicating that
.str cat
is only a prefix of one or more entries in the trie.

.coNP Function @ tree-value-at
.synb
.mets (trie-value-at << trie-context )
.syne
.desc
The
.code trie-value-at
function returns the value stored at the node in
in the trie given by
.metn trie-context .
Nodes which have not been given
a value hold the value
.codn nil .

.coNP Function @ filter-string-tree
.synb
.mets (filter-string-tree < filter << obj )
.syne
.desc
The
.code filter-string-tree
a tree structure similar to
.metn obj ,
in which all of the
string atoms have been filtered through
.metn filter .

The
.meta obj
argument is a string tree structure: either the symbol
.codn nil ,
denoting an empty structure; a string; or a list of tree structures. If
.meta obj
is
.codn nil ,
then
.code filter-string-tree
returns
.codn nil .

The
.meta filter
argument is a filter: it is either a trie, a function, or nil.
If
.meta filter
is
.codn nil ,
then
.code filter-string-trie
just returns
.metn obj .

If
.meta filter
is a function, it must be a function that can be called
with one argument. The strings of the string tree are filtered by passing
each one into the function and substituting the return value into the
corresponding place in the returned structure.

Otherwise if
.meta filter
is a trie, then this trie is used for filtering,
the string elements similarly to a function. For each string, a new
string is returned in which occurrences of the keys in the trie are
replaced by the values in the trie.

.coNP Function @ filter-equal
.synb
.mets (filter-equal < filter-1 < filter-2 < obj-1 << obj-2 )
.syne
.desc
The
.code filter-equal
function tests whether two string trees are equal
under the given filters.

The precise semantics can be given by this expression:

.cblk
.mets (equal (filter-string-tree < filter-1 << obj-1 )
.mets \ \ \ \ \ \  (filter-string-tree < filter-2 << obj-2 ))
.cble

The string tree
.meta obj-1
is filtered through
.metn filter-1 ,
as if by the
.code filter-string-tree
function, and similarly,
.meta obj-2
is
filtered through
.metn filter-2 .
The resulting structures are compared
using
.codn equal ,
and the result of that is returned.

.SS* Access To TXR Pattern Language From Lisp

It is useful to be able to invoke the abilities of the \*(TX pattern Language
from \*(TL. An interface for doing this provided in the form of the
.code match-fun
function, which is used for invoking a \*(TX pattern function.

The
.code match-fun
function has a cumbersome interface which requires the \*(TL program to
explicitly deal with the variable bindings emerging from the pattern match
in the form of an association list.

To make it the interface easier to use, \*(TX provides
the macros
.codn txr-if ,
.code txr-when
and
.codn txr-case .

.coNP Function @ match-fun
.synb
.mets (match-fun < name < args < input << files )
.syne
.desc
The
.code match-fun
function invokes a \*(TX pattern function whose name is
given by
.metn name ,
which must be a symbol.

The
.meta args
argument is a list of expressions. The expressions may be symbols
which will be interpreted as pattern variables, and may be bound or unbound.
If they are not symbols, then they are treated as expressions (of the
pattern language, not \*(TL) and evaluated accordingly.

The
.meta input
argument is a list of strings, which may be lazy. It represents the
lines of the text stream to be processed.

The
.meta file
argument is a list of filename specifications, which follow
the same conventions as files given on the \*(TX command line. If the pattern
function uses the
.code @(next)
directive, it can process these additional files.

The
.code match-fun
function's return value falls into three cases. If there is a
match failure, it returns
.codn nil .
Otherwise it returns a cons cell. The
.code car
field
of the cons cell holds the list of captured bindings. The
.code cdr
of the cons cell is one of two values. If the entire input was processed, the
cdr field holds the symbol
.codn t .
Otherwise it holds another cons cell whose
.code car
is the remainder of the list of lines which were not matched, and whose
.code cdr
is the line number.

.TP* Example:

.cblk
  @(define foo (x y))
  @x:@y
  @line
  @(end)
  @(do
     (format t "~s\en"
               (match-fun 'foo '(a b)
                          '("alpha:beta" "gamma" "omega") nil)))

  Output:
  (((a . "alpha") (b . "beta")) ("omega") . 3)
.cble

In the above example, the pattern function
.code foo
is called with arguments
.codn "(a b)" .
These are unbound variables, so they correspond to parameters
.code x
and
.code y
of the function. If
.code x
and
.code y
get bound, those values propagate to
.code a
and
.codn b .
The data being matched consists of the lines
.strn alpha:beta ,
.str gamma
and
.strn omega .
Inside
.codn foo ,
.code x
and
.code y
bind to
.str alpha
and
.strn beta ,
and then the line variable binds to
.strn gamma .
The input stream is left with
.strn omega .

Hence, the return value consists of the bindings of
.code x
and
.code y
transferred to
.code a
and
.codn b ,
and the second cons cell which gives information about the rest of the
stream: it is the part starting at
.strn omega ,
which is line 3. Note that the binding for the
.code line
variable does not propagate
out of the pattern function
.codn foo ;
it is local inside it.

.coNP Macro @ txr-if
.synb
.mets (txr-if < name <> ( argument *) < input < then-expr <> [ else-expr ])
.syne
.desc
The
.code txr-if
macro invokes the \*(TX pattern matching function
.meta name
on some input given by the
.meta input
parameter, which is a list of strings, or a single string.

If
.meta name
succeeds, then
.meta then-expr
is evaluated, and if it fails,
.meta else-expr
is evaluated instead.

In the successful case,
.meta then-expr
is evaluated in a scope in which the bindings emerging from the
.meta name
function are turned into \*(TL variables.
The result of
.code txr-if
is that of
.metn then-expr .

In the failed case,
.meta else-expr
is evaluated in a scope which does not have any new bindings.
The result of
.code txr-if
is that of
.metn else-expr .
If
.meta else-expr
is missing, the result is
.codn nil .

The
.meta argument
forms supply arguments to the pattern function
.metn name .
There must be as many of these arguments as the function
has parameters.

Any argument which is a symbol is treated, for the purposes
of calling the pattern function, as an unbound pattern variable.
The function may or may not produce a binding for that variable.
Also, every argument which is a symbol also denotes a local variable
that is established around
.meta then-expr
if the function succeeds. For any such pattern variable for which the function
produces a binding, the corresponding local variable will be initialized
with the value of that pattern variable. For any such pattern variable
which is left unbound by the function, the corresponding local variable
will be set to
.codn nil .

Any
.meta argument
can be a form other than a symbol. In this situation, the argument is
evaluated, and will be passed to the pattern function as the value of
the binding for the corresponding argument.

.TP* Example:

.cblk
  @(define date (year month day))
  @{year /\ed\ed\ed\ed/}-@{month /\ed\ed/}-@{day /\ed\ed/}
  @(end)
  @(do
     (each ((date '("09-10-20" "2009-10-20" "July-15-2014" "foo")))
       (txr-if date (y m d) date
         (put-line `match: year @y, month @m, day @d`)
         (put-line `no match for @date`))))

  Output:

  no match for 09-10-20
  match: year 2009, month 10, day 20
  no match for July-15-2014
  no match for foo
.cble

.coNP Macro @ txr-when
.synb
.mets (txr-when < name <> ( argument *) < input << form *)
.syne
.desc
The
.code txr-when
macro is based on
.codn txr-if .
It is equivalent to
.code

.cblk
.meti \ \ (txr-if < name <> ( argument *) < input (progn << form *))
.cble

If the pattern function
.meta name
produces a match, then each
.meta form
is evaluated in the scope of the variables established by the
.meta argument
expressions. The result of the
.code txr-when
form is that of the last
.metn form .

If the pattern function fails then the forms are not evaluated,
and the result value is
.codn nil .

.coNP Macro @ txr-case
.synb
.mets (txr-case < input-form
.mets \ \  >> {( name <> ( argument *) << form *)}*
.mets \ \  >> [( t << form *)])
.syne
.desc
The
.code txr-case
macro evaluates
.meta input-form
and then uses the value as an input to zero or more test clauses.
Each test clause invokes the pattern function named by that clause's
.meta name
argument.

If the function succeeds, then each
.meta form
is evaluated, and the value of the last
.meta form
is taken to be the result value of
.codn txr-case ,
which terminates. If there are no forms, then
.code txr-case
terminates with a
.code nil
result.

The forms are evaluated in an environment in which variables are bound
based on the
.meta argument
forms, with values depending on the result of the
invocation of the
.meta name
pattern function, in the same manner as documented in detail for the
.code txr-if
macro.

If the function fails, then the forms are not evaluated, and control passes to
the next clause.

A clause which begins with the symbol
.code t
executes unconditionally and causes
.code txr-case
to terminate. If it has no forms, then
.code txr-case
yields
.codn nil ,
otherwise the forms are evaluated in order and the value of the last
one specifies the result of
.codn txr-case .

.SS* Debugging Functions
.coNP Functions @ source-loc and @ source-loc-str
.synb
.mets (source-loc << form )
.mets (source-loc-str < form <> [ alternative ])
.syne
.desc
These functions map an expression in a \*(TX program to the file name and
line number of the source code where that form came from.

The
.code source-loc
function returns the raw information as a cons cell
whose
.cod3 car / cdr
consist of the line number, and file name.

The
.code source-loc-str
function formats the information as a string.

Forms which were parsed from a file have source location info
tracking to their origin in that file. Forms which are the result
of macro-expansion are traced to the form whose evaluation produced
them. That is to say, they inherit that form's source location info.

More precisely, when a form is produced by macro-expansion,
it usually consists of material which was passed to the macro as arguments,
plus some original material allocated by the macro, and possibly
literal structure material which is part of the macro code.
After the expansion is produced, any of its constituent material
which already has source location info keeps that info. Those nodes
which are newly allocated by the macro-expansion process inherit
their source location info from the form which yields the expansion.

If
.meta form
is not a piece of the program source code that was constructed by the
\*(TX parser or by a macro, and thus it was neither attributed with
source location info, nor has it inherited such info, then
.code source-loc
returns
.codn nil .

In the same situation, and if its
.meta alternative
argument is missing, the
.code source-loc-str
returns a string whose text conveys that the source location is not
available. If the
.meta alternative
argument is present, it is returned.

.coNP Function @ rlcp
.synb
.mets (rlcp < dest-form << source-form )
.syne
.desc
The
.code rlcp
function copies the source code location info ("rl" means "read location")
from the
.meta source-form
object to the
.meta dest-form
object. These objects
are pieces of list-based syntax.

Note: the function is intended to be used in macros. If a macro transforms
.meta source-form
to
.metn dest-form ,
this function can be used to propagate the
source code location info also, so that when the \*(TL evaluator
encounters errors in transformed code, it can give diagnostics which refer
to the original untransformed source code.

.coNP Function @ macro-ancestor
.synb
.mets (macro-ancestor << form )
.syne
.desc
The
.code macro-ancestor
function returns information about the macro-expansion ancestor of
.metn form .
The ancestor is the original form whose expansion produced
.metn form .

If
.meta form
is not the result of macro-expansion, or the ancestor information
is unavailable, the function returns
.codn nil .

.SS* Profiling
.coNP Operator @ prof
.synb
.mets (prof << form *)
.syne
.desc
The
.code prof
operator evaluates the enclosed forms from left to right similarly
to
.codn progn ,
while determining the memory allocation requests and time
consumed by the evaluation of the forms.

If there are no forms, the prof operator measures the smallest measurable
operation of evaluating nothing and producing
.codn nil .

If the evaluation terminates normally (not abruptly by a non-local
control transfer), then
.code prof
yields a list consisting of:

.cblk
.mets >> ( value < malloc-bytes < gc-bytes << milliseconds )
.cble

where
.meta value
is the value returned by the rightmost
.metn form ,
or
.code nil
if there are no forms,
.meta malloc-bytes
is the total number of bytes of all memory allocation
requests (or at least those known to the \*(TX runtime, such as those of all
internal objects),
.meta gc-bytes
is the total number of bytes drawn from the
garbage-collected heaps, and
.meta milliseconds
is the total processor time
consumed over the execution of those forms.

Notes:

The bytes allocated by the garbage collector from the C function
.code malloc
to create
heap areas are not counted as
.metn malloc-bytes .
.meta malloc-bytes
includes storage
such as the space used for dynamic strings, vectors and bignums (in addition to
their gc-heap allocated nodes), and the various structures used by the
.code cobj
type objects such as streams and hashes. Objects in external libraries that use
uninstrumented allocators are not counted: for instance the C
.code "FILE *"
streams.

.coNP Macro @ pprof
.synb
.mets (pprof << form *)
.syne
.desc
The
.code pprof
(pretty-printing
.codn prof )
macro is similar to
.codn progn .
It evaluates
.metn form -s,
and returns the rightmost one, or
.code nil
if there are no forms.

Over the evaluation of
.metn form -s,
it counts memory allocations, and measures
CPU time. If
.metn form -s
terminate normally, then just prior to returning,
.code pprof
prints these statistics in a concise report on the
.codn *std-output* .

The
.code pprof
macro relies on the
.code prof
operator.

.SS* Garbage Collection
.coNP Function @ sys:gc
.synb
.mets (sys:gc)
.syne
.desc
The
.code gc
function triggers garbage collection.  Garbage collection means
that unreachable objects are identified and reclaimed, so that their
storage can be re-used.

The function returns
.code nil
if garbage collection is disabled (and consequently nothing is done), otherwise
.codn t .

.coNP Function @ sys:gc-set-delta
.synb
.mets (sys:gc-set-delta << bytes )
.syne
.desc
The
.code gc-set-delta
function sets the GC delta parameter.

Note: This function may disappear in a future release of \*(TX or suffer
a backward-incompatible change in its syntax or behavior.

When the amount of new dynamic memory allocated since the last garbage
collection equals or exceeds the GC delta, a garbage collection pass is
triggered. From that point, a new delta begins to be accumulated.

Dynamic memory is used for allocating heaps of small garbage-collected objects
such as cons cells, as well as the satellite data attached to some objects:
like the storage arrays of vectors, strings or bignum integers. Most garbage
collector behaviors are based on counting objects in the heaps.

Sometimes a program works with a small number of objects which are very large,
frequently allocating new, large objects and turning old ones into garbage.
For instance a single large integer could be many megabytes long.  In such a
situation, a small number of heap objects therefore control a large amount of
memory.  This requires garbage collection to be triggered much more often than
when working with small objects, such as conses, to prevent runaway allocation
of memory. It is for this reason that the garbage collector uses the GC delta.

There is a default GC delta of 64 megabytes. This may be overridden in
special builds of \*(TX for small systems.

.coNP Function @ finalize
.synb
.mets (finalize < object < function <> [ reverse-order-p ])
.syne
.desc
The
.code finalize
function registers
.meta function
to be invoked in the situation when
.meta object
is identified by the garbage collector as unreachable.
This function is called a finalizer.

If and when this situation occurs, the finalizer
.meta function
will be called with
.meta object
as its only argument.

Multiple finalizer functions can be registered for the same object.
They are all called when the object becomes unreachable.

If the
.meta reverse-order-p
argument isn't specified, or is
.codn nil ,
then finalizer is registered at the end of the list.

If
.meta reverse-order-p
is true, then the finalizer is registered at the front of
the list.

Finalizers which are activated in the same finalization processing phase
are called in the order in which they appear in the
registration list.

After a finalization call takes place, its registration is removed.  However,
neither
.meta object
nor
.meta function
are reclaimed immediately; they are treated as if they were reachable objects
until at least the next garbage collection pass.
It is therefore safe for
.meta function
to store somewhere a persistent reference to
.meta object
or to itself, thereby reinstating these objects as reachable.

A finalizer is itself permitted to call
.code finalize
to register the original
.code object
or any other object for finalization. Such registrations made during
finalization execution are not eligible for the current phase of finalization
processing; they will be processed in a later garbage collection pass.

.coNP Function @ call-finalizers
.synb
.mets (call-finalizers << object )
.syne
.desc
The
.code call-finalizers
function invokes and removes the finalizers, if any, registered against
.metn object .
If any finalizers are called, it returns
.codn t ,
otherwise
.codn nil .

Note: the behavior is unspecified if a finalizer function calls
.codn call-finalizers .

.SS* Modularization
.coNP Variable @ self-path
.desc
This variable holds the invocation path name of the \*(TX program.
The value of
.code self-path
when \*(TL expressions are being evaluated in command line arguments
is the string
.strn cmdline-expr .
The value of
.code self-path
when a \*(TX query is supplied on the command line via the
.code -c
command line option is the string
.strn cmdline .

Note that for programs read from a file,
.code self-path
holds the resolved name, and not the invocation name. For instance if
.code foo.tl
is invoked using the name
.codn foo ,
whereby \*(TX infers the suffix, then
.code self-path
holds the suffixed name.

.coNP Variable @ stdlib
.desc
The
.code stdlib
variable expands to the directory where the \*(TX standard library
is installed.

Note: there is no need to use the value of this variable to load library
modules. Library modules are keyed to specific symbols, and lazily loaded. When
a \*(TL library function, macro or variable is referenced for the first time,
the library module which defines it is loaded.  This includes references
which occur during the code expansion phase, at "macro time", so it works for
macros. In the middle of processing a syntax tree, the expander may encounter a
symbol that is registered for auto-loading, and trigger the load. When the load
completes, the symbol might now be defined as a macro, which the expander
can immediately use to expand the given form that is being traversed.

.coNP Macro @ load
.synb
.mets (load << target )
.syne
.desc
The
.code load
macro causes a file of \*(TL code to be read and evaluated.
The
.meta target
argument is a string. If
.meta target
specifies a relative pathname, then it is assumed to be a reference relative
to the directory of the file in which the
.code load
macro form occurs.

If
.meta target
has no suffix, then
.code load
first tries to load the un-suffixed name. If that cannot be opened, the
.str .tl
suffix is added to the path and another attempt is made. If that fails,
an exception is thrown.

If
.meta target
has a
.str .txr
suffix, it is assumed to be a \*(TX query language file, and
an exception of type
.code eval-error
is thrown, since this is not supported.

If
.meta target
is successfully resolved and opened, \*(TL forms are read from the file
in succession. Each form is evaluated as if by the
.code eval
function, before the next form is read.
If a syntax error is encountered, an exception of type
.code eval-error
is thrown.

Parser error messages are directed to the
.code *stderr*
stream.

.coNP Symbol Macro @ self-load-path
.desc
The
.code self-load-path
symbol macro expands to a string which holds the name of the file being
loaded. This is a symbol macro rather than a variable so that it can
be replaced during the macro-expansion process, thereby permanently embedding
the file name into the expanded code.

An expansion for
.code self-load-path
is established for a \*(TX or \*(TL file which is loaded from the
command line.

If the
.code -i
command line option is used to enter the interactive listener,
and a file to be loaded is also specified, then the
.code self-load-path
macro remains bound to the name of that file.

An expansion for
.code self-load-path
is also established by the
.code load
function and the
.code @(load)
directive, referring to the file being loaded.  When loading completes, the
previous expansion of
.code self-load-path
is restored.

During the processing of the profile file (see Interactive Profile File),
the variable is bound to the name of that file.

.coNP Variable @ txr-path
.desc
This variable holds the absolute path name of the directory which
holds the executable file of the current process.

.SH* INTERACTIVE LISTENER

.SS* Overview

On some target platforms, \*(TX provides an interactive listener, which is
invoked using the
.code -i
command line option. The interactive listener provides features like visual
editing of the command line, tab completion on \*(TL symbols, and history
recall.

.SS* Basic Operation

The interactive listener prints a numbered prompt.  The number in the prompt increments with every
command.  The first command line is numbered 1, the second one 2 and so forth.

The listener accepts input characters from the terminal. Characters are either
interpreted as editing commands or other special characters, or else are
inserted into the editing buffer. However, control characters which don't
correspond to commands are silently rejected.

The carriage return character generated by the Enter key indicates that a
complete line has been entered, and it is to be interpreted. The listener
parses the line as a \*(TL expression, evaluates it, and prints the resulting
value. If the evaluation of the line throws an exception, the listener
intercepts the exception and prints information about it preceded by
two asterisks and a space. These asterisks distinguish an exception from a
result value.

If an empty line is entered, or a line containing only spaces, tabs
or embedded carriage returns or linefeeds, the prompt is repeated without
incrementing the number. Such a line is not entered into the history.

A line which only contains a \*(TL comment (optional spaces, tabs or embedded
carriage returns or linefeeds, followed by a semicolon), also causes
the prompt to be repeated without incrementing the number. However,
such a line
.B is
entered into the history.

.SS* Limitations

The interactive listener can only accept up to 1023 characters of input
in a single command line. The command line must contain exactly one complete
\*(TL expression, or a comment. Multiple expressions will not be evaluated.
Expressions cannot be continued across multiple lines of entry.

The interactive listener is based on 8 bit character processing. Its editing
functions do not recognize UTF-8 multi-byte characters.

The screen updating logic in the listener is based on the assumption that
the display terminal uses DEC VT100 emulation. No other terminal emulation
is supported. The
.code TERM
environment variable is ignored.

.SS* Ways to Quit

Pressing Ctrl-D in a completely empty command line terminates the listener.
Another way to quit is to enter the
.code :quit
keyword symbol. When the form input into the listener consists of this symbol,
the listener will terminate:

.cblk
  1> (+ 2 2)
  4
  2> :quit
  os-shell $
.cble

Another way to terminate is to evaluate a call to the
.code exit
function. This method allows a termination status to be specified:

.cblk
  1> (exit 1)
  os-shell $
.cble

Raising a fatal signal with the
.code raise
function is another way to quit:

.cblk
  1> (raise sig-abrt)
  Aborted (core dumped)
  os-shell $
.cble

.SS* Interrupting Evaluation

Ctrl-C typed while editing a command line is interpreted as an editing command
which causes that command line to be canceled. The listener prints the string
.str ** intr
and repeats the same prompt.

If a command line is submitted for evaluation, the evaluation might take
a long time or block for input. In these situations, typing Ctrl-C will issue
an interrupt signal. The listener has installed a handler for this signal which
generates an exception of type
.code error
which is caught by the listener. The exception's message is the string
.str intr
so that the listener ends up printing
.str intr **
like in the case of the Ctrl-C editing command. In this situation, though new
command line prompt is issued with an incremented number, and the exception
is recorded as a value.

.SS* Listener Variables

.coNP Variables @, *0 @, *1 @, *2 @, ... @ *99
.desc
The listener provides useful variables which allow commands to reference
the results of previous commands. As noted previously, the commands
are enumerated with an incrementing number. Each command's number, modulo 100,
corresponds to one of the variables
.codn *0 ,
.codn *1 ,
.codn *2 ,
.codn ... ,
.codn *99 .
Thus, up to the previous hundred results can be referenced:

.cblk
  ...
  99> (+ 2 2)  ;; stored in *99
  4
  100> (* 3 2) ;; stored in *0
  6
  101> (+ *99 *0) ;; i.e. (+ 4 6)
  10
.cble

.coNP Variable @ *n
.desc
The listener variable
.code *n
evaluates to the current command line number: the number of the command in
which the variable occurs:

.cblk
  5> *n
  5
  6> (* 2 *n)
  12
.cble

.coNP Variable @ *v
.desc
The listener variable
.code *v
evaluates to the current variable number: the command number modulo 100:

.cblk
  103> *v
  3
  104> *v
  4
.cble

.coNP Variable @ *r
.desc
The listener variable
.code *r
evaluates to a hash table which associates variable numbers with command
results:

.cblk
  213> 42
  42
  214> [*r 13]
  42
.cble

The result hash allows relative addressing. For instance the expression
.code "[*r (mod (pred *v) 100)]"
refers to the result of the previous command.

.SS* Exceptions

The interactive listener catches all exceptions. Each caught exception is
associated with the command's variable number, and stored as a value
in the appropriate listener variable as well as the
.code *r
result hash. Exceptions are turned into values by creating a cons cell
whose
.code car
is the exception symbol and whose
.code cdr
holds the exception's arguments.

For each caught exception, a message
is printed beginning with the sequence
.strn "** " .
Exactly how the message appears depends on the type and content of
the exception.

.SS* Editing

The following sections describe the interactive editing commands
available in the listener.

Terminals can often be configured with different choices of cursor
shape: such as a block-shaped cursor, an underline cursor or a
vertical line or "I-beam" cursor.  In the following sections, the
phrase "character under the cursor" refers to the character that is
currently covered by a block cursor, underlined by an underline cursor,
or that is immediately to the right of an I-beam cursor.

.NP* Move Left and Right

Moving within the line is achieved using the left and right arrow keys.  In
addition, Ctrl-B ("back") and Ctrl-F ("forward") perform this movement.

.NP* Jump to Beginning and End of Line

The Ctrl-A command moves to the beginning of the line. ("A" is the beginning
of the alphabet). The Ctrl-E ("end") command jumps to the end of the line,
such that the last character of the line is to the left of the cursor
position. On terminals which have the Home and End keys, these may also
be used instead of Ctrl-A and Ctrl-E.

In line mode, these commands move the cursor to the beginning or end of the
edit buffer.

In multi-line mode, if the cursor is not already at the beginning of a physical
line, then Ctrl-A moves it to the first character of the physical line.
Otherwise, Ctrl-A moves the cursor to the beginning of the edit buffer.

Similarly, in multi-line mode, if the cursor not already at the end of a
physical line, Ctrl-E moves it there. Otherwise, the cursor moves to the
end of the edit buffer.

.NP* Jump to Matching Parenthesis

If the cursor is on an opening or closing parenthesis, brace or bracket,
the Ctrl-] command tries to jump to the matching character. The logic for
finding the matching character is identical to that of the Parenthesis Matching
feature. If no matching character is found, then no movement takes place.

If the cursor is not on an opening or closing parenthesis, brace or bracket,
then the closest such character is found. The cursor is moved to that character
and then an attempt is made to jump to the matching one from that new
position.

If the cursor is equidistant to two such characters, then one of them
is chosen as follows. If the two characters are oriented in the same way (both
are opening and closing), then that one is chosen whose convex side faces the
cursor position.  Thus, effectively, an inner enclosure is favored over an
outer one.  Otherwise, if the two characters have opposite orientation (one is
opening and the other closing), then the one which is to the right of the
cursor position is chosen.

Note: the Ctrl-] character can be produced on some terminals using Ctrl-5
(using the keyboard home row 5, not the numeric keypad 5). This the same
key which produces the % character when Shift is used. The % character is
used in the Vi editor for parenthesis matching.

.NP* Character Swap

The Ctrl-T (twiddle) command exchanges the character under the cursor with the
previous character.

.NP* Delete Character Left

The Backspace key erases the character to the left of the cursor, and moves the
cursor to the position which that character occupied.

It doesn't matter whether this key generates ASCII
characters 8 (BS) or 127 (DEL): either one is acceptable. The Ctrl-H command
also performs the same action, since it corresponds to ASCII BS.

.NP* Delete Character Right

The Ctrl-D command is overloaded with two meanings. If the line is empty, it is
a quit indication. Otherwise, it deletes the character under the cursor
without changing the cursor position.  On terminals which have a Delete key,
the deleting action may also be performed with that key. The Delete key doesn't
have the quit indication meaning of Ctrl-D.

.NP* Delete Word Left

The Ctrl-W ("word") command deletes the word to the left of the cursor
position. More precisely, this command first deletes any consecutive whitespace
characters (spaces or tabs) to the left of the cursor. Then, it deletes
consecutive non-whitespace characters. Material under the cursor or to the
right remains.

.NP* Delete to Beginning of Line

The Ctrl-U ("undo typing") command is a "super backspace" operation: it deletes
all characters to the left of the cursor position. The cursor is moved to
the leftmost position.

In multi-line mode, Ctrl-U deletes only to the beginning of the current
physical line, not all the way to the first position of the buffer.

.NP* Delete to End of Line

The Ctrl-K ("kill") command deletes the character under the cursor position
and all subsequent characters. The cursor position doesn't change.

In multi-line mode, Ctrl-K deletes only until the end of the current
physical line, not the entire buffer.

.NP* Verbatim Character Insert

The Ctrl-V ("verbatim") command places the listener's input editor into
a mode in which the next character is interpreted literally and inserted
into the line, even if that character is a special character such as Enter,
or a command character.

.NP* Verbatim Insert Mode
The two-character sequence Ctrl-X, Ctrl-V ("extended verbatim", "super paste")
enters into an verbatim insert mode useful for entry of free-form text. It is
particularly useful in multi-line mode. In this mode, almost every character
is inserted verbatim, including Enter.  The only commands recognized are:
Ctrl-X, which terminates this mode, Backspace (both ASCII BS and DEL
variants) and arrow key navigation. Enter inserts a line break, which
appears as such in multi-line mode, or as
.code ^M
in line mode.

.NP* Delete Current Line

The Ctrl-X, Ctrl-K command sequence may be used in multi-line mode
to delete the entire physical line under the cursor. Any lines below that
line move up to close the gap. In line mode, the command has no effect,
other than canceling select mode.

.NP* History Recall

By default, the most recent 500 lines submitted to the interactive listener are
remembered in a history.  This history is available for recall, making it
convenient to repair mistakes, or compose new lines which are based on previous
lines.  Note that the the history suppresses consecutive duplicate lines.
The number of lines retained may be customized using the
.code *listener-hist-len*
variable.

If the up arrow is used while editing a line, the contents of the line are
placed into a temporary save area.  The line display is then updated to
show the most recent line of history.  Using the up arrow key additional times
will recall successively less recent lines.

The down arrow key navigates in the opposite direction: from older lines to
newer lines. When the down arrow key is invoked on the most recent history line,
then the current line is restored from the temporary save area.

Instead of the up and down arrow keys, the commands Ctrl-P ("previous")
and Ctrl-N ("next") may be used.

If the Enter key is pressed while a recalled history line is showing, then that
line will be submitted as if it were a newly composed line.  The originally
edited line which had been placed in the save area is discarded.

When a recalled line is showing, it may be edited. There are two important
behaviors to note here. If a recalled history line is edited, and then the
up/down arrow keys or a navigation command is used to show a different
history line, or to restore the original current line, then the edit is made
permanent: the edited line replaces its original version in the same
position in the history.  This feature allows corrections to be made to the
history.  However, if a recalled line is edited and submitted without
navigating to another line, then it is submitted as a newly composed line,
without replacing the original in the history.

Each submitted line is entered into the history, if it is different
from the most recent line already in history. This is true whether it
is a freshly composed line, a recalled history line, or an edited
history line.

.NP* History Search
It is possible to search backwards through the history interactively
for a line containing a substring. The Ctrl-R command is used to initiate
search.  The command prompt is replaced with the prefix
.code search:
next to which a pair of empty square brackets appears, indicating
that the listener is in search mode. The square brackets are the
search box, enclosing the search text, which is initially empty.

In search mode, characters may be typed. They accumulate inside the search
box, and constitute the string to search for. The listener instantly
navigates to the most recent line which contains a substring match for the
search string, and places the cursor on the first character of the
match. Control characters entered directly are ignored. The Ctrl-V command be
used to add a character verbatim, as in edit mode.

To remove characters from the search box, Backspace can be used. The
search is not repeated with the shortened search text: the same line
continues to show until a character is added, at which point
a new search is issued.

Search mode has a "home position": a starting point for searches.
The initial home position is whatever line of history is selected
when search mode is initiated. Searches work backward in history from
that line. If search text is edited by deleting characters and then
adding new ones, the new search proceeds from the home position.

The Ctrl-R command can be used in search mode. It registers the currently
showing line as the new home position, and then repeats the search using the
existing search text backwards from the new position. If the search text
is empty, Ctrl-R has no effect.

The Ctrl-C command leaves search mode at any time and causes the
listener to resume editing the original input at the original character
position. The Enter key accepts the result of a search and submits it
as if it were a newly composed line.

Navigation and editing keys may be used in search mode. A navigation or editing
key immediately cancels search mode, and is processed in edit mode, using
whatever line was located by the search, at the matching character position.

The Ctrl-L (Clear Screen and Refresh), as well as Ctrl-Z
(Suspend to Background) commands are available in search mode. Their effects
takes place without leaving search mode.

Navigating to a history line manually using the up and down arrow keys (or
Ctrl-P/Ctrl-N) has the same net effect same as locating that line using
Ctrl-R search.

.NP* Submit and Stay in History

Normally when the Enter key is used on a recalled history line,
the next time the listener is re-entered, it jumps back to the
newest history position where a new line is about to be composed.

The alternative command sequence Ctrl-X, Enter provides a useful alternative
behavior. After the submitted line is processed, the listener doesn't jump to
the newest history position. Instead, it stays in the history, advancing
forward by one position to the successor of the submitted line.

Ctrl-X, Enter can be used to conveniently submit a range of lines
from the history, one by one, in their original order.

.NP* Insert Previous Word

The equivalent command sequences Ctrl-X, w and Ctrl-X, Ctrl-W insert
a word from the previous line at the cursor position. A word is defined
as a sequence of non-whitespace characters, separated from other words
by whitespace. By default, the last word of the previous line is inserted.
Between the Ctrl-X and Ctrl-W or w, a decimal number can be entered.
The number 1 specifies that the last word is to be inserted, 2 specifies
the second last word, 3 the third word from the right and so on.
Only the most recent three decimal digits are retained, so the number can range
from 0 to 999. A value of 0, or a value which exceeds the number of words
causes the Ctrl-W or w to do nothing. Note that "previous line" means
relative to the current location in the history. If the 42nd most recent
history line is currently recalled, this command takes material from the 43rd
history line.

.NP* Insert Previous Atom

The equivalent command sequences Ctrl-X, a and Ctrl-X, Ctrl-A insert
an atom from the previous line at the cursor position. A line only
makes atoms available if it expresses a valid \*(TX form, free of syntax
errors. A line containing only whitespace or a comment makes no atoms
available. For the purposes of this editing feature, an atom is defined
as the printed representation of a Lisp atom taken from the Lisp form
specified in the previous line. The line is flattened into atoms
as if by the
.code flatcar
function. By default, the last atom is extracted. A numeric argument
typed between the Ctrl-X and Ctrl-A or a can be used to select a
atoms by position from the end. The number 1 specifies the last atom,
2 the second last and so on.
Only the most recent three decimal digits are retained, so the number can range
from 0 to 999. A value of 0, or a value which exceeds the number of words
causes the Ctrl-A or a to do nothing.  Note that "previous line"
has the same meaning as for the Ctrl-X, Ctrl-W (insert previous word) command.

.NP* Insert Previous Line

The command sequences Ctrl-X, Ctrl-R ("repeat") and Ctrl-X, r, which are
equivalent, insert an entire line of history into the current buffer. By
default, the previous line is inserted. A less recent line can be selected by
typing a numeric argument between the Ctrl-X and the Ctrl-R/r. The immediately
previous history line is numbered 1, the one before it 2 and so on.
If this command is used during history navigation, it references previous
lines relative to the currently recalled history line.

.NP* Symbolic Completion

If the Tab key is pressed while editing a line, it is interpreted as a
request for completion. There is a second completion command: the
sequence Ctrl-X Tab.

When completion is invoked with Tab or Ctrl-X Tab, the listener looks at a few
of the trailing characters to the left of the cursor position to determine the
applicable list of completions. Completions are determined from among the \*(TL symbols which have
global variable, function, macro and symbolic macro bindings.  Symbols which
have operator binding are also taken into consideration.  If a
package-qualified symbol is completed, then completion is restricted to that
package. Keyword symbol completion is restricted to the contents of the keyword
package.

The difference between Tab and Ctrl-X Tab is that Tab completion looks only for
prefix matches among the eligible identifiers. Thus it is a pure completion in
the sense that it suggests additional material that may follow what has been
typed. If the buffer contains
.code (list
it will only suggest completions which can be endings for
.code list
such as
.codn list* ,
.codn listp ,
and
.codn list-str .
It will not suggest identifiers which rewrite the
.code list
prefix.  By contrast, the Ctrl-X Tab completion suggests not only pure
completions but also alternatives to the partial identifier, by looking for
substring matches. For instance
.code copy-list
is a possible completion for
.codn list ,
as is
.codn proper-list-p .

If no completions are found, then the BEL character is sent to the terminal
to generate a beep or a visual alert indication. The listener returns to
editing mode.

If completions are found, listener enters into completion selection mode.
The first available completion is placed into the line as if it had been typed
in.  The other completions may be viewed one by one using the Tab key.
(Note that the Ctrl-X is not used, only Tab, even if completion mode had been
entered via Ctrl-X Tab).
When the completions are exhausted, the original uncompleted line is shown
again, and Tab can continue to be used to cycle through the completions again.
In completion mode, the Ctrl-C character acts as a command to cancel completion mode
and return to editing the original uncompleted line. Any other input character causes
the listener to keep the currently shown completion, and return to edit mode,
where that character is immediately processed as if it had been typed in
edit mode.

.NP* Edit with External Editor

The two character command Ctrl-X, Ctrl-E launches an external editor to
edit the current command line. The command line is stored in a temporary
file first, and the editor is invoked on this file. When the editor
terminates, the file is read into the editing buffer.

The editor is determined from the
.code EDITOR
environment variable. If this variable doesn't exist,
the command does nothing.

If the
.code HOME
environment variable exists, then the temporary file is created in the home
directory. Otherwise it is created in the current working directory. If the
creation of the file fails, then the command silently returns to edit mode.

If the command line contains embedded carriage returns (which denote
line breaks in multi-line mode) these are replaced with newline characters
when written out to the file. Conversely, when the edited file is read
back, its newlines are converted to carriage returns, so that multi-line
content is handled properly. (See the following section, Multi-Line Mode).

.NP* Undo Editing

The listener provides an undo feature.  The Ctrl-O command ("old", "oops")
restores the edit buffer contents and cursor position to a previous state.

There is a single undo history which records up the 200 most recent edit
states. However, the states are associated with history lines, so that it
appears that each line has its own, independent undo history.
Undoing the edits in one line has no effect on the undo history of another
line.

Undo also records edits for lines that has been canceled with Ctrl-C, and are
not entered into the history, making it possible to recall canceled lines.

The undo history is lost when \*(TX terminates.

Undo doesn't save and restore previous contents of the clipboard buffer.

There is no redo. When undo removes an edit to restore to a prior edit state,
the removed edit is permanently discarded.

Note that if undo is invoked on a historic line, each undo step updates that
history entry instantly to the restored state. This is in contrast
to the way new edits work. New edits are not committed to history until
navigation takes place to a different history line.

Also note that when new edits are performed on a historic line and it is
submitted with Enter without navigating to another line, the undo information
for those edits is retained, and belongs to the newly submitted line.  The
historic line hasn't actually been modified, and so it has no new undo
information.  However, if a historic line is edited, and then navigation takes
place to a different historic line, then the undo information is committed to
that line, because the modifications to the line have been placed back
in the history entry.

.SS* Visual Selection Mode

The interactive listener supports visual copy and paste operation.
Text may be visually selected for copying into a clipboard (copy)
or deletion. In visual selection mode, the actions of some editing
commands are modified so that they act upon the selection instead
of their usual target, or upon both the target and the selection.

.NP* Making a Selection

The Ctrl-S command enters into visual selection mode and marks the
starting point of the selection, which is considered the position
immediately to the left of the current character.

While in visual selection mode, it is possible to move around using
the usual movement commands. The ending point of the selection
tracks the movement. The ending point of the selection is also
the position immediately to the left of the current character.

The selected text is displayed in reverse video.

Typing Ctrl-S again while in visual selection mode cancels
the mode.

Tab completion, history navigation, history search and editing in an external
editor all cancel visual selection mode.

By default, the the selection excludes the character which lies to the right of
the rightmost end-point.  Thus, the selection simply consists of the text
between these two positions, whether or not they are reversed. This style of
selection pairs excellently with an I-beam style cursor, and has clear
semantics. The end-points are referenced to the positions between the
characters, and everything between them is selected.

The selection behavior may be altered using the Boolean configuration variable
.codn *listener-sel-inclusive-p* .
This variable is
.code nil
by default. If it is changed to true, then the selection includes the
character to the right of the rightmost endpoint, if there is such a
character within the current line.  This style of selection
pair well with a block-shaped cursor. It creates the apparent semantics that
the end-points of the election are characters, rather than points
between characters, and that these characters are included in the selection.

.NP* Selection Endpoint Toggle

In visual selection, the starting point of the selection remains fixed, while
the ending point tracks the movement of the cursor. The Ctrl-^ command will
exchange the two points. The effect is that the cursor jumps to the opposite
end of the selection. That end is now the ending point which tracks the cursor
movement.

.NP* Visual Copy

The Ctrl-Y command ("yank") copies the selected text into a clipboard buffer.
The previous contents of the clipboard buffer, if any, are discarded.

Unlike the history, the clipboard buffer is not persisted.
If \*(TX terminates, it is lost.

.NP* Visual Cut

If the Ctrl-D command is invoked while a selection is in effect, then
instead of deleting the character under the cursor, it deletes the
selection, and copies it to the clipboard.

.NP* Clipboard Paste

The Ctrl-Q command ("quote the clipboard") inserts text from the clipboard
at the current cursor position. The cursor position is updated to
be immediately after the inserted text.  The clipboard text remains available
for further pasting.

If nothing has been yet been copied to the clipboard in the current
session, then this command has no effect.

.NP* Clipboard Swap Paste

The Ctrl-X, Ctrl-Q command sequence ("exchange quote") exchanges the
selected text with the contents of the clipboard. The selection is
copied into the clipboard as if by Ctrl-Y and replaced by the
previous contents of the clipboard.

If the clipboard has not yet been used in the current session,

If nothing has been yet been copied to the clipboard in the current
session, then this command behaves like Ctrl-Y:
text is yanked into the clipboard, but not deleted.

.NP* Visual Replace

In visual selection mode, an editing commands may be used which insert new
text, or a character may be typed in order to insert it. When this happens, the
selection is first deleted and visual mode is canceled. Then the insertion
takes place and visual mode is canceled. The effect is that the newly inserted
text replaces the selected text.

This applies to the Clipboard Paste (Ctrl-Q) command also. If a
selection is effect when Ctrl-Q is invoked, the selected text
is replaced with the clipboard buffer contents.

When a selection is replaced, nothing is copied to the clipboard.

.NP* Delete in Selection Mode

In visual mode, it is possible to issue commands which delete text.
Ctrl-D has special behavior, Visual Cut, described above.

The Backspace key and Ctrl-H also have a special behavior in select mode. If
the cursor is at the rightmost endpoint of the selection, then these commands
delete the selection and nothing else.  If the cursor is at the leftmost
endpoint of the selection, then these commands delete the selection, and take
their usual effect of deleting a character also.  In both cases, selection mode
is canceled.

The Ctrl-W command to delete the previous word, when used in visual
selection mode, deletes the selection and cancels selection mode,
and then deletes the word before the selection.

All other deletion commands such as Ctrl-K simply cancel visual
selection mode and take their usual effect.

Nothing is copied to the clipboard when deletion commands are used while a
selection is in effect.

.SS* Multi-Line Mode

The listener operates in one of two modes: line mode and multi-line mode.
This is determined by the special variable
.code *listener-multi-line-p*
whose default value is
.code nil
(line mode).  It is possible to toggle between
line mode and multi-line mode using the Ctrl-J command.

In line mode, all input given to a single prompt appears to be on a single
line. When the line becomes longer than the screen width, it scrolls
horizontally.   In line mode, carriage return characters embedded in a line
are displayed as
.codn ^M .

In multi-line mode, when the input exceeds the screen width, it simply wraps to
take up additional lines rather than scrolling horizontally. Furthermore,
multi-line mode not only wraps long lines of input onto multiple lines of
the display, but also supports true multi-line input. In multi-line
mode, carriage return characters embedded in input are treated as line
breaks rather than being rendered as
.codn ^M .

To insert a line break character, use the sequence: Ctrl-V, Ctrl-M.
Or, equivalently: Ctrl-V, Enter.

Because carriage returns are not line terminators in text files,
lines which contain embedded carriage returns are correctly saved
into and retrieved from the persistent history file.

.SS* Reading Forms Directly from the Terminal

In addition to multi-line mode, the listener provides support
for directly parsing input from the terminal, suitable for processing
large amounts of pasted material.

If the
.code :read
keyword is entered into the listener, it will temporarily suspend
interactive editing and allow the \*(TL parser to read
directly from standard input. The reading stops when an error occurs,
or EOF is indicated by entering Ctrl-D.

In direct parsing mode, each expression which is read is evaluated, but its
value is not printed. However, the value of the last form evaluated is returned
to the interactive listener, which prints the value and accepts it as if
it as the result value of the
.code :read
command.

Note that none of the material read from the terminal is entered into the
interactive history. Only the
.code :read
command which triggers this parsing mode appears in the history.

.SS* Clear Screen and Refresh

The Ctrl-L command clears the screen and re-draws the line being edited.
This is useful when the display is disturbed by the output of some
background process, or serial line noise.

.SS* Suspend to Background

The Ctrl-Z ("Zzzz... (sleep)") command causes \*(TX to be placed into the
background in a suspended, and control returned to the system shell.
This feature depends on the use of a POSIX job control shell.

Bringing the suspended \*(TX back into the foreground is achieved with a shell
command such as the
.code fg
command in GNU Bash.

When \*(TX is resumed, the interactive listener will re-display the edited
line and restore the previous cursor position.

.SS* Interactive Profile File

When the listener starts up, it looks for file called
.code .txr_profile
in the user's home directory, as determined by the
.code HOME
environment variable. If that variable doesn't exist, no further attempt is
made to locate this file.

If the file exists, it is subject to a security check.
The function
.code path-private-to-me-p
is applied to the file. If it returns
.code nil
then an error message is displayed and the file is not loaded.

If the file passes the security check, it is expected to be readable and
to contain
\*(TL forms, which are read and evaluated.
Syntax errors encountered while reading the profile file are displayed
on standard output, and any exceptions thrown that are derived from
.code error
are caught and displayed.  The interactive listener starts in spite of these
situations.  Exceptions not derived from
.code error
will terminate the process.

The profile file is not read by non-interactive invocations of \*(TX:
that is, when the
.code -i
option isn't present.

.SS* History Persistence

The history is maintained in a text file called
.code .txr_history
in the user's home directory. Whenever the interactive listener terminates,
this file is overwritten with the history contents stored in the listener's
memory.  The next time the listener starts, it first re-loads the history from
this file, making the commands of a previous session available for recall.

The home directory is determined from the
contents of the
.code HOME
environment variable. If this variable doesn't exist, or the user doesn't
have permissions to write to this directory or to an existing history file
in that directory, then the history isn't saved.

.SS* Parenthesis Matching

A feature of the listener is visual parenthesis matching in the form of a
brief backward jump of the cursor.  This provides a hint to the programmer,
helping to prevent avoid parenthesis balancing errors.

When any of the three closing characters
.codn ) ,
.code ]
or
.code }
is inserted, the listener scans backward for the matching opening
character. Likewise, if any of the three opening characters
.codn ( ,
.code [
or
.code {
is inserted in the middle of text, the listener scans forward for the matching
closing character.

If the matching character is found, the cursor jumps to that
character and then returns to the original position a brief moment later. If a
new character is typed during the brief time delay, the delay is immediately
canceled, so as not to hinder rapid typing.

This back-and-forth jump behavior also occurs when a character is erased using
Backspace, and the the cursor ends up immediately to the right of a
parenthesis.

Note that the matching is unsophisticated; it doesn't observe the
lexical conventions and syntax of the \*(TL programming language.  For
instance, a closing parenthesis outside a string literal may match
match an opening one inside a string literal.

.SS* Listener Configuration Variables

The listener's behavior can be influenced through values of certain
global variables. The settings can be made persistent by means
of setting these variables in the interactive profile file.

.coNP Special variable @ *listener-hist-len*
.desc
This special variable determines how many lines of history are
retained by the listener. Changing this variable from within the listener
has an instant effect. If the number is reduced from its current value,
history lines are immediately discarded. The default value is 500.
.code

.coNP Special variable @ *listener-multi-line-p*
.desc
This is a Boolean variable which indicates whether the listener is
in multi-line mode. The default value is
.codn nil .

Changing this variable from within the listener takes effect
immediately for the next line of input.

If multi-line mode is toggled interactively from within the listener,
the variable is updated to reflect the latest state. This happens
when the command is submitted for evaluation.

.coNP Special variable @ *listener-sel-inclusive-p*
.desc
This Boolean variable controls the behavior of visual selection.
It is
.code nil
by default.

A visual selection is determined by end-points, which are abstract positions
understood as being between characters. When a visual selection begins,
it marks an end-point immediately to the left of a block-shaped cursor,
or precisely at the in-between position of an I-beam cursor.
The end of the visual selection is similarly determined from the ending
cursor position. The selection consists of those characters which lie
between these positions. This style of selection pairs well with an I-beam
style cursor shape.

If the
.code *listener-sel-inclusive-p*
variable is set true, then the selection also includes one more
character to the right of the rightmost endpoint, if there is
such a character within the current line, giving rise to the appearance
that the selection is determined by the starting and ending character,
and includes them. This type of selection pairs well with a block-shaped
cursor.

.SH* SETUID/SETGID OPERATION

On platforms with the Unix filesystem and process security model, \*(TX has
support for executing setuid/setgid scripts, even on platforms whose operating system
kernel does not honor the setuid/setgid bit on hash bang scripts. On these
systems, taking advantage of the feature requires \*(TX to be installed as a
setuid/setgid executable. For this reason, \*(TX is aware when it is executed
setuid and takes care to manage privileges.  The following description about
the handling of setuid applies to the parallel handling of setgid also.

When \*(TX starts, early in its execution it determines whether or not is
is executing setuid. If so, it temporarily drops privileges, as a precaution.
This is done before processing the command line arguments.
When \*(TX determines that it is executing a setuid script (a file marked
executable to its owner and attributed with the set-user-ID bit), it then
attempts to impersonate the owner of the script file by changing to
effective user ID to that owner just before executing the file. It retains
the real and saved user ID.  If the attempt to assume that user ID is
unsuccessful, then \*(TX permanently drops setuid privileges before executing
the script.  Likewise, before executing anything code other than a setuid
script, \*(TX also drops privileges.

\*(TX tries to honor and implement the setuid permissions on a script
whether or not it is running setuid. When not running setuid, it nevertheless
tries to change its effective user ID to that of the owner of the setuid
script. This will succeed if it has sufficient permissions to do so.

To rephrase: in order for \*(TX to execute a file which is setuid root,
it has to be running with a root effective user ID somehow. In order
to execute a file which is setuid to a non-root user, \*(TX has to be
running effectively as root or else as that user.   It doesn't matter whether
these privileges are achieved effectively using the setuid mechanism, or
whether \*(TX is running with the require user ID as its real ID.
However, if \*(TX is running setuid, it takes special care to temporarily
drop the privileges as early as possible, and eventually to drop the
privileges permanently before executing any code, other that the setuid
script. If the setuid script cannot be executed with the privileges it
calls for, \*(TX also drops privileges and executes it anyway, strictly as the
real user who invoked the \*(TX executable.

What it means to drop privileges is to change the effective user ID
and the saved user ID to be equal to the real user ID. On platforms
where the
.code setresuid
function is available, \*(TX uses that function to drop privileges.
On platforms where
.code setresuid
is not available, \*(TX tries to drop privileges using the
C language function call
.codn "setuid(r)" ,
where
.code r
is the previously noted real user ID obtained from
.codn getuid() .
On some platforms, this only works for dropping root privileges: it
overwrites the real and saved ID only if the caller is effectively root.
On those platforms, this approach does not drop non-root privileges.
\*(TX tries to detect whether this approach worked by evaluating
the C language expression
.codn "seteuid(e)" ,
where
.code e
is the previously noted effective user ID.  In other words, it
attempts to re-gain the dropped privilege by recovering the previous
effective ID. If this attempt succeeds, \*(TX immediately aborts.
Dropping setgid privileges is similar. Where
.code setresgid
is available it is used, otherwise an attempt is made with
.code "setegid(r)"
where
.code r
is the previously noted real group ID. Then a test using
.code "setegid(e)"
is performed using the original effective group ID as
.codn e .
This is done after dropping any setuid root user ID privilege
which would allow such a test to succeed.

If \*(TX is running both setuid and setgid, and execute a script
which is setuid only, it will still drop group privileges, and vice
versa: if it executed a setgid script, it will drop user privileges.
For instance, if a root-owned \*(TX runs a setgid script which is owned by
user
.code 10
and group-owned by group
.codn 20 ,
that script will run with an effective group ID of 20. The effective user ID
will be that of the user who invoked the script: \*(TX will drop the root
privilege to the original real ID of the user, and while for the setgid
operation, it will change to the group ID of the script.

The setuid/setgid privilege machinery in \*(TX does not manipulate
the list of supplementary ("ancillary", in the language of POSIX) group IDs.
It is unnecessary for security because the list does not change while
running with setuid privilege. No group IDs are added to the list which
need to be retracted when privileges are dropped. The supplementary
groups also persist across the execution of a setuid/setgid script.

.SH* STAND-ALONE APPLICATION SUPPORT

The \*(TX executable image supports a general mechanism by means of which
a custom program can be packaged as an apparent stand-alone executable.

.SS* The Internal Argument String

The \*(TX executable contains a 128 byte data area preceded by the
seven-byte ASCII character sequence
.strn @(txr): .
The 128 byte data area which follows this identifying prefix
represents a null-terminated UTF-8 string. In the stock executable,
this area is filled with null bytes.

If the \*(TX executable is edited such that this area is replaced
with a non-empty, null-terminated UTF-8 string, the program will,
for the purposes of command line argument processing, treat this string as if
it were the one and only command line argument. (The original command
line arguments are still retained in the
.code *args*
and
.code *args-full*
variables).

.TP* Example:

Suppose that \*(TX is copied to an executable in the same directory called
.code myapp
(or
.code myapp.exe
on an operating system which requires the
.code .exe
suffix). Also suppose that in the same directory, there exists a file
called
.codn myscript.tl .

This
.code myapp
executable can then be edited so that the data area which follows the
.code @(txr):
bytes contains the following string:

.cblk
  --args|-e|(load `@{txr-path}/main.tl`)
.cble

When the
.code myapp
executable is invoked, it will process the above string as a single
command line argument, causing the
.code main.tl
\*(TL source file to be loaded.
Any arguments passed to
.code myapp
are ignored and available to
.code main.tl
via the
.code *args*
variable.

.SS* Deployment Directory Structure

The \*(TX executable may require library files, depending on the
functionality invoked by the program code. Library files are located
relative to the installation directory, called the
.IR sysroot .
The executable tries to dynamically determine the sysroot from
its own location, according to this directory structure:

.cblk
  /path/to/sysroot/bin/txr
               .../share/txr/stdlib/cadr.tl
                         .../stdlib/except.tl
                                    ...
.cble

The above structure is assumed if the executable finds itself
in a directory named
.strn bin .

Otherwise, if the executable finds itself in a directory not
named
.strn bin ,
the following structure is expected:

.cblk
  /path/to/installation/txr
                    .../share/txr/stdlib/cadr.tl
                    .../share/txr/stdlib/except.tl
                                         ...
.cble

When a custom application is deployed using a possibly renamed
.code txr
executable, one of the above structures should be observed:
either the sysroot with a
.code bin
subdirectory where the executable is located, on the
same level with the
.code share
directory, or else the second structure in which the
.code share
directory is a subdirectory of the executable directory.
If one of these structures is not observed, the application
may fail due to the failure of a library file to load.

.coSS Utility program @ txr-embedded-arg.txr
.synb
.mets txr txr-embedded-arg.txr [ -w < new-string ] < executable
.syne
.desc
At the root of the \*(TX source code tree, a program called
.code txr-embedded-arg.txr
is provided. This program can display or modify the
embedded argument string inside a \*(TX executable.

The
.meta executable
argument must always be present. It should refer to a \*(TX
executable.

If the
.code -w
option and its
.meta new-string
argument are omitted, then
.meta executable
is examined, and the contents of embedded argument data
area
.code @(txr):
are displayed on standard output (including all
the padding/terminating null bytes), followed by a newline.

If
.code -w
option and its argument
are present, then
.code new-string
is truncated to 127 bytes, if necessary, and written into
the embedded argument data area of
.codn executable ,
padded with sufficient null bytes to write a complete unit of 128 bytes.
Nothing is displayed on standard output.

Note that
.code new-string
is treated as a UTF-8 representation. The 127 character limit is on the
number of UTF-8 bytes, not Unicode characters.

.TP* Example:

The following is a POSIX shell command, which writes a
.code --args
argument into the embedded data area of the
"myapp" executable. This argument encodes two
arguments:
.code -e
specifying an expression which will cause the executable
to load a
.str main.tl
file that is co-located in the same directory as
that executable.

.cblk
  txr txr-embedded-arg.txr \e
    -w '--args=-e=(load `@{txr-path}/main.tl`)' myapp
.cble

.SH* DEBUGGER
\*(TX has a simple, crude, built-in debugger. The debugger is invoked by adding
the
.code -d
command line option to an invocation of \*(TX.
In this debugger it is possible to step through code, set breakpoints,
and examine the variable binding environment.

Prior to executing any code, the debugger waits at the
.code txr>
prompt, allowing for the opportunity to set breakpoints.

Help can be obtained with the
.code h
or
.code ?
command.

Whenever the program stops at the debugger, it prints the Lisp-ified
piece of syntax tree that is about to be interpreted.
It also shows the context of the input being matched.

The s command can be used to step into a form; n to step over.
Sometimes the behavior seems counter-intuitive. For instance stepping
over a
.code @(next)
directive actually means skipping everything which follows
it. This is because the query material after a
.code @(next)
is actually child
nodes in the abstract syntax tree node of the
.code next
directive, whereas the surface syntax appears flat.

The following is an example of the debugger being applied to a web scraping program
which connects to a US NAVY clock server to retrieve a dynamically-generated
web page, from which the current time is extracted, in various time zones.
The handling of the web request is done by the wget command; the
\*(TX query opens a wget command as and scans the body of the HTTP response
containing
HTML. This is the code, saved in a file called navytime.txr:

.cblk
  @(next `!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null`)
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>
  <html>
  <body>
  <TITLE>What time is it?</TITLE>
  <H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
  @(collect :vars (MO DD HH MM SS (PM "  ") TZ TZNAME))
  <BR>@MO. @DD, @HH:@MM:@SS @(maybe)@{PM /PM/} @(end)@TZ@/\et+/@TZNAME
  @  (until)
  </PRE>@/.*/
  @(end)
  </PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A>

  </body></html>
  @(output)
  @  (repeat)
  @MO-@DD @HH:@MM:@SS @PM @TZ
  @  (end)
  @(end)
.cble

This is the debug session:

.cblk
  $ txr -d navytime.txr
  stopped at line 1 of navytime.txr
  form: (next (sys:quasi "!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null"))
  depth: 1
  data (nil):
  nil
.cble

The user types
.code s
to step into the
.code "(next ...)"
form.

.cblk
  txr> s
  stopped at line 2 of navytime.txr
  form: (sys:text "<!DOCTYPE" (#<sys:regex: 95e4590> 1+ #\espace) "HTML" (#<sys:regex: 95e4618> 1+ #\espace) "PUBLIC" (#<sys:regex: 95e46a8> 1+ #\espace) "\e"-//W3C//DTD" (#<sys:regex: 95e4750> 1+ #\espace) "HTML" (#<sys:regex: 95e47d8> 1+ #\espace) "3.2" (#<sys:regex: 95e4860> 1+ #\espace) "Final\e"//EN>")
  depth: 2
  data (1):
  "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr> s
.cble

The current form now is a
.code sys:text
form which is an internal representation of
a block of horizontal material. The pattern matching is in vertical mode at
this point, and so the line of data is printed without an indication of
character position.

.cblk
  stopped at line 2 of navytime.txr
  form: (sys:text "<!DOCTYPE" (#<sys:regex: 95e4590> 1+ #\espace) "HTML" (#<sys:regex: 95e4618> 1+ #\espace) "PUBLIC" (#<sys:regex: 95e46a8> 1+ #\espace) "\e"-//W3C//DTD" (#<sys:regex: 95e4750> 1+ #\espace) "HTML" (#<sys:regex: 95e47d8> 1+ #\espace) "3.2" (#<sys:regex: 95e4860> 1+ #\espace) "Final\e"//EN>")
  depth: 3
  data (1:0):
  "" . "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
.cble

The user types
.code s
to step in.

.cblk
  txr> s
  stopped at line 2 of navytime.txr
  form: "<!DOCTYPE"
  depth: 4
  data (1:0):
  "" . "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
.cble

Now, the form about to be processed is the first item of the
.codn "(sys:text ...)" ,
the string
.strn <!DOCTYPE .

The input is shown broken into two quoted strings with a dot in between.
The dot indicates the current position. The left string is empty, meaning
that this is the leftmost position. The programmer steps:

.cblk
  txr> s
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4590> 1+ #\espace)
  depth: 4
  data (1:9):
  "<!DOCTYPE" . " HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
.cble

Control has now passed to the second element of the
.codn "(sys:text ...)" ,
a regular expression which matches one or more spaces, generated by
a single space in the source code according to the language rules.

The input context shows that
.str <!DOCTYPE
was matched in the input, and the position moved past it.

.cblk
  txr> s
  stopped at line 2 of navytime.txr
  form: "HTML"
  depth: 4
  data (1:10):
  "<!DOCTYPE " . "HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
.cble

Now, the regular expression has matched and moved the position past
the space; the facing input is now
.strn "HTML ..." .

The programmer then repeats the
.code s
command by hitting Enter.

.cblk
  txr>
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4618> 1+ #\espace)
  depth: 4
  data (1:14):
  "<!DOCTYPE HTML" . " PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: "PUBLIC"
  depth: 4
  data (1:15):
  "<!DOCTYPE HTML " . "PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e46a8> 1+ #\espace)
  depth: 4
  data (1:21):
  "<!DOCTYPE HTML PUBLIC" . " \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: "\e"-//W3C//DTD"
  depth: 4
  data (1:22):
  "<!DOCTYPE HTML PUBLIC " . "\e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4750> 1+ #\espace)
  depth: 4
  data (1:34):
  "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD" . " HTML 3.2 Final\e"//EN>"
.cble

It is not evident from the session transcript, but during interactive use,
the input context appears to be animated. Whenever the programmer hits
Enter, the new context is printed and the dot appears to advance.

Eventually the programmer becomes bored and place a breakpoint on line 15,
where the
.code @(output)
block begins, and invokes the
.code c
command to continue the execution:

.cblk
  txr> b 15
  txr> c
  stopped at line 15 of navytime.txr
  form: (output (((repeat nil (((sys:var MO nil nil) "-" (sys:var DD nil nil) " " (sys:var HH nil nil) ":" (sys:var MM nil nil) ":" (sys:var SS nil nil) " " (sys:var PM nil nil) " " (sys:var TZ nil nil))) nil nil nil nil nil nil))))
  depth: 2
  data (16):
  ""
.cble

The programmer issues a
.code v
command to take a look at the variable bindings,
which indicate that the
.code @(collect)
has produced some lists:

.cblk
  txr> v
  bindings:
  0: ((PM "  " "PM" "PM" "PM" "PM" "PM" "PM") (TZNAME "Universal Time" "Eastern Time" "Central Time" "Mountain Time" "Pacific Time" "Alaska Time" "Hawaii-Aleutian Time") (TZ "UTC" "EDT" "CDT" "MDT" "PDT" "AKDT" "HAST") (SS "35" "35" "35" "35" "35" "35" "35") (MM "32" "32" "32" "32" "32" "32" "32") (HH "23" "07" "06" "05" "04" "03" "01") (DD "30" "30" "30" "30" "30" "30" "30") (MO "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar"))
.cble

Then a continue command, which finishes the program, whose output appears:

.cblk
  txr> c
  Mar-30 23:22:52    UTC
  Mar-30 07:22:52 PM EDT
  Mar-30 06:22:52 PM CDT
  Mar-30 05:22:52 PM MDT
  Mar-30 04:22:52 PM PDT
  Mar-30 03:22:52 PM AKDT
  Mar-30 01:22:52 PM HAST
.cble

.SH* COMPATIBILITY

.SS* Overview

New \*(TX versions are usually intended to be backward-compatible with prior
releases in the sense that documented features will continue to work in
the same way. Due to new features, new versions of \*(TX will supply new
behaviors where old versions of \*(TX would have produced an error, such as a
syntax error. Though, strictly speaking, this means that something is working
differently in a new version, replacing an error situation with functionality
is usually not considered a deviation from backward-compatibility.

.coNP The @ -C compatibility option

When a change is introduced which is not backward compatible, \*(TX's 
.code -C
option can be used to request emulation of old behavior.

The option was introduced in \*(TX 98, and so the oldest \*(TX version which
can be emulated is \*(TX 97.

Side effects occur in the processing of the option.  If the option is specified
multiple times, the behavior is unspecified.

.coNP Environment variable @ TXR_COMPAT

If the
.code TXR_COMPAT
environment variable exists, and its value is not en empty string,
it must contain a decimal integer. Its value is taken by \*(TX  as a request
to emulate old behaviors, just like the value of the
.code -C
option.

If the variable has incorrect contents or an out-of-range value,
\*(TX will print an error diagnostic and exit.

If both
.code -C
and the
.code TXR_COMPAT
environment variable are supplied, the behavior is unspecified.

.coNP Compatibility Version Values

The following version values which have a special meaning as arguments to the
.code -C
option, along with a description of what behaviors are affected. For each
of these version values, the described behaviors are provided if
.code -C
is given an argument which is equal or lower. For instance
.code "-C 103"
selects the behaviors described below for version 105, but not those for 102.
.IP 139
After \*(TX 139, changes were implemented in the area of pseudo-random
number generation. Compatibility with 139 brings back the previous
seeding algorithm used by
.codn make-random-state ,
allowing the old pseudo-random sequences to be reproduced. This is only
the case if the default value of 8 is used for the
.meta warmup-period
argument of that function (which didn't exist in 139 or earlier versions).
.IP 138
After \*(TX 138, the variable name lookup rules in the \*(TX pattern language
changed for greater utility and consistency. Compatibility with 138 or later
restores the previous rules under which most accesses to a \*(TL variable from
\*(TL require the
.code @
prefix denoting Lisp evaluation, but some do not.
.IP 137
Compatibility with \*(TX 137 restores the behavior of not expanding
symbol macros in the dot position of a function call form. For instance
if
.code x
is a symbol macro, in this compatibility mode it is not recognized
in a form like
.codn "(list 1 2 . x)" .
This preserves the behavior of code which depends on
.code x
in such a form to refer to a variable that is being otherwise shadowed by the
symbol macro. \*(TX 137 compatibility also restores a particular behavior
of the global and local macro defining operators
.code defsymacro
and
.codn symacrolet :
in compatibility mode, these operators macro-expand the replacement forms
of symbol macros at expansion time, and then bind the resulting expanded
forms to their respective macro symbols. The forms are then potentially
expanded again when the symbol macros are substituted. This wrong behavior was
never implied by the documentation. The
.code with-slots
macro is also affected by this, because it is implemented in terms of
.codn symacrolet .
Lastly, \*(TX 137 compatibility mode also restores another behavior
of the dot position in function call forms: if the dot position of a
function call form produces a sequence that is not a list, that sequence
is converted to a list so that
.cblk
(list . "abc")
.cble
produces
.codn "(#\ea #\eb #\ec)" .
After 137, no such treatment is applied to the value and the same form now
yields
.strn abc .
.IP 136
A request for compatibility with \*(TX 136 or earlier restores the old behavior
of the
.code if
directive, which in used to be a syntactic sugar for a
.code cases
directive with
.code require
at the top of each block. Though semantically well-defined and working as
documented, the behavior was confusing, since failed matching caused potential
evaluation of multiple clauses, whereas programmers expect an if/elif/else
ladder to select exactly one clause.
.IP 128
Compatibility with \*(TX 128 or earlier brings back the behavior that
expressions in quasiliterals are evaluated according to \*(TX evaluation
rules for quasiliterals which occur in the \*(TX pattern language.
Similarly, expressions in
.code @(output)
blocks are treated \*(TX pattern language expressions.
.IP 127
In versions of \*(TX until 127, the functions
.codn symbol-function ,
.code fboundp
and
.code fmakunbound
behaved similarly to their Common Lisp counterparts. See the Dialect Notes
under these functions.
.IP 124
In \*(TX 124 and earlier versions, the
.code @(next)
directive didn't evaluate the
.meta source
argument as a Lisp expression, but as a \*(TX Pattern Language
expression. Lisp expressions thus had to be delimited by
.codn @ .
The current behavior is that the argument is treated as Lisp.
If the compatibility option is set to 124 or lower, the old behavior
is restored. However, even without the presence of the compatibility option,
if the
.meta source
argument is a meta-expression or meta-variable (denotes by the
.code @
prefix in front of a compound expression or symbol, respectively)
it is also treated in the old way. This latter behavior is obsolescent
and will eventually disappear, and the compatibility option will be
the only way to get the old behavior.

.IP 123
In \*(TX 123 and earlier, the variable initialization forms of a
.code for
or
.code for*
loop were evaluated outside of the scope of the implicit
.code nil
block. They are now inside the block. The compatibility option will
restore the old behavior.
.IP 121
In \*(TX 121 and earlier versions, \*(TL expressions evaluated in the
pattern language were placed in a lexical environment in which the
pattern variables were visible as lexical variables. The meant that
these variables could be directly captured in lexical closures. On the other
hand, it meant that a Lisp function defined in a
.code @(do)
block could not access a variable established by a later
.codn @(bind) .
It doesn't make sense for dynamically captured variables to be lexical,
so the rule was changed. The backward compatibility switch will enable
the old scoping behavior. Capturing the values of pattern variables in
closures is possible indirectly under the new rule: simply bind new lexical
variables with their values.
.IP 118
The
.code slot-p
function's name changed to
.code slotp
after 118. The compatibility option causes
.code slot-p
to be defined also.

.IP 117
The arguments of the
.code make-struct-type
acquired changed after version 117. 117 compatibility brings back the old
interface.

.IP 114
\*(TX until version 114 reported parse errors in this format:

.cblk
  ./txr: (file.txr:123): syntax error
.cble

The new format omits the program name prefix and parentheses.

Also, the
.code kill
function returned an integer, obtained from the return
value of the underlying C function, rather than converting
that value to a Boolean. The old behavior was not documented,
and 114 compatibility restores it.

Lastly, prior to 115, random state objects were of type
.code *random-state*
(the same symbol as the special variable name)
rather than of type
.codn random-state .
This is a bug whose behavior is simulated by 114 compatibility.

.IP 113
Version 113 is the last version in which the
.codn stat ,
.codn lstat ,
and
.code fstat
functions returned a property list rather than a structure.
Requesting 113 compatibility restores the behavior of returning
a property list. However, the filesystem testing functions like
.code path-exists-p
will not work, because they rely on these functions returning
a structure.

.IP 109
The optional trailing semicolon on hex and octal codes in the \*(TX
pattern language was introduced in 110. The feature is disabled
with 109 or lower compatibility, so that
.code @\ex21;a
encodes
.code !;a
rather than the current behavior of encoding
.codn !a .
Also, in 109 and earlier, newlines were allowed in word list literals and
word list quasiliterals. They were treated as a word-separating space.
A backslash-escaped newline, and all whitespace around it, was deleted
just like in ordinary literals, and did not separate words. The old
behavior is emulated.

.IP 107
Up through \*(TX 107, by accident, there was a function called
.code flip
as well as an operator by the same name. The function was renamed to
.codn flipargs .
Version 107 compatibility or earlier provides the
function under the original name also. Also, up until this version,
\*(TX allowed functions and macros to be defined with the same names
as built-in operators, and macros. Newer versions reject this as an error.
Requesting compatibility to 107 or earlier suppresses the rejection,
though without introducing any requirement that redefinition will work as
expected.

.IP 105
Provides the behavior that the
.code open-file
function automatically marks a stream open on a TTY devices as a real-time stream
(subject to the availability of the POSIX
.code isatty
function).

Also allows unrecognized backslash escape sequences in regular
expression syntax to simply denote the escaped character literally,
as was historically the case prior to \*(TX 106, so that
.code \ez
for instance denotes
.codn z .
As of \*(TX 106, these are diagnosed as errors.

.IP 102
Up to \*(TX 102, the
.code get-string
function did not close the stream. This old behavior is emulated.

.IP 101
Up to \*(TX 101, the
.code make-like
function incorrectly returned
.code nil
when converting the empty list
.code nil
to string type. This affects numerous generic sequence functions,
causing their result to be
.code nil
instead of an empty string.

.IP 100
Up to \*(TX 100, the
.code split-str
function had an undocumented behavior. When the
.code sep
argument was an empty string, it split the string into
individual characters as if by calling
.codn list-str .
This behavior changed to the currently
documented behavior starting in \*(TX 101.
Also, the arguments of the
.code where
function, which introduced in \*(TX 91, were reversed starting
in \*(TX 101.

.IP 99
Up to \*(TX 99, the substitution of TXR Lisp expressions in
.code @(output)
directives and in the quasistrings of the pattern language
exhibited the buggy behavior that if the TXR Lisp expression
produced a list, the list was rendered as a parenthesized
representation, or the text
.code nil
in the empty list case. Moreover, in the
.code @(output)
case, the value of TXR Lisp expressions was not subject to filtering. 
Starting with \*(TX 100, these issues
are fixed, making the the behavior is consistent with
the behavior of TXR Lisp quasiliterals.
.IP 97
Up to \*(TX 97, the error exception symbols such as
.code file-error
were named with underscores, as in
.codn file_error .
These error symbols existed:
.codn type_error ,
.codn internal_error ,
.codn numeric_error ,
.codn range_error ,
.codn query_error ,
.code file_error
and
.codn process_error .

.coNP Variables @ txr-version and @ lib-version
.desc
The
.code txr-version
variable gives the version of the \*(TX executable. Programs can express
conditional variable based on detecting the version.

The
.code lib-version
variable gives the version of the installed library of \*(TX code accompanying
the executable.

It is expected that these two variables have an identical value. Any
discrepancy in their value indicates an installation whose library or \*(TX
executable were upgraded independently. Should such a situation arise in any
system and cause a problem, \*(TX programs can be defensively coded against it
with the help of these variables.

Some features of the \*(TX library are built into the executable, whereas
others are in the library directory. This aspect of library symbols isn't
specified in this manual; knowing which of these two variables is relevant
to a library feature requires familiarity with the implementation.

.SH* APPENDIX
.SS* A. NOTES ON EXOTIC REGULAR EXPRESSIONS
Users familiar with regular expressions may not be familiar with the complement
and intersection operators, which are often absent from text processing tools
that support regular expressions.  The following remarks are offered in hope
that they are of some use.

.TP* "Equivalence to Sets"
Regexp intersection is not essential; it may be obtained from complement and
union as follows, since De Morgan's law applies to regular expression algebra:
.code (R1)&(R2)
=
.codn ~(~(R1)|~(R2)) .
(The complement of the union of the complements of
R1 and R2 constitutes the intersection.) This law works because the regular
expression operators denote set operations in a straightforward way. A regular
expression denotes a set of strings (a potentially infinite one) in a condensed
way. The union of two regular expressions
.code R1|R2
denotes the union of the set
of texts denoted by
.code R1
and that denoted by
.codn R2 .
Similarly
.code R1&R2
denotes a set intersection, and
.code ~R
denotes a set complement. Thus algebraic laws
that apply to set operations apply to regular expressions. It's useful to keep
in mind this relationship between regular expressions and sets in understanding
intersection and complement.

Given a finite set of strings, like the set
.cblk
{ "abc", "def" }
.cble
which corresponds to the regular expression
.codn (abc|def) ,
the complement is the set which contains
an infinite number of strings: it consists of all possible strings except
.str abc
and
.strn def .
It includes the empty string, all strings of length 1, all strings
of length 2, all strings of length 3 other than
.str abc
and
.strn def ,
all strings of
length 4, etc.  This means that a "harmless looking" expression like
.code ~(abc|def)
can actually match arbitrarily long inputs.

.TP* "Set Difference"
How about matching only three-character-long strings other than
.str abc
or
.strn def ?
To express this, regex intersection can be used: these strings are the
intersection of the set of all three-character strings, and the set of all
strings which are not
.str abc
or
.strn def .
The straightforward set-based reasoning
leads us to this:
.codn ...&~(abc|def) .
This
.code A&~B
idiom is also called set
difference, sometimes notated with a minus sign:
.code A-B
(which is not supported in \*(TX regular expression syntax).  Elements which
are in the set
.codn A ,
but not
.codn B ,
are those elements which are in the intersection of
.code A
with the complement of
.codn B .
This is similar to the arithmetic rule
.codn "A - B = A + -B" :
subtraction is
equivalent to addition of the additive inverse. Set difference is a useful
tool: it enables us to write a positive match which captures a more general set
than what is intended (but one whose regular expression is far simpler
than a positive match for the exact set we want), then we can
intersect this over-generalized set with the complemented set of
another regular expression which matches the particulars that we wish excluded.

.TP* "Expressiveness versus Power"

It turns out that regular expressions which do not make use of the
complement or intersection operators are just as powerful as expressions
that do. That is to say, with or without these operators, regular expressions
can match the same sets of strings (all regular languages).  This means that
for a given regular expression which uses intersection and complement, it is
possible to find a regular expression which doesn't use these operators, yet
matches the same set of strings.  But, though they exist, such equivalent
regular expressions are often much more complicated, which makes them difficult
to design.  Such expressions do not necessarily
. B express
what it is they match; they merely capture the equivalent set. They
perform a job, without making it obvious what it is they do.  The use of
complement and intersection leads to natural ways of expressing many kinds of
matching sets, which not only demonstrate the power to carry out an operation,
but also easily express the concept.

.TP* "Example: Matching C Language Comments"

For instance, using complement, we can write a straightforward regular
expression which matches C language comments. A C language
comment is the digraph
.codn /* ,
followed by any string which does not contain the
closing sequence
.codn */ ,
followed by that closing sequence.
Examples of valid comments are
.codn /**/ ,
.code "/* abc */"
or
.codn /***/ .
But C
comments do not nest (cannot contain comments), so that 
.code "/* /* nested */ */"
actually consists of the comment
.codn "/* /* nested */" ,
which is followed by the trailing junk
.codn */ .
Our simple characterization of interior part of a C comment as a string
which does not contain the terminating digraph makes use of the
complement, and can be expressed using the complemented regular expression like
this:
.codn (~.*[*][/].*) .
That is to say, strings which contain
.code */
are matched by
the expression
.codn .*[*][/].* :
zero or more arbitrary characters, followed by
.codn */ ,
followed by zero or more arbitrary characters. Therefore, the complement of
this expression matches all other strings: those which do not contain
.codn */ .
These strings make up the inside of a C comment between the
.code /*
and
.codn */ .

The equivalent simple regex is quite a bit more complicated.
Without complement, we must somehow write a positive match for all strings such
that we avoid matching
.codn */ .
Obviously, sequences of characters other than
.code *
are included:
.codn [^*]* .
Occurrences of
.code *
are also allowed, but only if followed
by something other than a slash, so let's include this via union:

.cblk
  ([^*]|[*][^/])*.
.cble

Alas, already, we have a bug in this expression. The
subexpression
.code [*][^/]
can match
.codn ** ,
since a
.code *
is not a
.codn / .
If the next character in the input is
.codn / ,
we missed a comment close.  To fix the problem we
revise to this:

.cblk
  ([^*]|[*][^*/])*
.cble

(The interior of a C language comment is a any
mixture of zero or more non-asterisks, or digraphs consisting of an asterisk
followed by something other than a slash or another asterisk).  Oops, now we
have a problem again. What if two asterisks occur in a comment?  They are not
matched by
.codn [^*] ,
and they are not matched by
.codn [*][^*/] .
Actually, our regex must not simply match asterisk-non-asterisk digraphs, but
rather sequences of one or more asterisks followed by a non-asterisk: 

.cblk
  ([^*]|[*]*[^*/])*
.cble

This is still not right, because, for instance, it fails to match the interior
of a comment which is terminated by asterisks, including the simple test cases
where the comment interior is nothing but asterisks.  We have no provision in
our expression for this case; the expression requires all runs of asterisks to
be followed by something which is not a slash or asterisk. The way to fix this
is to add on a subexpression which optionally matches a run of zero or more
interior asterisks before the comment close:

.cblk
  ([^*]|[*]*[^*/])*[*]*
.cble

Thus our the semi-final regular expression is

.cblk
  [/][*]([^*]|[*]*[^*/])*[*]*[*][/]
.cble

(Interpretation: a C comment is an interior string enclosed in
.codn "/* */" ,
where this interior part
consists of a mixture of non-asterisk characters, as well as runs of asterisk
characters which are terminated by a character other than a slash, except for
possibly one rightmost run of asterisks which extends to the end of the
interior, touching the comment close. Phew!) One final simplification is
possible: the tail part
.code [*]*[*][/]
can be reduced to
.code [*]+[/]
such that the
final run of asterisks is regarded as part of an extended comment terminator
which consists of one or more asterisks followed by a slash.   The regular
expression works, but it's cryptic; to someone who has not developed it, it
isn't obvious what it is intended to match.  Working out complemented matching
without complement support from the language is not impossible, but it may be
difficult and error-prone, possibly requiring multiple iterations of
trial-and-error development involving numerous test cases, resulting in an
expression that doesn't have a straightforward relationship to the original
idea.

.TP* "The Non-Greedy Operator"

The non-greedy operator
.code %
is actually defined in terms of a set difference,
which is in turn based on intersection and complement. The uninteresting case
.code (R%)
where the right operand is empty reduces to 
.codn (R*) :
if there is no trailing
context, the non-greedy operator matches
.code R
as far as possible, possibly to the
end of the input, exactly like the greedy operator.  The interesting case
.code (R%T)
is defined as a "syntactic sugar" which expands to the expression
.code ((R*)&(~.*(T&.+).*))T
which means: match the longest string which is matched
by
.codn R* ,
but which does not contain a non-empty match for
.codn T ;
then, match
.codn T .
This is a useful and expressive notation. With it, we can write the regular
expression for matching C language comments simply like this:
.code [/][*].%[*][/]
(match the opening sequence
.codn /* ,
then match a sequence of zero or more
characters non-greedily, and then the closing sequence
.codn */ .
With the non-greedy
operator, we don't have to think about the interior of the comment as set of
strings which excludes
.codn */ .
Though the non-greedy operator appears expressive,
its apparent simplicity may be deceptive.  It looks as if it works "magically"
by itself; "somehow" this
.code .%
part "knows" only to consume enough characters so that
it doesn't swallow an occurrence of the trailing context. Care must be taken
that the trailing context passed to the operator really is the correct text
that should be excluded by the non-greedy match. For instance, take the
expression
.codn .%abc .
If you intend the trailing context to be merely
.codn a ,
you must be careful to write
.codn (.%a)bc .
Otherwise, the trailing context is
.codn abc ,
and this means that the
.code .%
match will consume the longest string that does not contain
.codn abc ,
when in fact what was intended was to consume the longest string that
does not contain
.codn a .
The change in behavior of the
.code %
operator upon modifying the
trailing context is not as intuitive as that of the * operator, because the
trailing context is deeply involved in its logic.

On a related note, for single-character trailing contexts, it may be a good
idea to use a complemented character class instead. That is to say, rather than
.codn (.%a)bc ,
consider
.codn [^a]*abc .
The set of strings which don't contain the
character a is adequately expressed by
.codn [^a]* .