# vile A Scheme implementation in V, with an R5RS scanner, datum reader, and [embeddable runtime](scheme/README.md). Vile is one R5RS-based dialect with selected R6RS/R7RS extensions. Both surface syntaxes use the same language and runtime. See [the feature checklist](CHECKLIST.md) for the remaining work; report names describe feature origins, not separate modes. ## Build and run ```sh v -cc gcc -prod -o vile main.v ./vile # REPL; EOF (Ctrl-D) exits ./vile program.scm # Scheme file ./vile program.vile # Vile file, detected automatically ./vile -e '(+ 3 (* 2 4))' # print 11 printf '(display 42) (newline)\n' | ./vile - ./vile --help ``` To build with TinyCC, run `v -cc tcc -o vile main.v`. This selects scalar scanning and V's portable complex math at compile time for both frontends. The REPL keeps definitions and reader case state between inputs, and continues incomplete lists, strings, comments, and other unfinished datums on the next line. `-e`/`--eval` can be repeated in the same environment. Both print results except unspecified values. Files and `-` (stdin) print only through `display`, `write`, and `newline`, provided by the runtime port library. Errors go to stderr; failed scripts and expressions exit with status 1. The CLI defaults to unlimited execution steps and continuation frames; `--max-steps N` sets a per-evaluation instruction/application budget (`0` disables it). Non-tail calls retain their pending work in memory. The embedding API keeps its configurable default limits. V hosts can also use [cooperative context cancellation](scheme/README.md#host-cancellation) through `VM.with_context`, including native reentry and either frontend. An opt-in [cooperative arena usage threshold](scheme/README.md#cooperative-arena-usage) also samples absolute region usage; it is distinct from a hard allocator cap. For builds without a hosted C runtime, see [freestanding support](FREESTANDING.md). ## Reader syntax Source starts with R5RS case folding. `#!fold-case` and `#!no-fold-case` control subsequent identifiers and character names. Ports, the REPL, and repeated `-e` inputs retain that state; separate source files start independently. Unicode17 full folding does not normalize identifier spelling. ```scheme #!no-fold-case (define Straße 42) (list Straße #true #false #u8(0 255) #vu8(65)) ``` Both frontends accept nested `#| ... |#` comments, `#;` datum comments, barred and hex-escaped identifiers, named/hexadecimal characters, hexadecimal string escapes, and string line continuations. `#!r6rs` is an accepted comment directive; it does not select a language profile or another library system. `[]` in Vile still builds an evaluated vector; bytevector literals contain exact integers in `0..255`. Labels preserve datum sharing and cycles. Their scope is one outer datum: ```scheme (define ring '#1=(leaf . #1#)) (eq? ring (cdr ring)) ; #t ``` Forward references are a Vile extension to R7RS. Duplicate/unresolved labels and cycles consisting only of aliases are errors. Executable structures, quasiquote templates, and `syntax-rules` pattern/template definitions must be finite. Macros can still capture cyclic datums and quote them. `write` emits readable symbol and string escapes, and `write-shared` also preserves string/bytevector sharing. Procedural macros use the same compiler and library system as `syntax-rules`: ```scheme (define-syntax identity (lambda (form) (syntax-case form () ((_ expression) #'expression)))) (identity (+ 20 22)) ; => 42 ``` `syntax-case`, `with-syntax`, `quasisyntax`, identifier comparisons, datum/syntax conversion and temporary generation are available through `(vile syntax-case)` and its unversioned `(rnrs syntax-case)` alias. The reader accepts `#'`, `#``, `#,`, and `#,@`. See the [paired macro examples](examples/macros/main.scm) and the [runtime documentation](scheme/README.md) for hygiene and ownership details. `(command-line)` returns the script filename followed by its arguments. Interpreter options precede the filename; everything after it belongs to the script: ```sh ./vile program.scm hello --verbose ./vile -e '(command-line)' -- hello --verbose ``` With `-e` or the REPL, the first element is the interpreter name. `--` ends option parsing. `exit` runs outstanding `dynamic-wind` after procedures and closes managed ports before the host exit hook. Custom port closers run on the exiting machine; their saved continuations retain the remaining cleanup, and a closer can supersede the exit status. `emergency-exit` terminates immediately. Omitted status or `#t` means success, `#f` means failure, and exact integers supply the low eight bits of the OS status. Embedded V hosts receive a typed request by default; see [system interfaces](scheme/README.md#system-interfaces). For a checked whole-process comparison with Guile: ```sh v -cc gcc run bench/compare_guile.vsh --samples 31 --iterations 100000 ``` The runner verifies every exit code and printed sum before accepting timings. The front-end inspection commands remain available: ```sh v run . --tokens main.scm v run . --read main.scm v test . ``` ## Shared and cyclic data output `write` and `display` terminate on cyclic pairs/vectors using datum labels. Ordinary acyclic output keeps its existing representation. `write-shared` also preserves acyclic sharing, while `write-simple` never emits labels and rejects cycles instead of hanging an embedding host: ```scheme (define tail (list 2 3)) (define rows (list (cons 1 tail) tail)) (write rows) ; ((1 2 3) (2 3)) (write-shared rows) ; ((1 . #0=(2 3)) #0#) (define ring (list 1)) (set-cdr! ring ring) (write ring) ; #0=(1 . #0#) ``` The new procedures accept an optional textual output port and are exported by `(scheme write)`. Labels start fresh on each call. Records retain their opaque printed representation. Source and port readers accept shared/cyclic datum labels; quoted source data is immutable and port reads return mutable data. See the runnable [Scheme example](examples/shared/main.scm) and [Vile example](examples/shared/main.vile). ## List helpers and stable sorting Selected R6RS procedures are available in the same dialect: ```scheme (filter even? '(3 1 4 2 5)) ; (4 2) (fold-left + 0 '(1 2 3)) ; 6 (list-sort < '(3 5 2 1)) ; (1 2 3 5) (vector-sort < '#(3 1 2)) ; #(1 2 3) (define data (vector 3 1 2)) (vector-sort! < data) ; unspecified; data is now #(1 2 3) ``` `find`, `memp`, and `assp` search with a predicate. `for-all` and `exists` short-circuit across one or more lists, returning the predicate's actual value where appropriate. `partition` returns two lists as multiple values. Other additions are `remp`, `remove`, `remv`, `remq`, `fold-right`, and `cons*`. Sorts are stable, preserving the order of elements with equal keys. `list-sort` and `vector-sort` leave their inputs unchanged; `vector-sort!` requires a mutable vector. Comparators use a strict ordering. List predicates/combiners must not mutate the input list structure. Short-circuit searches inspect only the consumed prefix; list lengths for multi-input predicates are checked only as needed. `(vile lists)` / `(rnrs lists)` export the selected list collection, and `(vile sorting)` / `(rnrs sorting)` export the sorting collection. These are unversioned binding collections sharing the same pristine procedures. Libraries use R7RS-small's `define-library` and import sets; these names do not select modes. Vile syntax uses the same procedures: ```text list-sort(<,list(3,1,2)) filter(even?,list(3,1,4,2)) fold-left(+,0,list(1,2,3)) ``` Barred identifiers let Vile call names that otherwise contain operator characters: ```text |cons*|(1,2,list(3)) ``` See the [Scheme example](examples/lists/main.scm), [Vile example](examples/lists/main.vile), and [embedding details](scheme/README.md#list-utilities-and-sorting). ## Selected Scheme extensions Self-evaluating keywords such as `#:name` work in both frontends. The default environment and `(vile keywords)` export `keyword?`, `symbol->keyword`, and `keyword->symbol`. Keyword names use the same Unicode, escaping, and case rules as identifiers; `#:||`, `#:|123|`, and `#:|space name|` name unusual keywords. Symbol/keyword conversions share immutable storage and allocate nothing. See [keyword details](scheme/README.md#keywords). This is groundwork for GOOPS; keyword argument binding and object dispatch are separate features. `when` and `unless` conditionally evaluate a sequence, and `letrec*` initializes recursive bindings from left to right. `case-lambda` selects the first clause whose parameters accept the supplied arguments. `case` also accepts `=>` receivers, including in its `else` clause: ```scheme (letrec* ((x 20) (y (+ x 22))) (when (> y 0) (display y) (newline))) (define add (case-lambda ((x) (+ x 1)) ((x y) (+ x y)))) (add 20 22) ; 42 (case 41 ((41) => add)) ; 42 ``` `let-values` binds several results from each initializer; all initializers see the enclosing scope. `let*-values` makes each group visible to the following initializers. `define-values` works at top level and among internal definitions: ```scheme (let-values (((x y) (values 20 22))) (+ x y)) ; 42 (let*-values (((x) 20) ((y) (+ x 2))) (+ x y)) ; 42 (define-values (first . remaining) (values 1 2 3)) ``` Formals support fixed lists, dotted tails, and a single rest identifier, as in `lambda`; mismatched result counts are errors. Fixed bindings unpack existing results directly into argument slots. Only a rest formal constructs a list. `delay-force` composes lazy computations without accumulating a pending force for each link. Its expression must return a promise. `make-promise` eagerly wraps a value, returning an existing promise unchanged; `promise?` tests for promises. Ordinary `delay` still returns its result without flattening it: ```scheme (define (countdown n) (delay-force (if (= n 0) (make-promise 42) (countdown (- n 1))))) (force (countdown 10000)) ; 42 ``` Long chains use bounded forcing stack space. All aliases share the first completed result, including across recursive forcing and continuation reentry. As with ordinary procedure execution, the host's instruction budget still applies. `make-parameter` creates a procedure holding a dynamically configurable value. Call it with no arguments to read the current value, or one argument to update the current binding. `parameterize` installs temporary bindings for its body: ```scheme (define radix (make-parameter 10)) (define (format-number n) (number->string n (radix))) (parameterize ((radix 2)) (format-number 12)) ; "1100" (format-number 12) ; "12" ``` An optional converter runs at creation, explicit updates, and new parameterized bindings. Restoring a binding or reentering its body through a continuation does not rerun the converter. Binding expressions run once in the enclosing context; conversions finish before any temporary bindings are installed. Repeated bindings of the same parameter use the last value. Parameters are also ordinary first-class procedures, including when called from V through `vm.call`. The three current ports are parameters too. String ports can capture output or provide input without touching the process streams: ```scheme (parameterize ((current-output-port (open-output-string))) (write-string "aλ😀z" (current-output-port) 1 3) (newline) (get-output-string (current-output-port))) ; λ😀 followed by a newline (call-with-port (open-input-string "20 22") (lambda (p) (+ (read p) (read p)))) ; 42 ``` `read-line`, `read-string`, and `write-string` use Unicode character positions. `flush-output-port` flushes files, standard streams, and capable host Writers. String snapshots are independent of later writes and mutations. See the [port embedding API](scheme/README.md#ports-and-host-io) and [Vile syntax example](examples/alt/text_ports.vile). Bytevectors hold raw bytes. `bytevector`, `make-bytevector`, the `bytevector-u8-*` accessors, and copy/append procedures work through either syntax. UTF-8 conversion is explicit and rejects invalid byte sequences: ```scheme (string->utf8 "λ") ; #u8(206 187) (utf8->string (bytevector 206 187)) ; "λ" (parameterize ((current-output-port (open-output-bytevector))) (write-u8 0) (write-bytevector (string->utf8 "λ")) (get-output-bytevector (current-output-port))) ; #u8(0 206 187) ``` Binary ports accept arbitrary bytes, including invalid UTF-8. Use `open-binary-input-file`/`open-binary-output-file` for files, or bytevector ports for memory. `read-u8`, `peek-u8`, `u8-ready?`, `read-bytevector`, `read-bytevector!`, `write-u8`, and `write-bytevector` enforce binary mode; character/datum operations enforce textual mode. Both frontends accept immutable `#u8(...)` and `#vu8(...)` literals; constructor results remain mutable. See the [bytevector example](examples/alt/bytevectors.vile). Endian-aware integer/IEEE access and UTF16/32 conversions are available through `(vile bytevectors)` and `(rnrs bytevectors)`. Whole-value codecs/transcoders are available through `(vile io ports)` and `(rnrs io ports)`, together with the port-first `get-*` and `put-*` procedures. Their optional output ranges use start/count; string ranges count Unicode characters. `get-bytevector-some` returns an available chunk, and `get-string-n!` fills an existing mutable string. The same libraries export the six `make-custom-*` binary/textual port constructors, direction-open predicates, and half-close procedures. Imports retain the original runtime procedures even after interaction bindings change. Port-position queries and seeking support memory ports, owned seekable files, and capable V host Readers/Writers. Binary positions are byte offsets; textual positions are opaque tokens returned to the same port. Input lookahead and pending output are included in the logical position. `transcoded-port` transfers a binary port's resource into a textual port and closes the binary alias. `port-transcoder` reports the selected codec, newline style, and error policy even after close. One-way ports, borrowed V duplex ports, and native input/output files support this transfer. Custom Scheme binary callback ports support both one-way and combined transcoding; textual callbacks accept decoded characters directly. A custom combined port calls its shared closer only when its last logical direction closes. Final input close also drains encoded output left by an earlier failed output half-close. Positioned custom binary duplex callbacks describe one shared backend byte cursor. Getter and setter capabilities are independent. Before a write or an input half-close with unread bytes, Vile uses the callbacks to rewind to the logical cursor. This can issue an extra getter/setter callback. With a setter alone, an explicit successful seek must first establish the absolute cursor; accepted callback counts then track it with exact Scheme integers. A getter alone can report the logical cursor but cannot rewind it: a transition that needs a rewind fails while preserving the open input and its unread bytes. Full close discards unread input without seeking. Custom duplex ports with neither position callback retain independent input/output algorithms. Positioned custom textual duplex ports use opaque facade-specific checkpoints. The VM retains the exact source token and an immutable unread snapshot, including Unicode character coordinates and speculative datum prefixes. A read-to-write transition can call the source setter and reread a bounded prefix of characters before the writer runs. Getter-only and setter-only capabilities are advertised independently; a transition without a recoverable origin fails before writing. Tokens remain valid for the same facade across half-closes and never reopen a closed direction. If seeking succeeds but the hidden reread fails, further I/O requires an explicit `set-port-position!`; `port-position` can observe a recovery checkpoint at the current backend frontier. Zero-length reads remain observational and preserve suspended callbacks and probes. Whole-close needs no rewind. Attached custom transcoders with position callbacks also synchronize a shared raw byte cursor. Writes and input half-closes align to the visible character's raw boundary, including split Unicode sequences, normalized newlines, ignored bytes, and speculative datum input. Pending encoded output drains before a positive input request resumes. Zero-length reads preserve unread input. Output that encodes to no bytes also preserves it when no pending output needs draining. A transition requiring an unavailable rewind fails before discarding that input. Attached facades do not expose public position tokens, even when their custom binary backend has position callbacks. Callbacks can capture and resume Scheme continuations. A resumed callback restores its private operation progress, so future I/O after the capture can repeat; callback counts must still describe bytes actually written. A physical cursor acknowledgment is committed once even when private progress replays. For positioned custom duplex ports, a callback returning after a different port operation is rejected before it can publish a stale cursor or input buffer. Once the physical closer has been attempted, resuming an in-flight closing callback cannot cause the wrapper to issue fresh writer requests. The callback's own Scheme code can still resume. `open-file-input-port`, `open-file-output-port`, and `open-file-input/output-port` accept file options, a buffer mode, and an optional transcoder. A native input/output file shares one byte cursor between reading and writing. Lookahead leaves the next character available for an overwrite; a write replaces encoded bytes rather than inserting text. Closing one direction leaves the other usable, and the last close releases the owned descriptor. Borrowed host duplex ports keep their input and output streams independent. For a native shared UTF16 file, a BOM at the attachment origin selects byte order and is preserved when writing, including when the first operation is a write. Without a BOM, output uses big endian and emits no BOM. Later U+FEFF characters remain data. This preservation rule is Vile's file-update policy; one-way and independent duplex output retains its big-endian encoding. Custom callback output also retains big-endian encoding; an input BOM selects only its decoder's byte order, which survives subsequent direction switches. Input normalization and malformed-byte recovery retain physical byte boundaries. For example, after reading `A` and peeking `B` from bytes `41 FF 42` with the `ignore` error policy, a write starts at byte 1, before the ignored byte. Reading `B` instead advances to byte 3. An observed decoding error commits its malformed unit and a subsequent retry cannot move that boundary backward. Attached textual ports do not expose public position tokens; shared files still synchronize their internal cursor when changing direction. `define-record-type` introduces a nominal type, a constructor, a predicate, and named field accessors. Include a third name in a field clause to make that field mutable: ```scheme (define-record-type point (make-point x y) point? (x point-x set-point-x!) (y point-y)) (define p (make-point 20 22)) (set-point-x! p 21) (+ (point-x p) (point-y p)) ; 43 ``` Constructor fields can be reordered or omitted; omitted fields start with an unspecified value. Each execution of an R7RS declaration creates a fresh type, even when its name and fields match an earlier one. Record declarations work in local bodies and through macros. Records compare by identity and print as opaque values; their fields are stored in one allocation. See the [Vile syntax example](examples/alt/records.vile). Selected R6RS record syntax adds `fields`, inheritance, constructor protocols, sealed/opaque types, and compatible nongenerative UIDs. These use the same runtime and R7RS-small library machinery. See the [record APIs](scheme/README.md#records). Sequence procedures include `make-list`, shallow `list-copy`, `list-set!`, `vector-copy`, `vector-copy!`, `vector-append`, `string-copy!`, `vector->string`, and `string->vector`. String/vector copying, conversion to lists, and filling accept optional start/end ranges. String indexes count Unicode characters; in-place copies handle overlap in either direction. ```scheme (vector-copy #(10 20 30 40) 1 3) ; #(20 30) (string-copy "aλ😀z" 1 3) ; "λ😀" (vector-map + #(1 2 3) #(10 20)) ; #(11 22) (member "B" '("a" "b" "c") string-ci=?) ; ("b" "c") ``` `map`, `for-each`, `vector-map`, `vector-for-each`, `string-map`, and `string-for-each` stop at the shortest input. List iteration permits circular inputs when another input is finite. Mapping returns fresh mutable results; reentering a callback continuation preserves earlier returned results. `member` and `assoc` accept an optional comparison procedure. `boolean=?`, `symbol=?`, and character/string comparisons accept two or more arguments. See [the Vile sequence example](examples/alt/sequences.vile). These extensions are available in both syntaxes without a mode flag. Keyword bindings retain lexical shadowing and macro hygiene. Their bodies and receivers preserve tail calls and multiple values. Bare vector literals such as `#(a b)` are self-evaluating data; their elements are not evaluated and their contents are immutable. Vile's `[a, b]` instead evaluates elements into a mutable vector. See [the Vile example](examples/alt/extensions.vile) and the [R7RS expression rules](https://standards.scheme.org/corrected-r7rs/r7rs-Z-H-6.html). ## Source files and loading `load` evaluates a source file in the interaction environment and returns an unspecified value. It also accepts an explicit environment specifier: ```scheme (load "config.vile") (load "helpers.scm" (interaction-environment)) ``` In Vile syntax, write `load("config.vile")`. Loaded `.vile` files use Vile syntax; `.scm` and other extensions use Scheme. Each nested load selects its own syntax, independently of the CLI override on the entry file. Relative loads resolve against the file containing the calling expression, including calls inside closures invoked later. Inputs without a filename (the REPL, `-e`, or stdin) resolve against the process directory. Loading does not change the process directory or current ports. Definitions are global; `load` is not a lexical binding form or an isolated library import. Top-level forms compile as execution reaches them, so loaded macros are visible to subsequent forms, including top-level `begin` groups. Every file is parsed before its first form runs. Runtime failures preserve earlier completed definitions, and diagnostics retain the original file, line, and column. See [the config file](examples/alt/config.vile) and [its loader](examples/alt/use-config.vile). V hosts can use `vm.eval_file(path)!Value` to select syntax by extension and return the final value, or `vm.eval_file_as(path, .scheme)` / `.vile` to force a frontend. ## Libraries Libraries register without executing their bodies. Importing a library initializes its dependencies and body once per VM, then installs its exported bindings: ```scheme (define-library (example counter) (export next!) (import (scheme base)) (begin (define value 40) (define (next!) (set! value (+ value 1)) value))) (import (example counter)) (next!) ; 41 ``` Imports support nested `only`, `except`, `prefix`, and `rename` transformations. Imported variables share their library's locations and cannot be assigned or redefined through the imported name. Exported macros retain their private definition-site bindings. Library declarations support `export`, `import`, `begin`, `include`, `include-ci`, `include-library-declarations`, and `cond-expand`. `(scheme ...)` catalogs expose the standard names implemented so far. `(vile base)` exposes the combined dialect. These are binding collections in the same runtime. `(environment '(scheme base) '(scheme write))` creates an immutable evaluation environment for `eval`. Library names map to paths such as `(example state)` → `example/state.sld`. Search tries the caller's directory, the root used to discover its library, V host paths added with `add_library_path`, and the process directory. Suffixes are tried in order: `.sld`, `.scm`, `.vile`; the last uses Vile syntax. Special filename bytes are percent-encoded. See the runnable [Scheme](examples/libraries/main.scm) and [Vile](examples/libraries/main.vile) examples, and the [embedding documentation](scheme/README.md#libraries). Complex arithmetic now shares the exact integer/rational tower and inexact transcendental functions. Both syntaxes accept finite rectangular/polar notation; constructors, components and `magnitude`/`angle` are available. Zero imaginary parts collapse to scalars after inexact contagion, following the selected R5RS behavior. See [numeric representations and complex branch rules](scheme/README.md#complex-numbers) for host ownership, nonfinite reader limits and libm portability. ## Newer numeric procedures The shared numeric library adds `exact`, `inexact`, `exact-integer?`, `square`, `exact-integer-sqrt`, floor/truncate division families, and optional-base `log`. Square roots and paired division return multiple values: ```scheme (call-with-values (lambda () (floor/ -5 2)) list) ; (-3 1) (call-with-values (lambda () (exact-integer-sqrt 12345)) list) ; (111 24) ``` `finite?`, `infinite?`, and `nan?` classify real and complex values. `string->number` accepts signed decimal infinity/NaN spellings, and printing uses those spellings. Results of `number->string` remain independent mutable strings. Source and port readers accept signed decimal infinity/NaN literals, including complex components. Exact integers and rationals promote through V `math.big`, while small integers and rational components keep their existing fast representations. See the [numeric implementation notes](scheme/README.md) and runnable [Scheme](examples/numeric/main.scm)/[Vile](examples/numeric/main.vile) examples. ## Source inclusion and feature selection `include` splices files into the surrounding scope, so included definitions can share a procedure's local variables. Filenames must be string literals: ```scheme (include "helpers.scm" "settings.vile") (cond-expand ((and vile (library (scheme char))) (display "character library available")) (else (display "fallback"))) ``` Lookup tries the containing file's directory, V host paths added with `add_include_path`, then the process directory. Included `.vile` files use Vile syntax. `include-ci` uses case folding; both readers currently fold identifiers by default. Strings retain their contents. Included code keeps its own filename for diagnostics and relative file operations. `cond-expand` selects forms statically using feature identifiers, `and`, `or`, `not`, and `(library (...))` requirements. Library queries discover declarations without initializing them. `(features)` returns an immutable list of the implementation's feature identifiers. Vile advertises its own implementation and platform flags, without claiming complete R6RS/R7RS conformance. See the runnable [Scheme](examples/inclusion/main.scm) and [Vile](examples/inclusion/main.vile) examples. ## Vile syntax `+` joins strings as well as adding numbers: `"hello " + "world"` produces `"hello world"`. All operands must be strings or all must be numbers; `string-append` remains available. The shared runtime also accepts `(+ "hello " "world")` in Scheme syntax. In Vile syntax, a procedure name used as a standalone statement calls it with no arguments: `a` behaves like `a()`. Data variables still evaluate to their values. Arguments and assignment values remain references, so `map(a, xs)` and `b := a` pass or store the procedure. An explicit call runs once, and a procedure returned by that call is not called again automatically. Scheme syntax and V host lookups retain ordinary first-class procedure references. To inspect a procedure as a standalone result in Vile, use `values(a)`. The reader prints implicit calls using the reserved `vile:statement` compiler form so the lowered output can be evaluated as Scheme. File inputs select their format by extension: `.scm` uses Scheme and `.vile` uses Vile syntax. Other extensions retain the Scheme default. `--vile` / `-v` forces Vile syntax; `--scheme` / `-s` forces Scheme syntax. Explicit modes override the file extension and are mutually exclusive. Both modes apply to files, `-e`, stdin, the REPL, `--read`, and `--tokens`. Without an override, files use extension detection; `-e`, stdin, and the REPL use Scheme. `--version` continues to print the version; `-v` selects Vile. The two formats use separate scanners and readers and share the existing compiler and VM. Scheme scanning and instruction execution retain their existing paths. ```sh ./vile -v -e '3 + 2 * 4' # 11 ./vile --vile -e '+(3, *(2, 4))' # 11 ./vile --vile -e '[1, 2 + 3, [4, 5]]' # #(1 5 #(4 5)) ./vile examples/alt/sum.vile ./vile --read program.vile # inspect lowered Scheme forms ./vile --tokens program.vile ./vile -s misnamed.vile # explicitly read Scheme ``` The flag also applies to the REPL and repeated `-e` inputs. For example: ```scheme define(sum-loop(n, acc), if(n == 0, acc, sum-loop(n - 1, acc + n))) display(sum-loop(100000, 0)) newline() ``` Calls use comma-separated arguments, with an optional trailing comma. Infix `* / %`, `+ -`, `< <= > >=`, `== !=`, `&&`, and `||` bind in that order, from strongest to weakest; binary operators associate left. Unary `+ - !` bind more strongly. `%` calls `remainder`; `!` calls `not`; `&&` and `||` use Scheme's short-circuit `and` and `or`. Comparisons retain Scheme semantics: write `a < b && b < c` to compare three values. All arithmetic still uses Scheme's numeric tower, exact division and ordinary procedure bindings. Infix `:=` defines a binding or function, and `=` updates an existing binding through `set!`. Both bind below every arithmetic, comparison, and logical operator. Use `==` for equality: ```scheme answer := 20 + 22 answer = answer + 1 square(x) := x * x same := square(3) == 9 ``` These lower to ordinary `define` and `set!` forms. Assignment updates the nearest lexical binding, including captured variables, and fails if the name is unbound. To replace an existing function, assign a function literal: `square = fn(x) { x + x }`. Chained bindings such as `a := b := 1` or `a = b = 1` are rejected. Prefix `=(a, b)` remains Scheme numeric equality, and ordinary Scheme mode keeps its existing procedures and syntax. Use `{ ... }` for a multi-expression body. Expressions are separated by newlines or commas, and the final expression is the result: ```scheme hypotenuse(a, b) := { aa := a * a bb := b * b sqrt(aa + bb) } make-counter(start) := { count := start fn() { count = count + 1 count } } counter := make-counter(10) [counter(), counter(), counter()] ; #(11 12 13) ``` Blocks lower to `begin(...)` and can appear wherever that form can appear, including function bodies, lambda bodies, and conditional branches. A plain block does not introduce a new lexical scope. In both syntaxes, procedure and binding bodies allow declarations before or after expressions. Local names are in scope throughout their body, but reading one before its initializer runs is an error. Initializers run in source order. A body ending in a declaration returns an unspecified value; definitions in expression operands remain invalid. The statement-style control-flow bodies below provide their own local scopes. Parentheses inside a block allow an expression to span lines; a line ending in an operator also continues the expression. `;` still starts a comment. An empty `{}` returns an unspecified value. See [the complete examples](examples/alt/functions.vile). Statement-style conditionals and loops use ordinary expressions as conditions: ```scheme list-of-squares(n) := { res := list() i := n while i >= 0 { res = cons(i * i, res) i = i - 1 } res } sign(n) := { if n < 0 { -1 } else if n == 0 { 0 } else { 1 } } total := 0 for(i := 0, i < 5, i = i + 1) { total = total + i } total ; 10 ``` Parentheses around a condition are optional. `if` evaluates only the selected branch and returns its result; without `else`, a false condition produces an unspecified value. `while` reevaluates its condition before each iteration, discards body results, and returns an unspecified value. Only `#f` is false; `0` and the empty list remain true as in Scheme. Each statement-style `if` branch and `while` body gives `:=` declarations a local scope. `=` still updates the nearest existing binding. Closures can retain locals from separate loop iterations. The reader lowers these scopes to `let`, loops to `do`, and conditionals to `if`; compiler and VM execution are shared with Scheme. The prefix form `if(condition, yes, no)` remains available. In the REPL, put `else` on the same line as the preceding `}`. `for(init, condition, step) { ... }` evaluates its initializer once, checks the condition before each iteration, and runs the step after each completed body. Its result is unspecified. The initializer's declarations belong to the loop; each iteration gets a fresh body scope. Closures over a header variable share its mutable location, while closures over body locals retain their individual iterations. The step cannot see body-local declarations. All three header expressions are required; use `{}` for an initializer or step with no work. Commas separate the header expressions; semicolons continue to start comments. Without a trailing block, `for(...)` remains an ordinary procedure call. Use `break` or `break()` to finish the nearest `for`, `while`, or `do` loop. It skips the remaining body and step expressions and makes the loop produce an unspecified value. Binding scopes and `parameterize` are transparent to it; procedures, named `let` procedures, and delayed expressions form boundaries. The Scheme spelling is `(break)`. It accepts no arguments, follows ordinary lexical shadowing, and is exported by `(vile base)`. Saved continuations can replay a pending break with the original loop target and dynamic bindings. Use `continue` or `continue()` to skip the remaining body and start the nearest loop's step sequence. A `for` runs its step and then checks its condition; a `while` checks its condition again. Scheme `(continue)` runs all `do` steps using the current iteration's bindings. A continue inside a step restarts the entire step sequence, discarding partial step arguments while preserving explicit mutations. It follows the same scope, shadowing, import, and continuation rules as `break`. The printable lowering of `for` uses a `do` effect-only binding, `(() step)`. It runs the step in binding order and discards its result, without introducing a variable or initializer. Multiple effect-only bindings can appear among ordinary `do` bindings; their names are empty lists, not empty symbols. Use `return(value)` to finish a procedure before its final expression: ```text nonnegative?(xs) := { for(i := 0, i < vector-length(xs), i = i + 1) { if xs[i] < 0 { return(#f) } } #t } ``` `return()` or a bare `return` produces an unspecified value. A return accepts at most one expression and preserves all values that expression produces. It exits the nearest `fn`, `lambda`, named procedure, `case-lambda` clause, or named `let` procedure. Ordinary binding scopes and loop bodies share that procedure's return target. A return cannot cross a delayed expression; a procedure written inside a delayed expression has its own return target. The return operand runs in the current dynamic bindings before those bindings are restored. Saved continuations retain the return target on replay. Tail returns preserve tail calls, including when unreachable forms follow them. The shared runtime also accepts Scheme `(return value)`. `return` is available in the default environment and `(vile base)`; libraries importing only standard collections can import it with `(only (vile base) return)`. A lexical or global variable named `return` shadows the keyword, as with other syntax names. A conditional can select a procedure in infix position: ```scheme x := 1 y := 2 foobar := #f x if foobar { + } else { - } y ; -1 ``` This calls the selected procedure with `x` and `y`. The conditional operator binds at the same level as `+` and `-` and associates left; use parentheses to group other combinations. It evaluates the selector first, then the left and right operands once each. As with other infix expressions, keep the left operand and `if` on the same line or enclose the expression in parentheses. Anonymous functions use `fn(parameters) { body }`, without a second parameter-list wrapper or a trailing comma for one parameter: ```scheme square := fn(x) { x * x } map(fn(x) { x * x }, list(1, 2, 3)) ``` This lowers to `lambda`; zero parameters, multiple parameters, and dotted rest parameters such as `fn(first . rest) { rest }` are supported. `fn`, `if`, `while`, and `for` are contextual names. A trailing body turns `fn(...)` into a function literal or `if(...)` / `while(...)` / `for(...)` into a control form. Otherwise these are ordinary calls, so callbacks can use those parameter names: ```scheme apply-fn(fn, x) := { fn(x) } apply-fn(fn(x) { x + 1 }, 41) ; 42 ``` Bare names also work as values, with infix operators and indexing. An unparenthesized control header needs its condition on the keyword's line; put unary `+`/`-` or vector-literal conditions inside parentheses. Keep the whole condition parenthesized when using a conditional inside a larger infix expression. In the REPL, put the opening `{` on a parenthesized header's line: `fn(x)` and `if(x)` alone are complete calls. Keyword bindings retain the lexical rules of the Scheme forms they lower to. Vector indexing uses `xs[i]`, and indexed assignment uses `xs[i] = value`: ```scheme xs := [[1, 2], [3, 4]] xs[1][0] = 42 xs[1][0] ; 42 ``` These lower to `vector-ref` and `vector-set!`, preserving their type/bounds checks and ordinary procedure bindings. The vector, index, and assigned value are each evaluated once, in that order. Put a separate vector literal on a new line after a completed expression: `f() [i]` indexes the result of `f()`. See [the control-flow example](examples/alt/control.vile) for a complete program. `(expression)` groups arithmetic. `(a, b)` makes a syntax list, `(x,)` makes a one-element list, and `()` is the empty list. This lets binding forms retain their Scheme structure: ```scheme lambda((x,), x * x)(7) let((x(20), y(22)), x + y) let*((x(20), y(x + 2)), x + y) define(collect(first . rest), rest) ``` `[a, b]` lowers to `vector(a, b)`, evaluating its elements and producing a mutable vector. Under quote or quasiquote, brackets denote vector data instead: `'[a, b]` is `#(a b)`. Existing `#(...)` vector datum notation is also accepted, using commas between elements. Quoted parentheses always denote lists, so `'(x)` remains a one-element list. At an element's start, `,x` and `,@xs` retain their quasiquote meanings; after an element, a comma separates arguments. Strings, characters, booleans, quote prefixes, case folding, and `;` comments keep their Scheme meanings. Operator characters delimit names in this mode, with support for standard spellings such as `let*`, `call/cc`, `char<=?`, `string->list`, and `set!`. Hyphens remain part of names: **write `a - b` for subtraction between identifiers**, since `a-b` is a Scheme name. Explicit `#` numeric prefixes and complex literals retain their Scheme numeric spelling; otherwise `/` is infix, so `8/4/2` means `(8/4)/2`. A completed top-level or block-level line ends its form. Expressions inside parentheses or brackets may span lines; an operator at a line's end also continues its operand onto the next line. Runtime `read` and datum `eval` retain their Scheme interfaces; the flag selects the CLI's source input syntax only. Scheme-level `load` is not implemented yet. `--tokens` prints each token's line, column, kind, and original spelling. Backslashes, tabs, and line endings are escaped for display. Invalid input exits with a filename and a located error. Tokens are printed as they are scanned; a lexical error after valid input leaves the preceding token lines on stdout. ## Tokenizer ```v import lexer source := '(+ 12 3)' mut scanner := lexer.new_scanner(source)! for { span := scanner.next()! // Use kind, offsets and positions directly; text is optional. println('${span.kind} ${span.start}..${span.end}') if span.kind == .eof { break } } ``` The scanner returns a `TokenSpan` by value and keeps a constant-size cursor over the source. It does not build a token array or copy lexemes. Identifiers and numbers are classified directly within their source ranges. `span.text(source)` copies the spelling on demand, with fixed punctuation, booleans, and single ASCII bytes sharing immutable NUL-terminated literals. EOF can be requested repeatedly and returns the same span. Discard a scanner after a lexical error. With GCC or Clang, UTF-8 validation skips ASCII prefixes in 16-byte SIMD blocks, then delegates any non-ASCII suffix to V's UTF-8 validator. Comment and string scanning skips blocks without line endings or string special characters, updating byte columns in bulk. Loads stay within the source; special bytes and partial blocks use scalar handling. Other C compilers use scalar scanning. Build with `-d vile_scalar` to disable SIMD for comparison; no AVX-specific flags are needed. The ASCII and string block kernels return scalar flags directly, avoiding SIMD struct copies between operations. They use SSE2 on x86 and NEON on AArch64, with a scalar implementation for other targets. The kernels borrow only complete 16-byte source ranges. Identifier scanning borrows the remaining source in one native call. Short names use an exact 256-byte membership table. Long runs use SSSE3 or AVX2 byte-shuffle tables for the complete R5RS alphabet, including punctuation, when runtime CPU/OS support is present. Other machines retain the SSE2/NEON letter/digit prefix and scalar tail. No CPU-specific compiler flags are required. The native loop returns a bounded byte count; V keeps token classification, source positions and errors. `-d vile_scalar` uses the V loop with the same character alphabet. For callers that need every token and its owned spelling, the collection adapter remains available: ```v import lexer tokens := lexer.tokenize('(+ 12 3)')! // lparen, identifier("+"), number("12"), number("3"), rparen, eof ``` Collection estimates capacity once from progress through its first 32 tokens, with an 8192-token reservation cap. It does not rescan the source or reserve a large token array for one huge scalar. Metadata growth may release private old storage; the returned array supports ordinary slicing and later growth. `lexer/token.v` defines the public token and error types. `lexer/lexer.v` scans tokens and skips whitespace and semicolon comments. `lexer/number.v` recognizes numeric spellings. The implementation follows [R5RS lexical conventions](https://people.csail.mit.edu/jaffer/r5rs_4.html) and the [formal lexical grammar](https://people.csail.mit.edu/jaffer/r5rs_9.html). - Token kinds cover parentheses, vector starts, quote/backquote/comma/comma-at, dots, identifiers, booleans, numbers, characters, strings, and EOF. - Numbers include radix and exactness prefixes, fractions, decimals, exponent markers, rectangular/polar complex forms, and unspecified digits (`#`). Numbers remain text: conversion, exact arithmetic, and runtime validation such as a zero denominator belong to later stages. - Original spelling and case are preserved. The reader will normalize identifier case and decode string/character literals. R5RS supports `\"` and `\\` string escapes; a literal newline is allowed, while the escape `\n` is not. - Identifiers use the R5RS ASCII grammar. Strings, comments, and single-character literals also accept valid UTF-8. Named characters are `space` and `newline`. - Offsets are zero-based UTF-8 bytes; `start..end` is half-open. Lines and columns are one-based, columns count bytes, and tabs occupy one column. CR, LF, and CRLF each count as one line break. Vertical tabs and form feeds are whitespace. - Each collected array ends with exactly one EOF token. The first lexical error returns a `lexer.LexError` with an offset, line, column, and message. The collection adapter returns no partial array. Invalid UTF-8 is rejected when the scanner is constructed, at offset zero. - The lexer keeps syntax separate from meaning: `+` and `if` are identifiers, parenthesis balance belongs to the reader, and R5RS booleans terminate themselves (`#t#f` is two tokens). Identifiers, numbers, character literals, and dots require a delimiter or EOF. The tests exercise the report's examples, malformed and truncated input, numeric combinations, source spans, line endings, UTF-8, long input, and deterministic random ASCII input. ## Reader and flat arena ```v import reader doc := reader.read_all("'(a . b) #(1 2)")! first := doc.forms[0] node := doc.arena.node(first)! println(node.kind) // pair println(doc.arena.write(first)!) // (quote (a . b)) ``` `read_all` consumes one current scanner token at a time. Atoms use a direct path at every level, with the same nesting guard as recursive compound dispatch. A document owns the source, a flat cell arena, a vector-element ID buffer, a shared source-line index, and top-level form IDs. Cells have no per-node strings, pointers, or child arrays. Pair links and vector ranges share two 32-bit payload fields. A line reference fits alongside those fields, keeping full-width byte offsets and constant-time line/column lookup. Cells are 32 bytes on the current 64-bit V build; `node()` returns the unchanged descriptive public `Node` view. Lists and vectors share one reusable ID scratch buffer with a logical stack cursor; closing a compound does not shrink or copy the scratch array. Lists are built backwards into batch-reserved slots once their closing span is known. Every link points to an already initialized cell, so no link patching or source span repair pass is needed. Vectors copy their live IDs once into a flat range. The cell pool uses unscanned Boehm allocations for its pointer-free payload, with matching allocator paths for other GC modes. It grows by reallocating its base allocation. A bounded 1 KiB / 32-token prefix sample estimates initial capacity; it is only a hint, and truncated or invalid samples fall back to a small reserve without changing actual error precedence. A single huge scalar needs only two cells. A large final list reserves its exact remaining cell count. Private buffers have no borrowed slices or pointers, so growth can release their old storage immediately; IDs remain valid. After construction the arena is read-only. Low-level pool and copy operations stay in small, documented private helpers; public accessors check IDs, types and bounds. The reader handles atoms, proper and dotted lists, vectors, and all four quote abbreviations. Abbreviations expand to pair structures such as `(quote datum)`. Symbols remain symbols in every position, including names such as `if` and `+`. It preserves source byte spans and positions. Node zero is a source-free empty-list sentinel; each explicit `()` has its own node and source span. Atoms retain their validated source ranges. `symbol_name`, `boolean_value`, `character_value`, and `string_value` decode values on demand. Numbers preserve their exact spelling; numeric conversion belongs to the runtime layer. Parsing allocates no atom text. `DatumArena.write` prints data, expands abbreviations, folds symbol case, and normalizes proper list tails. Printing uses short-atom fast paths and bounded bulk copies from retained source, without per-atom temporary strings. Scalar roots can return their spelling directly. Case detection uses bounded SIMD loads, and string decoding searches for escapes with bounded `memchr` calls. Uppercase scalar symbols fold a single owned copy in place. Compound printing and escaped string values use `strings.Buffer`. Compound printing uses the root's source span as an initial capacity hint, bounded between 64 and 4096 bytes. Its `take_string()` transfers the base allocation to a NUL-terminated string, avoiding the final full-buffer copy. Growth can still move and copy the buffer, and the result can retain spare capacity. Returned strings own their allocation and can be freed independently. Syntax failures return a located `reader.ReadError`; unfinished forms set its `incomplete` field. Lexical errors retain the `lexer.LexError` type. No partial document is returned. Flat lists and their printing are iterative; recursive datum nesting has a checked depth limit of 512 (top-level depth zero). `--read` validates the file before printing each datum followed by a newline. It reads data; evaluation is the next stage. Correctness tests must run without `-prod`: the current V compiler removes `assert` statements in production builds, including test files. Use `-prod` for benchmark executables, and keep assertions enabled when running tests. ## Benchmark ```sh v -cc gcc -o /tmp/vile-tokenize-bench bench/tokenize.v /tmp/vile-tokenize-bench 65536 /tmp/vile-tokenize-bench 262144 ``` This measures both `collect` (retaining tokens with owned spellings) and `stream` (consuming spans without retaining tokens or requesting text) in memory, with no file I/O or printing in the timed section. It reports the median of three samples for long identifiers, varied identifier bytes, short names, integers, strings, comments, and mixed Scheme source. Samples use fixed-size stack storage. The byte count controls each input's approximate size. Add `-prod` to the build command to measure an optimized build; compare the same build flags. Ordinary identifiers and decimal integers with an optional sign are validated while finding their token boundary, avoiding a second scan. A numeric suffix falls back to the full R5RS number parser; an invalid identifier suffix is consumed through the atom's end so errors retain the complete spelling. Atom classification and numeric case folding operate directly on source bytes without allocating substring or lowercase copies. ### Reader and printer ```sh v -cc gcc -prod -o /tmp/vile-reader-bench bench/read.v /tmp/vile-reader-bench 65536 15 /tmp/vile-reader-bench 262144 9 ``` The reader benchmark measures parsing and printing separately, with a warm-up and median samples. Cases cover mixed code, flat lists/vectors, nested data, abbreviations, atoms, long symbols/strings and comments. It checks stable form, node and output-byte counts. `arena bytes` reports reserved node, vector and source-line buffers, excluding source text, top-level IDs, temporary scratch and allocator metadata. Corpus construction and file/terminal I/O are not timed. Additional cases cover short strings, comment lines, escaped strings and UTF-8 strings. Compare SIMD against the same scanner with its block paths disabled: ```sh v -cc gcc -prod -d vile_scalar -o /tmp/vile-reader-scalar bench/read.v /tmp/vile-reader-scalar 65536 15 ``` Reader regression tests include arena/scratch growth boundaries, initialized backward links, source positions checked against scanner spans, UTF-8/NUL output, independent documents and the existing nesting/error/round-trip cases. ### Allocation and GC ```sh v -cc gcc -prod -o /tmp/vile-memory-bench bench/memory /tmp/vile-memory-bench 65536 9 /tmp/vile-memory-bench 262144 9 quoted ``` With the default Boehm collector enabled, this reports mean allocated bytes for reading, printing and selected value decoding, plus collection counts across all samples. Allocation totals include allocator rounding; they are not live memory or RSS. Corpus construction, warm-up and the explicit collection before each case are excluded. Collection counts depend on heap state. The counter snapshot uses C-stack storage so profiling does not add measured heap allocations. ### Blip comparison ```sh v run bench/compare_blip.vsh v run bench/compare_blip.vsh 262144 9 ~/git/blip v run bench/compare_blip.vsh 65536 7 ~/git/blip --dev ``` The arguments are approximate bytes per case, samples, and the Blip checkout. Defaults are 65536 bytes, 7 samples, and `~/git/blip`. The launcher uses the V compiler running the script and GCC, builds one executable containing both implementations with `-prod` (or without it for `--dev`), and removes its temporary build directory afterward. It reads the Blip working tree without modifying it; no dependency installation is needed. Compiler version, flags, Blip path and HEAD are printed with the results. Each case uses the same source for all four paths, warms each once, then rotates their order across samples. Each call uses fresh scanner/result state. Timings include allocation and any GC during the call, and exclude build time, input generation, file I/O and output. Output counts and reader diagnostics are checked before accepting a measurement. Sample buffers have their final lengths from the start and are filled by index, then sorted in place. **The stages differ:** `vile-collect` retains a token array and owned spellings; `vile-stream` consumes token spans without retaining tokens or requesting text; `vile-read` builds a pair/vector arena with source-backed atoms; `blip-read` builds a datum arena and converts numeric values. Rows include stage names and token/node/form counts. This compares current front-end costs; it does not measure evaluation or claim equivalent work. Cases use shared syntax: long identifiers, bounded decimal integers, strings, comments, definitions and quoted lists. ## License Vile is licensed under the [GNU General Public License, version 3](LICENSE). The bundled [utf8proc](thirdparty/utf8proc/LICENSE.md), [libgrapheme](thirdparty/libgrapheme/LICENSE), [Unicode data](tools/unicode/data/LICENSE), and [Chibi Scheme test fixtures](scheme/testdata/CHIBI-COPYING) carry their respective upstream notices.