Skip to content
menezesdPublic

About

Scheme interpreter in C

Topics

Resources

Stars

17 stars

Watchers

2 watching

Forks

Latest commit

Β 

History

195 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Vesper

A compact R5RS-inspired Scheme interpreter written in C, featuring a bytecode compiler, generational copying garbage collector, hygienic macros, and full numeric tower. Where the standards leave room, behavior follows MIT/GNU Scheme, which make test-diff checks it against.

Features

  • Bytecode Compiler: Compiles to bytecode for a stack-based VM with peephole optimization
  • Garbage Collection: Generational copying collector: a nursery promoted into Cheney semispaces
  • Tail Call Optimization: Proper tail calls in both interpreter and VM
  • R5RS Compliance: Passes standard compliance tests including tricky edge cases
  • Numeric Tower: Integers, bignums, rationals, floats, and complex numbers
  • Hygienic Macros: Full syntax-rules with referential transparency, and MIT's procedural er-macro-transformer, rsc-macro-transformer and sc-macro-transformer (with close-syntax, make-syntactic-closure, identifier? and identifier=?)
  • First-Class Continuations: Full call/cc with multi-shot continuation support
  • SRFI Support: SRFI-1 (lists), SRFI-2 (and-let*), SRFI-8 (receive), SRFI-9 (records), SRFI-26 (cut/cute), SRFI-27 (random bits), SRFI-28 (format)
  • Ports: File I/O, string ports, and bytevector ports with standard Scheme port operations
  • Unicode Strings: UTF-8 strings with table-driven normalization, case folding, and character predicates from Unicode 15.1

Building

make          # Build the interpreter
make debug    # Build with debug symbols
make sanitize # Build with AddressSanitizer/UBSan
make ubsan    # Build with UBSan only
make test     # Run the Scheme test suite (test.scm) on the bytecode VM
make test-interpreter # Run the same suite on the CPS interpreter
make test-c   # Run the C unit tests
make test-prop # Run the property tests (property_tests.scm)
make test-numeric-oracle # Check exact arithmetic, float rounding, and complex radices in both engines
make test-port-readiness # Check nonblocking UTF-8 reads on a blocking pipe in both engines
make test-r5rs # Run the R5RS conformance tests in both engines
make test-stress # Run the stress tests (stress_tests.scm)
make test-repl-exit # Check REPL exit codes and input handling in both engines
make test-backtrace # Check the backtraces of unhandled errors in both engines
make test-lineedit # Drive the REPL's line editor through a pseudo-terminal
make test-fuzz # Differential fuzzing: random programs must print the same in both engines
make lint     # GC-safety lint of the C sources (tools/lint_gc.py)
make test-gcstress # Run a workload under forced collections in both engines
make test-diff # Compare semantic probes, in both engines, against MIT Scheme (skipped without mit-scheme)
make test-sanitize # Run bounded AddressSanitizer/UBSan smoke tests
make test-ubsan # Run bounded UBSan-only smoke tests
make test-all # Run every test target above except test-sanitize
make clean    # Remove build artifacts
make unicode-tables # Download the Unicode 15.1 data files and regenerate the tables

Debugging aids

VESPER_GC_STRESS=N forces a minor collection every N allocations instead of waiting for the 256K-cell nursery to fill. A reference that was never rooted otherwise survives almost every run and fails only when a collection happens to land on the wrong allocation, which makes rooting bugs look like flaky, layout-dependent failures. Small values are slow but deterministic:

VESPER_GC_STRESS=1000 ./vesper myprogram.scm

VESPER_GC_STRESS_MAJOR=N does the same for full collections. Minor GC only touches the nursery, so on its own it barely exercises the semispace flip, promotion, or the card-table scan for old-to-young pointers.

make test-gcstress runs a small workload at several intervals in both engines, and is part of make test-all.

The collectors free the malloc'd payloads of dead strings, vectors, bignums, ports and the like from lists of the cells that own one, rather than by visiting every dead cell, so each constructor of such a cell must call gc_note_external. VESPER_GC_VERIFY=1 checks those lists against a walk of the heap at every collection and aborts on a cell that was never noted; it combines with the stress settings above.

Building with -DVESPER_GC_TRAP_FREE_CELLS additionally aborts the moment a reclaimed cell is dereferenced, which points at the stale read rather than the corruption it causes later. It is compile-time because car/cdr are the hottest functions in the interpreter.

On some Apple Clang/macOS combinations, ASan can hang before main while the sanitizer runtime initializes shadow memory. make test-sanitize reports that case as a bounded skip; make test-ubsan still provides runtime undefined behavior checks on those systems.

Requirements

  • GCC or Clang with C11 support
  • GNU Make
  • Standard C library with math support (-lm)

Usage

Interactive REPL

./vesper
]=> (+ 1 2 3)

;Value: 6
]=> (define (factorial n)
      (if (= n 0) 1 (* n (factorial (- n 1)))))

;Value: factorial
]=> (factorial 50)

;Value: 30414093201713378043612608166064768844377641568960512000000000000

On a terminal the REPL has line editing: arrow keys, Home/End, Delete, the emacs keys (Ctrl-A/E/B/F/K/U/W/Y/T/D/L, Alt-B/F), and history on Up/Down, kept in ~/.vesper_history (set VESPER_HISTORY to another file, or to nothing to keep no history). Enter on an entry whose parentheses, string or #| |# comment is still open starts a continuation line (... ), so a multi-line definition is edited and recalled as one entry. Ctrl-C abandons the entry, Ctrl-D on an empty one ends the session. The editor only runs when both stdin and stdout are terminals; otherwise input is read exactly as typed.

With input piped rather than typed, the exit status is 1 if any top-level form signalled an error, as when running a script.

Running Scripts

./vesper script.scm

Vesper normally loads its embedded standard library. For development, an external standard library can be selected explicitly:

./vesper --stdlib ./stdlib.scm script.scm

Interpreter Mode

By default, Vesper uses its bytecode compiler. For the tree-walking CPS interpreter (useful for debugging), use:

./vesper --interpreter script.scm

Errors and Debugging

An error that no handler takes is reported as Unhandled exception: ..., followed by a backtrace, innermost call first, with each procedure named by its definition and source line; repeated frames of one procedure are folded into one line:

Unhandled exception: car: not a pair
  in (fact n) at fact.scm:1
  ... 3 more frames in (fact n)
  in <top-level> at fact.scm:2

Proper tail calls leave no frame behind, and the interpreter reconstructs its frames from the continuation, so its backtraces can be shorter. An error that a guard or with-exception-handler catches prints nothing. Reading a letrec, letrec*, named-let or internal-definition variable before its initializer has run is the error Unassigned variable: NAME, as in MIT Scheme.

Procedures print as MIT's do: #[compound-procedure 12 fact], #[compound-procedure 13] for an anonymous one, #[compiled-procedure 17 ("car") car] for a built-in, #[continuation 14]. MIT's debugging aids are available: pp pretty-prints data, (trace fact) and untrace (also trace-entry, trace-exit) report each call and return, procedure-arity returns (min . max) with #f for no maximum, and runtime, real-time and with-timings time a computation.

Language Features

Special Forms

define    lambda    if        cond      case
let       let*      letrec    begin     and
or        quote     quasiquote set!     do
delay     define-syntax        syntax-rules

Numeric Types

; Integers (arbitrary precision)
(factorial 100)

; Rationals (exact)
(/ 1 3)           ; => 1/3
(+ 1/2 1/3)       ; => 5/6

; Floating point (inexact)
(sqrt 2)          ; => 1.4142135623730951
(sin 3.14159)     ; => 2.65358979335273e-06

; Complex numbers
(sqrt -1)         ; => +i
(+ 1+2i 3+4i)     ; => 4+6i

Data Structures

; Lists
(list 1 2 3)      ; => (1 2 3)
(cons 'a '(b c))  ; => (a b c)

; Vectors
#(1 2 3)          ; => #(1 2 3)
(vector-ref #(a b c) 1)  ; => b

; Strings
"hello world"
(string-append "foo" "bar")  ; => "foobar"
(string-length "πŸ˜‰test")     ; => 5
(string-normalize-nfc "é")  ; => "é"
(string-foldcase "Straße")   ; => "strasse"

; Characters
#\a #\space #\newline

String length, indexing, slicing, and mapping operate on Unicode scalar values encoded as UTF-8. Normalization (string-normalize-nfc, string-normalize-nfd, string-normalize-nfkc, string-normalize-nfkd) and case folding are table-driven from Unicode 15.1. Ordering predicates such as string<? compare encoded/codepoint order; they are not locale-sensitive collation.

Higher-Order Functions

(map (lambda (x) (* x x)) '(1 2 3 4 5))
; => (1 4 9 16 25)

(filter odd? '(1 2 3 4 5))
; => (1 3 5)

(fold + 0 '(1 2 3 4 5))
; => 15

Macros

Full hygienic macro support with syntax-rules:

(define-syntax when
  (syntax-rules ()
    ((when test body ...)
     (if test (begin body ...)))))

(define-syntax unless
  (syntax-rules ()
    ((unless test body ...)
     (if (not test) (begin body ...)))))

The macro system implements mark-based hygiene to handle complex cases like nested macros with shadowing:

;; Nested macro hygiene - x in bar's template refers to outer x, not inner
(let ((x 1))
  (let-syntax
      ((foo (syntax-rules ()
              ((_ y) (let-syntax
                           ((bar (syntax-rules ()
                                 ((_) (let ((x 2)) y)))))
                       (bar))))))
    (foo x)))  ; => 1 (correctly returns outer x)

;; Referential transparency - + refers to definition-time binding
(let-syntax ((foo (syntax-rules ()
                    ((_ expr) (+ expr 1)))))
  (let ((+ *))
    (foo 3)))  ; => 4 (uses + from definition, not shadowed *)

Records (SRFI-9)

(define-record-type point
  (make-point x y)
  point?
  (x point-x point-set-x!)
  (y point-y))

(define p (make-point 3 4))
(point-x p)        ; => 3
(point-set-x! p 5)
(point-x p)        ; => 5
p                  ; => #[point 12]
(vector? p)        ; => #f
point              ; => #[record-type 13 point]

Records are a type of their own, as R7RS requires: no vector operation accepts one, and equal? compares them by identity. As in MIT Scheme, the type name is bound to the record type, instances print as #[point 12] (the number is the object's hash, assigned when it is first printed), and MIT's procedural interface is available: record?, record-type-descriptor, record-type-name, record-type-field-names, make-record-type, record-constructor, record-predicate, record-accessor and record-modifier. The runtime's other opaque objects - error objects (conditions), promises, character sets and bytevector ports - are records too, printed like MIT's: #[condition 7 simple-error], #[promise 8 (evaluated) 5], #[char-set 9], #[binary-input-port 10].

Partial Application (SRFI-26)

;; cut - slots filled at call time
(define add1 (cut + <> 1))
(add1 5)  ; => 6

(define list-1-x-3 (cut list 1 <> 3))
(list-1-x-3 2)  ; => (1 2 3)

;; cute - non-slot expressions evaluated at definition time
(define counter 0)
(define cute-fn (cute cons (begin (set! counter (+ counter 1)) counter) <>))
counter     ; => 1 (evaluated once at definition)
(cute-fn 'a)  ; => (1 . a)
(cute-fn 'b)  ; => (1 . b) (still 1, not re-evaluated)

Ports and I/O

; File I/O
(call-with-input-file "data.txt"
  (lambda (port)
    (read port)))

; String ports
(call-with-output-string
  (lambda (port)
    (display "hello" port)
    (newline port)))
; => "hello\n"

Continuations

(call-with-current-continuation
  (lambda (k)
    (+ 1 (k 42))))
; => 42

Architecture

File Structure

File Description
main.c Entry point, REPL, file loading
lineedit.c/h Line editor for the interactive REPL (raw-mode termios, history)
compile.c, compile_internal.h Bytecode compiler with constant folding
optimize.c Peephole optimizer and bytecode disassembler
code_object.c Code objects and their garbage collection
vm.c Stack-based virtual machine
bytecode.h Opcode definitions and VM structures
types.h Core type definitions, cell structure
context.c/h Memory management, GC, cell allocation
reader.c/h S-expression parser, tokenizer
writer.c/h S-expression printer with cycle detection
eval.c/h, eval_forms.c, eval_cont.c CPS interpreter (--interpreter)
env.c/h Environment frames, variable binding
primitives.c/h, prim_*.c Built-in procedures (over 250 primitives)
primitive_table.c/h One entry per primitive: bound name, arity (checked before dispatch), flags
macros.c/h, compiled_pattern.c/h Hygienic macro expander, compiled syntax-rules patterns
utf8.c/h UTF-8 decoding, encoding and string indexing
bignum.c/h Arbitrary precision integer arithmetic
feature_table.c/h cond-expand / (features) identifiers
stdlib.scm Standard library (Scheme code), embedded via the generated stdlib_data.h
unicode_*.h Unicode tables and test fixtures generated by tools/gen_unicode_*.py
tools/ MIT differential runner, differential fuzzer, GC-safety lint, line-editor pty test, sanitizer smoke tests, Unicode table generators

Memory Model

The interpreter uses a generational copying garbage collector:

  • Nursery: New cells are allocated in a 256K-cell nursery; a minor collection copies its survivors into the old generation, with a card table recording old-to-young pointers
  • Old Generation: Two semispaces, collected by Cheney copying on a major collection
  • Cells: 12-byte packed structs: a type tag plus a car/cdr pair, a 64-bit value, or a pointer to external data (strings, vectors, bignums, ports)
  • Reserved Space: Cells 0-272 (reader tokens, nil, booleans, permanent atoms, the integer cache 0-255, the end-of-file object)

Bytecode VM

The default execution mode compiles Scheme to bytecode:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Parse   │───>β”‚ Compile  │───>β”‚ Execute  β”‚
β”‚ (reader) β”‚    β”‚(bytecode)β”‚    β”‚   (VM)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key optimizations:

  • Peephole optimization (fused compare-and-jump, etc.)
  • Specialized opcodes for common operations (car, cdr, +, -, etc.), guarded so that redefining the primitive's name still takes effect
  • Constant folding for pure operations
  • Inline caches for variable lookup, and side indexes for large frames
  • Parameters kept on the VM stack when no closure can capture them
  • Fixnum arithmetic and comparisons quickened in place on first use
  • Tail call optimization via dedicated TAILCALL opcode, and loops for recursion in tail position modulo cons/append

Type System

Each cell carries an enum lisp_type tag (types.h). The main ones:

Type Description
BT_ATOM Interned symbol
BT_NUM Exact integer (64-bit)
BT_BIGNUM Arbitrary precision integer
BT_RATIONAL Exact rational (num/denom)
BT_INEXACT IEEE 754 double
BT_COMPLEX Complex number (real/imag)
BT_CHAR Unicode character
BT_STRING String (UTF-8)
BT_CONS Pair (car/cdr)
BT_VECTOR Fixed-size array
BT_BYTEVEC Bytevector
BT_HASHTABLE Hash table
BT_INPORT, BT_OUTPORT, BT_STRINPORT, BT_STROUTPORT Ports
BT_FUNCTION Interpreter closure
BT_BUILTIN Built-in procedure
BT_SYNTAX syntax-rules transformer
BT_CONT Interpreter continuation
BT_VMCLOSURE VM closure: a BT_CLOSURE code cell and an environment
BT_VMCONT VM continuation

Inside the VM, integers that fit in 31 bits travel as tagged immediates (fixnums) rather than cells, and are boxed when they leave it.

Testing

Scheme Test Suite

make test

Runs test.scm which exercises all language features including arithmetic, list operations, macros, continuations, and the standard library; make test-interpreter runs it on the CPS interpreter. r5rs_tests.scm, property_tests.scm, stress_tests.scm and gc_stress_tests.scm have targets of their own (see Building), and make test-all runs them all.

C Unit Tests

make test-c

Runs eight test suites:

  • test_bignum - Arbitrary precision arithmetic
  • test_reader - S-expression parsing and printing
  • test_context - Memory management, GC, environments and VM edge cases
  • test_macros - Macro expansion
  • test_eval - Both evaluators, the compiler and the VM
  • test_pattern - Compiled syntax-rules patterns
  • test_unicode_norm - Normalization against Unicode's NormalizationTest.txt
  • test_unicode_case - Case mapping and character properties

Configuration

Key constants in types.h:

#define SEMISPACE_SIZE (16384 * 1024) // 16M cells per semispace
#define NURSERY_SIZE (256 * 1024)     // Cells in the nursery
#define HEAP_RESERVED 273             // Reserved cells (0-272)
#define INITIAL_STRING_CAP 32         // Initial string buffer size

License

MIT

References

About

Scheme interpreter in C

Topics

Resources

Stars

17 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages