docs/text-data.md
Unmodified engine source document, commit af8e0b5f6d97ab379337d3539fd8dbe0d6337fd8. Markdown source is displayed as text to preserve exact content.
# Text and data processing (M38)
> M39 added string streams, `FORMAT`, `SUBSEQ`, `SORT` and more on top of this page: see [text composition](text-composition.md).
M38 turns the M37 file streams into a base for standalone text and data programs: characters
and strings, integer parsing, character input and output, `READ` / `PRIN1` / `PRINT` on
streams (so that symbolic data can be written and read back), program arguments for batch
scripts, and `IDENTITY` / `COPY-LIST` / `REDUCE`. The design is
[ADR 0026](decisions/0026-character-io-read-and-script-arguments.md); the file and stream
basics (`OPEN`, `CLOSE`, `READ-LINE`, `WITH-OPEN-FILE`, the standard streams) are in
[text I/O](text-io.md). Everything here works on the same streams: files, `*STANDARD-INPUT*`
and `*STANDARD-OUTPUT*`.
## Quick start
A filter from standard input to standard output, run as `rustlisp --script fold.lisp`:
```lisp
(loop
(let ((form (read *standard-input* nil *standard-input*)))
(when (eq form *standard-input*) (return))
(prin1 form)
(terpri)))
```
Symbolic data written and read back:
```lisp
(with-open-file (out "data.sexp" :direction :output :if-exists :supersede)
(print '(:name "Ada" :age 36 :tags (math code)) out))
(with-open-file (in "data.sexp")
(read in)) ; => (:NAME "Ada" :AGE 36 :TAGS (MATH CODE))
```
Arguments of a script (`rustlisp --script wc.lisp input.txt`):
```lisp
(with-open-file (in (first *command-line-arguments*))
(read-line in))
```
## Which operators, and where they live
| Operator | Where | Section |
|---|---|---|
| `CHAR-CODE` `CHAR-INT` `CODE-CHAR` `DIGIT-CHAR-P` `DIGIT-CHAR` `ALPHA-CHAR-P` `ALPHANUMERICP` `UPPER-CASE-P` `LOWER-CASE-P` `BOTH-CASE-P` `GRAPHIC-CHAR-P` | Rust builtins | [Characters](#characters) |
| `CHAR/=` `CHAR<` `CHAR>` `CHAR<=` `CHAR>=` `CHAR-EQUAL` `CHAR-NOT-EQUAL` `CHAR-LESSP` `CHAR-GREATERP` `CHAR-NOT-GREATERP` `CHAR-NOT-LESSP` | Rust builtins | [Characters](#characters) |
| `STRING` `STRING-UPCASE` `STRING-DOWNCASE` `PRINC-TO-STRING` | Rust builtins | [Strings](#strings) |
| `PARSE-INTEGER` | Rust builtin | [PARSE-INTEGER](#parse-integer) |
| `READ-CHAR` `PEEK-CHAR` `UNREAD-CHAR` | Rust builtins | [Character input](#character-input) |
| `WRITE-CHAR` `WRITE-STRING` `TERPRI` `FINISH-OUTPUT` `FORCE-OUTPUT` | Rust builtins | [Output](#character-and-string-output) |
| `READ` `READ-PRESERVING-WHITESPACE` | Rust builtins | [READ](#read) |
| `PRIN1` `PRINT` (and `PRINC`, M18) | Rust builtins | [Printing](#printing-and-round-trips) |
| `*COMMAND-LINE-ARGUMENTS*` | special variable | [Command line](#the-command-line) |
| `IDENTITY` `COPY-LIST` `REDUCE` | Layer 0 Lisp | [List functions](#identity-copy-list-and-reduce) |
The Rust builtins are protected names (`DEFUN` of them is an error); the Layer 0 functions are
ordinary redefinable names and use only special operators and protected builtins, so
redefining `NOT`, `REVERSE`, `AND` and the like does not break them.
Where a name exists in Common Lisp, its behaviour was compared with SBCL
(`examples/paip/m38-cases.tsv`, 223 cases; `scripts/paip-baseline.py`). The places where this
implementation differs, deliberately, are marked **Difference** below and collected in
[Differences from Common Lisp](#differences-from-common-lisp).
## Characters
Characters are Unicode scalar values. `(char-code c)` is the scalar value (0 to 1,114,111) and
`(code-char n)` the character, or `NIL` when `n` is a surrogate (55296 to 57343) or above
1,114,111; a negative or non-integer `n` is a type error. `CHAR-INT` is `CHAR-CODE`.
`(digit-char-p c &optional (radix 10))` is the weight of `c` as a digit, or `NIL`. Radix is 2 to 36
(anything else is a type error); digits are `0`-`9` and letters of either case. **Difference:**
digits of other scripts are not digits. `(digit-char weight &optional (radix 10))` is the digit
character (upper case for letters) or `NIL` when `weight` is not below `radix`.
| Predicate | True for |
|---|---|
| `ALPHA-CHAR-P` | Unicode alphabetic characters |
| `ALPHANUMERICP` | Unicode alphabetic or numeric characters |
| `UPPER-CASE-P` / `LOWER-CASE-P` | characters whose case mapping (see below) turns them into a different character in the other direction |
| `BOTH-CASE-P` | either of the two |
| `GRAPHIC-CHAR-P` | every character that is not a control character; Space is graphic, Newline, Tab and Rubout are not |
Case mapping is the one `CHAR-UPCASE` / `CHAR-DOWNCASE` use: a character maps to the Unicode
upper or lower case of it if that is exactly one scalar value, and to itself otherwise. So
`(upper-case-p #\É)` is true, and `ß` (whose upper case is `SS`) has no case here.
The comparisons take one or more characters and check every argument first. `CHAR<` `CHAR>`
`CHAR<=` `CHAR>=` compare adjacent pairs by code point; `CHAR/=` is true when **no two**
arguments are equal. The `-EQUAL` / `-LESSP` family ignores case by folding to lower case (so
`#\[` sorts below `#\a`, as in SBCL). One argument gives `T`.
## Strings
`(string x)` returns a string argument itself, and a fresh string for a character or a symbol
(a symbol's name, without a keyword colon). Anything else is a type error.
`(string-upcase x &key start end)` and `STRING-DOWNCASE` return a fresh string with the
characters in `[start, end)` case-mapped; `x` is a string designator as for `STRING`. `:start` must be
an integer in range; `:end` may be `NIL` (the length). Bad bounds are type errors.
`(princ-to-string object)` is a fresh string of the aesthetic form of `object` (the text `PRINC`
would write). `(prin1-to-string object)` is the readable form (M18).
## PARSE-INTEGER
`(parse-integer string &key start end radix junk-allowed)` returns two values: the integer and
the index (in characters) where parsing stopped.
- White space (Space, Tab, Newline, Return, Page) is skipped before the number; an optional
`+` or `-`; then at least one digit of `radix` (default 10, up to 36).
- Without `:junk-allowed` only white space may follow, and it is skipped; any other
character is an error. The second value is `:end` (the end of the substring).
- With `:junk-allowed` true the parse stops at the first character that is not a digit and the
integer is returned; if there were no digits the result is `NIL` and the index where it stopped.
- Values promote from i64 fixnums to bignums (ADR 0057), whether or not junk is allowed.
Exceeding the implementation exact-number bit limit is an arithmetic error; values never wrap.
- Errors: text that is not an integer is a **parse error** (`parse error: PARSE-INTEGER: no digits in "abc"`),
a program error that `HANDLER-CASE` and `HANDLER-BIND` see like any `ERROR`. A non-string argument, bad bounds
(`:start` must be an integer in range, `:end` may be `NIL`) or a bad radix is a type error. A mistake in the
keyword list is `invalid syntax`, as everywhere.
`(handler-case (parse-integer s) (error () nil))` is the usual "integer or `NIL`" idiom
(`examples/text/text-lib.lisp` has it as `text-number-or-nil`).
## Character input
`(read-char &optional stream eof-error-p eof-value recursive-p)` returns the next character.
`(peek-char &optional peek-type stream eof-error-p eof-value recursive-p)` returns it without
consuming it: with a `peek-type` of `T` it first consumes white space (Space, Tab, Newline,
Return, Page), with a character it first consumes everything before the first occurrence of that
character (a comment is not skipped). `(unread-char character &optional stream)` puts back the character
the last `READ-CHAR` returned.
- The stream designator is as for `READ-LINE` ([text I/O](text-io.md#stream-designators)).
- Characters are decoded from UTF-8, and **no line-ending translation** is done: `CR LF` is two
characters (`READ-LINE` is the operation that treats it as one terminator).
- At end of file `eof-error-p` (default true) decides as for `READ-LINE`: a file stream signals a
stream error that `ERROR` handlers see; the host input keeps the M18 `end of file` error, which they do
not; otherwise `eof-value` (default `NIL`) is returned. `recursive-p` is accepted and ignored.
- Invalid UTF-8 is a stream error naming the operator. The offending lead byte and the valid continuation
bytes that followed it are consumed, and the byte that broke the sequence is not, so reading on resynchronises.
An incomplete sequence at the end of a file is one such error.
- **Difference:** `UNREAD-CHAR` is checked. It is a stream error unless the character is exactly the one
the last `READ-CHAR` returned and nothing has been unread since; a `READ-LINE` or `READ` in between
makes it an error (a `PEEK-CHAR` does not: the unread character goes in front of the peeked one). Common Lisp makes
these cases undefined; SBCL accepts some.
- Characters handed back (`UNREAD-CHAR`, `PEEK-CHAR`, and the text a `READ` fetched beyond its object) belong to
the stream and come before the rest of the file for every operation, `READ-LINE` included.
- `LISTEN`, `READ-CHAR-NO-HANG` and `CLEAR-INPUT` do not exist: process standard input cannot be tested for readiness
without blocking in safe Rust.
## Character and string output
| Operator | Result | Writes |
|---|---|---|
| `(write-char character &optional stream)` | `character` | the character, UTF-8 |
| `(write-string string &optional stream &key start end)` | `string` | `string[start, end)`; `NIL` bounds mean the defaults |
| `(terpri &optional stream)` | `NIL` | a newline (`LF`), always |
| `(finish-output &optional stream)`, `(force-output ...)` | `NIL` | nothing; buffered text is written through to the file or the process, and a failure is reported |
| `(write-line string &optional stream &key start end)` | `string` | as in M37 |
Output is buffered per stream; `CLOSE` and `FINISH-OUTPUT` write it out. `FRESH-LINE` knows the column
(beginning of line) of every stream however the text got there; `PRINT` leaves it after its trailing space,
not at a line start. An input stream, a closed stream or a non-stream is an error before anything is written.
`FINISH-OUTPUT` on an input stream is a type error (SBCL answers `NIL`).
## READ
`(read &optional stream eof-error-p eof-value recursive-p)` reads one object with the ordinary reader
(the same syntax as source code: lists, dotted pairs, symbols, keywords, integers, strings, characters with
`#\`, `'`, `#'`, backquote, `;` comments) and gives the text after it back to the stream.
- **It never fetches input beyond its object.** The stream is read a line at a time, and as soon as an object
has certainly ended (a closing parenthesis, a closing quote, a token followed by a delimiter) the reader runs
on what has been gathered. So `READ` on a terminal or a pipe returns when the object is complete, even if
more text follows on the same line, and a line holding the start of a second object is not waited on.
An object that spans lines is gathered whole. (`tests/m38.rs` checks this with a live pipe.)
- After the object, **one white-space character is consumed** (`CR LF` counts as one), whatever the kind
of object, as SBCL does; nothing else is. `READ-PRESERVING-WHITESPACE` consumes nothing. So after
`(read s)` of `(a b)` followed by a newline, `(read-line s)` returns the next line, not an empty one.
- Everything after the object on its line stays in the stream: `READ` then `READ-LINE` sees the rest of the line.
- A clean end of file (only white space and comments left) is the end of file of `READ-CHAR`: an error if
`eof-error-p` (stream error for files, the M18 error for standard input) or `eof-value`. **An object cut
short by the end of the file is always `read error: unexpected end of input`**, whatever `eof-error-p` says.
- **Reader errors are `ERROR` conditions** (since M39, ADR 0027; they were not in M38): an unmatched `)`, malformed text and
an object cut short by the end of the input. `HANDLER-CASE` catches them. Still not conditions: `not implemented` for syntax
the reader does not have (`#(...)`, `#<...>`, `|...|`, a backslash outside a string or character, integers
beyond 64 bits) and a clean end of file on the *host* input.
A missing package in `pkg:sym` is an ordinary reader error, and `HANDLER-CASE` catches it.
The text gathered for an object that failed to read is consumed; the lines after it are not.
- The text of one object is limited to 16 MiB (as a line is); beyond that is a stream error.
- The reader's own limits apply (nesting depth 256). A symbol is read in upper case, as in source code.
`*PACKAGE*` selects the package (M45). `pkg:name` and `pkg::name` are qualified symbols.
The package operators named as absent in [semantics](semantics.md) are absent.
`DEFPACKAGE` accepts `:USE`, `:EXPORT` and `:SHADOW`. `SHADOW` is a builtin.
- `READ` evaluates nothing (there is no `#.`). To evaluate what was read use `EVAL`.
## Printing and round trips
`(prin1 object &optional stream)` writes the readable form and returns `object`. `(print object &optional stream)`
writes a newline, the readable form and a space, and returns `object`. `(princ object &optional stream)` (M18) writes the
aesthetic form. **`PRINC` now writes a keyword without its colon** (`(princ :key)` is `KEY`, as in Common Lisp when
`*print-escape*` is false); `PRIN1` keeps `:KEY`.
The readable form of an integer, symbol, keyword, string, character, list or dotted pair is read back as an `EQUAL`
object, which `tests/m38.rs` checks on generated data containing awkward characters (`( ) " ; ' \` , # \ |`, controls,
Unicode, line separators) in strings, characters and lists, under every garbage-collection policy:
- strings print with `"` and `\` escaped and everything else literally, newlines included;
- characters print as `#\` and the character, or by name (`Space`... `Newline`, `Tab`, `Return`, `Page`, `Backspace`,
`Rubout`, `Null`), or `#\U+XXXX` for other controls; the reader accepts all of these;
- quote forms print as `(QUOTE X)` and `(FUNCTION F)` and read back as the same lists (SBCL prints `'X`);
- `NIL` prints as `NIL`, also for `()` and an empty list inside a list.
What does **not** round trip: a circular or very deep structure (printed with `...` after 256 levels, 1,000,000 conses
or a cycle), functions, streams and other objects (`#<...>`, which the reader refuses), and symbols that
did not come from the reader (there is no way to make one yet). Printing is unaffected by `*print-...*`
variables, which do not exist.
## The command line
```
rustlisp [--quiet] [--load FILE]... [-e EXPRESSION] [-- ARGUMENT...]
rustlisp [--quiet] --script FILE [ARGUMENT...]
```
- **`--script FILE ARG...`**: everything after `FILE` belongs to the program, verbatim, including things that
look like options (`--help`, `-e`, `--`). This is what makes `#!/usr/bin/env rustlisp --script` scripts
work: the system appends the script path and then the user's arguments.
- **`-- ARG...`** ends the options of `-e`, `--load` and the REPL; what follows is the argument list.
- `*COMMAND-LINE-ARGUMENTS*` is a special variable holding the list of strings, in order: empty strings, spaces, Unicode
and quote characters are preserved. Without arguments it is `NIL`. It is a fresh list; the program may rebind or
assign it. The host sets it before any Lisp runs (`Interp::set_command_line_arguments` for embedders). The program
name and the script's path are not in it.
- A command-line argument that is not valid Unicode is refused before anything runs: status 2, a message
on standard error and the usage text.
- A first line of `#!...` is ignored in a file given to `--script` and also by `LOAD` (the line's newline is
kept, so line numbers in error messages are unchanged). A `#!` on any later line is not Lisp and an error.
- **Status:** 0; the `(rustlisp-exit :code N)` code; 1 for an error nothing handled (the message, located
at the top-level form, goes to standard error); 2 for command-line mistakes. **A closed output pipe** (`rustlisp
--script prog.lisp | head -1`) ends the program quietly with 141 on Unix (what a process killed by `SIGPIPE`
reports) and 1 elsewhere; the error unwinds through `UNWIND-PROTECT` and `WITH-OPEN-FILE`, so files are flushed and
closed first.
- Standard input and output stay what they were in M37: the program owns standard input, output is written
unbuffered through the host writer, nothing is evaluated that the program does not read.
## IDENTITY, COPY-LIST and REDUCE
`(identity object)` returns its argument (one value).
`(copy-list list)` copies the conses of the spine and shares the elements. A dotted list stays dotted and
its final cdr is the same object. `NIL` is `NIL`. A non-list is a type error. A **circular** list has no
finite copy and is an error (`COPY-LIST: the list is circular`, a catchable error), detected as the copy
proceeds. It is iterative: long lists need no recursion.
`(reduce function sequence &key key from-end start end initial-value)` combines the elements of a list or a
string:
- The elements of `[start, end)` (`:end NIL` is the length) are taken in order, each passed through `:key`
once; the function is then applied as `(function accumulator element)` left to right, or, with `:from-end`,
as `(function element accumulator)` from the right.
- With `:initial-value` that value starts the fold (and is not passed through `:key`); without it the first
element does. With no elements: the initial value, or **a call of `function` with no arguments**
(`(reduce #'+ nil)` is 0). One element and no initial value: that element, `function` is not called.
- `:initial-value NIL` is an initial value (supplied-p is honoured); `:key NIL` and `:from-end NIL` mean none.
- Bad bounds or a sequence that is not a list, a string or (since M40) a vector are catchable errors.
- It is iterative and builds one list of the selected elements first, so a long list needs no recursion; the
function may do anything, including non-local exits.
## Differences from Common Lisp
- `PRINC` of a keyword and `READ` after-object whitespace follow SBCL; **`READ-FROM-STRING` (M18) keeps its documented
rule** of consuming whitespace only after a token, so `(read-from-string "(a) b")` returns position 3 where SBCL and
`READ` on a stream consume the space (position 4).
- `UNREAD-CHAR` is checked; `FINISH-OUTPUT` on an input stream is an error.
- `DIGIT-CHAR-P` knows only ASCII digits and letters; `ALPHANUMERICP` and the case predicates follow Rust's Unicode
tables and the single-scalar rule above (they differ from SBCL for a few characters such as `²`, `ß`).
- Keyword-list mistakes and unsupported reader syntax are not `ERROR` conditions (reader errors proper became conditions in M39). `PARSE-INTEGER` errors are, as in Common Lisp.
- `PARSE-INTEGER` and the printer support bignums (ADR 0057); bounds and radix arguments remain machine-sized.
- No `LISTEN`, `READ-CHAR-NO-HANG`, `READ-DELIMITED-LIST`, `WRITE`, `PPRINT`, `FORMAT`, `READ-BYTE` / `WRITE-BYTE`,
string streams (`WITH-OUTPUT-TO-STRING`, `MAKE-STRING-INPUT-STREAM`), `SUBSEQ` or `SORT`.
## Examples
Original programs in `examples/text/` (run them from the repository root; they load `text-lib.lisp` by a
relative path):
| File | Command | What it shows |
|---|---|---|
| `wordfreq.lisp` | `rustlisp --script examples/text/wordfreq.lisp [LIMIT] < text` | words, `ALPHANUMERICP`, `CHAR-DOWNCASE`, a hand-written stable sort, `PARSE-INTEGER` on an argument |
| `csv-stats.lisp` | `rustlisp --script examples/text/csv-stats.lisp IN.csv [OUT.txt]` | line input, `PARSE-INTEGER`, rejects with line numbers, `REDUCE`, exit status 3 on rejects, the report sent to a file by rebinding `*STANDARD-OUTPUT*` |
| `records.lisp` | `rustlisp --script examples/text/records.lisp IN.sexp OUT.sexp` | `READ` of property lists, grouping, `PRINT` to a file, reading it back and verifying `EQUAL` |
| `fold.lisp` | `rustlisp --script examples/text/fold.lisp < forms` | a `READ` / `PRIN1` filter between standard input and output |
| `text-lib.lisp` | (library) | portable Common Lisp, compared with SBCL in `examples/text/text-cases.tsv` (47 cases) |
Data files: `people.sexp`, `scores.csv`, `sample.txt`, `expressions.txt`.
Tests: `tests/m38.rs` (contract table, error classes, UTF-8, lookahead, `READ` against the reader on random
token soup and on every example program, generated round trips under all four collection policies, pipes, the
examples). The SBCL-compared tables are `examples/paip/m38-cases.tsv` and `examples/text/text-cases.tsv`.
MediaLisp