raz / commit a61882bd

commit
a61882bdd2bc3abd52fe63e0f8e5253fde91ec4e
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
7f0df936
sbcl: one interface to a module's files, report 2026-10.23, README

Each other file of a module is read for its declarations and must
export what the one taken does (section 3). Math's bits, fromBits and
mul. Frames pushed by moving *sp*, not binding it, so a deep recursion
doesn't fill SBCL's binding stack. A generic main module and a constant
index out of an array are errors. README: how it works, and this
implementation's choices (appendix A).

patch · log

7 files changed, +287 -12

sbcl/README.md (history) added +132 -0

@@ -0,0 +1,132 @@
1+# raz in SBCL
2+
3+A second compiler for raz, written in Common Lisp for SBCL from the
4+report alone: `doc/raz.md`, the language, and `doc/raz-lib.md`, the
5+library. It shares no code with the compiler in `src/`, and its library,
6+`lib/` here, is written afresh from volume 2. It follows report
7+2026-10.23 and passes the conformance suite, `conform/`: 301 of 301.
8+
9+ make # ./raz, from src/*.lisp (needs sbcl)
10+ make check # conform/, run from the directory above
11+ ./raz [-I dir]... [-o exe] [-S] file.raz
12+
13+`-S` also writes the Lisp it made to `exe.lisp`. With `RAZ_DEBUG` set
14+in the environment, a mistake of the compiler's own comes with a
15+backtrace.
16+
17+## How it works
18+
19+The compiler reads each module once, front to back, checking it and
20+turning it into Lisp as it goes. Each procedure becomes a `DEFUN`. At
21+the end the compiler compiles them with SBCL into its own image and
22+saves the image, program and all, as the executable, which starts at
23+`START` in `src/rt.lisp`.
24+
25+| File | What |
26+|---|---|
27+| `src/package.lisp` | the packages: `RAZ`, and `RAZP` for the program's procedures |
28+| `src/scan.lisp` | the scanner: UTF-8 checked, then tokens |
29+| `src/types.lisp` | types, their layout, and sameness (5.10) |
30+| `src/rt.lisp` | the run time the compiled code calls |
31+| `src/comp.lisp` | what the rest share: modules, names, items, frames, the data block |
32+| `src/expr.lisp` | expressions, conversions, built-ins and calls |
33+| `src/stmt.lisp` | statements |
34+| `src/decl.lisp` | declarations, procedures, modules and generic instances |
35+| `src/driver.lisp` | the command line, and the executable |
36+
37+**Memory.** Every raz variable lives at an address, as `ADR` needs.
38+The module variables, string literals, constant arrays and records,
39+and the errors' messages lie in one block, the data, mapped at
40+`200000000000H`, so that the compiler knows each of their addresses.
41+A procedure's parameters, variables and temporaries lie in its frame,
42+on a raz stack of 256 MB that each thread maps for itself; a frame is
43+zeroed as the procedure starts.
44+
45+**Values.** In Lisp an integer, a pointer, an `ERROR` or a set is an
46+integer, kept within its type's range; a `BOOL` is `T` or `NIL`; a
47+real a `DOUBLE-FLOAT` or `SINGLE-FLOAT`. An array, a record, a variant
48+or a slice is handled by its address. An `ERROR` is the address of a
49+slice of its message, so `MSG` reads it there. A procedure value is an
50+index into a table of the program's procedures; one given to C becomes
51+a C function made by SBCL, so C can call it back, from its own threads
52+too.
53+
54+**Results.** A procedure returns its results as Lisp's multiple values;
55+for each record, array, variant or slice among them the caller passes
56+the address of a place to put it.
57+
58+**Deferred statements** are copied, by the compiler, to each place
59+their statement list can be left: its end, and each `return`, `try`
60+and `break` that leaves it. Nothing about them is kept as the program
61+runs, and a stop, `Rt.exit` or `Sys.exit` runs none of them, as 7.7
62+wants.
63+
64+## This implementation's choices (appendix A)
65+
66+- **The target** is `linux-sbcl`: Linux, on the machine SBCL runs on.
67+ A module's files are looked for as `Name.linux-sbcl.raz`,
68+ `Name.linux.raz`, `Name.sbcl.raz` and `Name.raz`. An address, and
69+ so `INT`, is 8 bytes; reals are there; bytes are little-endian.
70+- **Separate compilation**: none. Every module of a program is
71+ compiled together, and no object file is written.
72+- **Atomics**: `CAS` is the machine's, through SBCL; `XCHG` and `XADD`
73+ loop on it.
74+- **The calling convention** is SBCL's for raz procedures, and C's
75+ (System V) where raz meets C, for `extern` procedures and callbacks.
76+- **Code procedures.** The target's machine is SBCL, so its assembly
77+ language is Lisp: each instruction, up to its `;`, is a Lisp form,
78+ read in the package `RAZ`, which sees the parameters by their names
79+ in capitals, and the value of the last is the result. A code
80+ procedure returns no record, array or slice. The library uses them
81+ for the few things only the run time can do (`Rt`'s end, `Math`,
82+ threads, signals). x86 code procedures aren't this target's.
83+- **`SYSCALL`** goes through the C library's `syscall()`, with
84+ x86-64's numbers. A program that makes the system calls SBCL itself
85+ relies on (signals' handlers, `clone`) is on its own.
86+- **`Out`'s buffer**, `Sys.outSize`, is 4 KB.
87+- **The executable** is an SBCL image, about 36 MB, which starts in a
88+ few milliseconds. It carries the names of the procedures, which a
89+ stop and `Rt.trace` print, but no line numbers for a debugger.
90+- **Failures.** A failed check, a division by zero and a `nil`
91+ procedure are checked by the compiled code; a `nil` pointer or a bad
92+ address is caught by SBCL; a stack overflow by either: past the raz
93+ stack, or past SBCL's own (256 MB). Each prints where it was, as far
94+ as it can tell, and the calls under way, without their variables,
95+ then runs `Rt.atExit`'s procedures and ends with status 2. SBCL may
96+ also say on standard error that it used a stack's guard page.
97+- **Messages.** One error is reported, as `file:line:col: what`, and
98+ the compiler stops with status 1. It gives no warnings, and takes
99+ `-Werror` and does nothing with it.
100+- **Every program uses C**, in that SBCL's run time is a C program. A
101+ module that says `link static` still must not be in a program with
102+ an `extern` or a `link` of a library, which the compiler reports.
103+
104+## The library
105+
106+`lib/` has every module of volume 2: the core (`Rt`, `Out`, `Mem`,
107+`Arena`, `Lock`, `Str`, `Buf`, and `Sys`) and the rest (`Heap`, `Fmt`,
108+`List`, `Map`, `Sort`, `Math`, `Files`, `Opt`, `Thread`, `C`,
109+`Bytes`), in raz, over `SYSCALL` and a few code procedures.
110+
111+- `Sys` makes Linux's system calls; `spawn` forks and runs the
112+ program; `catch` has SBCL's run time handle the signals and write
113+ each to a pipe, the fd it gives.
114+- `Thread` runs each thread as one of SBCL's, on a raz stack of its
115+ own; `Mutex` is a futex.
116+- `Heap` keeps eight free lists, of blocks of 16 to 2048 bytes, and
117+ gives a bigger block, or one aligned to more than 16 bytes, pages of
118+ its own. It refuses a negative size, and an alignment that isn't a
119+ power of 2 up to a page.
120+- `Bytes`: volume 2 names its procedures but not their parameters.
121+ Here they are `index(s, b)`, `last(s, b)` and `count(s, b)` for a
122+ byte `b: U8`, and `find(s, sub)`, each an `INT`, -1 for none.
123+
124+## Beyond conform/
125+
126+Of the reference compiler's own tests, `test/run` and `examples/`, all
127+pass whose expected output this target can give: the rest are x86
128+code procedures (`Asm`, `Atomic`, `Edge`, `Results`, `Simd`, `Single`,
129+`Cpu`) and a module only for `linux-x86_64` (`Target`). Of
130+`test/err`, it rejects every program the report makes an error; the
131+others are that compiler's own limits, its warnings under `-Werror`
132+and its assembler.

sbcl/build.lisp (history) modified +5 -1

@@ -15,7 +15,11 @@
1515 (let ((src (format nil "src/~a.lisp" f))
1616 (fasl (format nil "build/~a.fasl" f)))
1717 (ensure-directories-exist fasl)
18- (load (compile-file src :output-file (merge-pathnames fasl))))))))
18+ (multiple-value-bind (out warnings failure) (compile-file src :output-file (merge-pathnames fasl))
19+ (declare (ignore warnings))
20+ ;; an error or a full warning in the compiler stops the build
21+ (when failure (format t "~a doesn't compile~%" src) (sb-ext:exit :code 1))
22+ (load out)))))))
1923
2024 (sb-ext:save-lisp-and-die "raz" :executable t :toplevel (intern "MAIN" :raz)
2125 :save-runtime-options t)

sbcl/lib/Math.raz (history) modified +27 -0

@@ -90,4 +90,31 @@
9090 (c-call "atan2" double-float double-float y double-float x);
9191 end;
9292
93+(* the bits of x, as IEEE 754 lays them out *)
94+proc bits*(x: F64): U64;
95+begin
96+ return ^U64(ADR(x))^;
97+end;
98+
99+(* the F64 whose bits are u *)
100+proc fromBits*(u: U64): F64;
101+begin
102+ return ^F64(ADR(u))^;
103+end;
104+
105+(* a times b: the low 64 bits of the product, and the high *)
106+proc mul*(a, b: U64): (U64, U64);
107+var al, ah, bl, bh, lo, mid1, mid2, hi, carry: U64;
108+begin
109+ (* by halves of 32 bits, as on paper *)
110+ al := a & 0FFFFFFFFH; ah := a shr 32;
111+ bl := b & 0FFFFFFFFH; bh := b shr 32;
112+ lo := al * bl;
113+ mid1 := ah * bl;
114+ mid2 := al * bh;
115+ hi := ah * bh;
116+ carry := ((lo shr 32) + (mid1 & 0FFFFFFFFH) + (mid2 & 0FFFFFFFFH)) shr 32;
117+ return a * b, hi + (mid1 shr 32) + (mid2 shr 32) + carry;
118+end;
119+
93120 end Math.

sbcl/src/decl.lisp (history) modified +111 -6

@@ -121,7 +121,7 @@
121121 :exported *type-exported* :module *module*)))
122122
123123 (defun variant-type ()
124- (let ((cases '()) (ty (make-ty :kind :variant)))
124+ (let ((cases '()) (toks '()))
125125 (loop until (accept :end)
126126 do (let* ((tk (tok)) (name (ident)) (fields '()))
127127 (when (accept :|(|)
@@ -130,10 +130,11 @@
130130 (when (find name cases :key #'vcase-name :test #'string=)
131131 (fail-tok tk "the case ~a is declared twice" name))
132132 (setf cases (append cases (list (make-vcase :name name :index (length cases) :fields fields))))
133- (push tk (ty-names ty)))
133+ (push tk toks))
134134 (expect :|;|))
135+ ;; the cases are named in the scope around the type (5.6)
135136 (let ((v (make-variant-type cases *module*)))
136- (loop for c in cases for tk in (reverse (ty-names ty))
137+ (loop for c in cases for tk in (reverse toks)
137138 do (declare-member (vcase-name c) :case v c tk))
138139 v)))
139140
@@ -305,6 +306,7 @@
305306 (cond ((accept :forward)
306307 (when (eq obj old) (fail-tok tk "~a is declared forward twice" name))
307308 (setf (obj-forward obj) t))
309+ (*interface-only* (skip-body) (setf (obj-defined obj) t))
308310 ((eq (kind) :code) (next-tok) (code-procedure obj))
309311 (t (procedure-body obj)
310312 (setf (obj-defined obj) t)))
@@ -314,6 +316,19 @@
314316 (next-tok))
315317 (expect :|;|))))
316318
319+(defun skip-body ()
320+ "Reads past a procedure's body unchecked, for a file read only for its
321+interface: its local declarations and statements, or its code."
322+ (if (accept :code)
323+ (expect :end)
324+ (let ((depth 0))
325+ (loop (let ((k (kind)))
326+ (next-tok)
327+ (case k
328+ ((:begin :if :while :for :match :record :variant) (incf depth))
329+ (:end (when (= (decf depth) 0) (return)))
330+ (:eof (fail-here "the procedure never ends"))))))))
331+
317332 (defun procedure-body (obj)
318333 "Compiles a procedure's declarations and statements into a DEFUN."
319334 (let* ((sig (obj-sig obj))
@@ -342,12 +357,18 @@
342357 (reverse stores) body (zeros-form (sig-results sig)))))))
343358
344359 (defun procedure-defun (sym params dests stores body end)
360+ ;; The frame is pushed by moving *SP*, and popped by moving it back as
361+ ;; the procedure returns, by RETURN-FROM or by its end. (Binding *SP*
362+ ;; with LET would be simpler, but each binding takes room on SBCL's
363+ ;; binding stack, which a deep recursion soon fills.)
345364 `(defun ,sym (,@params ,@dests)
346- (let* ((fp *sp*) (*sp* (+ fp ,(proc-size *proc*))))
365+ (let ((fp *sp*))
347366 (declare (ignorable fp))
348367 (enter fp ,(proc-size *proc*))
368+ (setf *sp* (+ fp ,(proc-size *proc*)))
349369 ,@stores
350- (block ,(proc-block *proc*) ,@body ,end))))
370+ (multiple-value-prog1 (block ,(proc-block *proc*) ,@body ,end)
371+ (setf *sp* fp)))))
351372
352373 (defun code-procedure (obj)
353374 "A code procedure (section 8). This implementation's target is SBCL's
@@ -406,6 +427,7 @@
406427 ;;; Modules (section 3).
407428
408429 (defvar *search-dirs* '() "Where modules are looked for, in order.")
430+(defvar *interface-only* nil "Whether the module being read is another target's file, read for its interface.")
409431 (defvar *target-names* '("linux-sbcl" "linux" "sbcl"))
410432
411433 (defun find-module-file (name tk)
@@ -434,7 +456,7 @@
434456 (setf (gethash name *modules*) m)
435457 (if (and (eq (tok-kind (aref toks 2)) :|(|))
436458 (read-generic-header m)
437- (read-module m))))
459+ (progn (read-module m) (check-other-files m)))))
438460 ((eq (module-state m) :compiling)
439461 (fail-tok tk "the module ~a imports itself" name)))
440462 m))
@@ -495,6 +517,7 @@
495517 (next-tok) (expect :|;|)
496518 (setf (module-check-off m) t))
497519 (declarations)
520+ (when *interface-only* (return-from read-module m))
498521 (when (eq (kind) :begin)
499522 (next-tok)
500523 (let* ((sym (lisp-name "(body)"))
@@ -601,3 +624,85 @@
601624 (fail-tok tk "~a's signature isn't the parameter ~a's" (obj-name actual) name))
602625 (setf (gethash name (scope-table *scope*)) actual)))))
603626 (expect :|)|)))
627+
628+;;; One interface to a module's files (section 3): each file of the
629+;;; module beside the one taken, Name.*.raz and Name.raz, is read for its
630+;;; declarations alone, and must export what the one taken does.
631+
632+(defun other-files (m)
633+ (let* ((file (module-file m)) (dir (directory-namestring file)))
634+ (remove-if (lambda (f) (equal (namestring f) file))
635+ (append (directory (format nil "~a~a.*.raz" dir (module-name m)))
636+ (directory (format nil "~a~a.raz" dir (module-name m)))))))
637+
638+(defun check-other-files (m)
639+ (loop for f in (other-files m) for i from 1
640+ do (let* ((file (namestring f))
641+ (other (make-module :name (module-name m) :file file
642+ :toks (let ((*file* file)) (scan (read-bytes file)))
643+ :lisp-name (format nil "~a{~d}" (module-name m) i))))
644+ (let ((*interface-only* t)) (read-module other))
645+ (compare-interfaces m other))))
646+
647+(defun iface-type-p (a b)
648+ "Whether types A and B, of two files of one module, are built alike, a
649+name in one standing for the same name in the other."
650+ (cond ((eq a b) t)
651+ ((or (ty-name a) (ty-name b))
652+ (and (ty-name a) (ty-name b) (string= (ty-name a) (ty-name b))
653+ (eq (ty-kind a) (ty-kind b))))
654+ ((not (eq (ty-kind a) (ty-kind b))) nil)
655+ (t (case (ty-kind a)
656+ (:ptr (and (eq (ty-vol a) (ty-vol b)) (iface-type-p (ptr-base a) (ptr-base b))))
657+ (:array (and (= (ty-len a) (ty-len b)) (iface-type-p (ty-elem a) (ty-elem b))))
658+ (:slice (iface-type-p (ty-elem a) (ty-elem b)))
659+ (:set (iface-type-p (ty-enum a) (ty-enum b)))
660+ (:proc (iface-sig-p (ty-sig a) (ty-sig b)))
661+ (t (iface-shape-p a b))))))
662+
663+(defun iface-fields-p (as bs)
664+ "The exported fields of two records, or the fields of two cases, alike."
665+ (and (= (length as) (length bs))
666+ (every (lambda (f g) (and (string= (field-name f) (field-name g))
667+ (iface-type-p (field-type f) (field-type g))))
668+ as bs)))
669+
670+(defun iface-shape-p (a b)
671+ "What a record, variant or enumeration shows another module, alike:
672+its exported fields, its cases, its names."
673+ (ecase (ty-kind a)
674+ (:record (iface-fields-p (remove-if-not #'field-exported (ty-fields a))
675+ (remove-if-not #'field-exported (ty-fields b))))
676+ (:variant (and (= (length (ty-cases a)) (length (ty-cases b)))
677+ (every (lambda (c d) (and (string= (vcase-name c) (vcase-name d))
678+ (iface-fields-p (vcase-fields c) (vcase-fields d))))
679+ (ty-cases a) (ty-cases b))))
680+ (:enum (equal (ty-names a) (ty-names b)))
681+ ((:int :bool :real :error) t)))
682+
683+(defun iface-sig-p (a b)
684+ (and (= (length (sig-params a)) (length (sig-params b)))
685+ (= (length (sig-results a)) (length (sig-results b)))
686+ (eq (sig-varargs a) (sig-varargs b))
687+ (every (lambda (p q) (and (eq (third p) (third q)) (iface-type-p (second p) (second q))))
688+ (sig-params a) (sig-params b))
689+ (every #'iface-type-p (sig-results a) (sig-results b))))
690+
691+(defun compare-interfaces (m other)
692+ (flet ((differ (name file)
693+ (error 'raz-error :text (format nil "~a: ~a isn't exported as in ~a" file name (module-file m)))))
694+ (maphash (lambda (name o)
695+ (let ((p (gethash name (module-exports other))))
696+ (unless (and p (eq (obj-kind o) (obj-kind p))
697+ (ecase (obj-kind o)
698+ ((:const :var :case) (iface-type-p (obj-type o) (obj-type p)))
699+ (:type (and (eq (ty-kind (obj-type o)) (ty-kind (obj-type p)))
700+ (if (member (ty-kind (obj-type o)) '(:record :variant :enum))
701+ (iface-shape-p (obj-type o) (obj-type p))
702+ (iface-type-p (obj-type o) (obj-type p)))))
703+ (:proc (iface-sig-p (obj-sig o) (obj-sig p)))))
704+ (differ name (module-file other)))))
705+ (module-exports m))
706+ (maphash (lambda (name p) (declare (ignore p))
707+ (unless (gethash name (module-exports m)) (differ name (module-file other))))
708+ (module-exports other))))

sbcl/src/driver.lisp (history) modified +4 -1

@@ -11,7 +11,7 @@
1111
1212 (in-package :raz)
1313
14-(defparameter *version* "raz-sbcl 0.1.0, report 2026-10.22")
14+(defparameter *version* "raz-sbcl 0.1.0, report 2026-10.23")
1515
1616 (defun body-order (roots)
1717 "The modules whose bodies run, in order (section 3): each after those
@@ -78,6 +78,9 @@
7878 (let* ((none (make-tok :eof nil 1 1))
7979 (main (progn (load-module "Rt" none) (load-module name none (namestring path))))
8080 (modules (all-modules)))
81+ (when (module-generic main)
82+ (error 'raz-error :text (format nil "~a: ~a is generic: it is compiled where a module imports it"
83+ file name)))
8184 (when (and (some #'module-static modules) (some #'module-uses-c modules))
8285 (error 'raz-error
8386 :text (format nil "~a: the program uses C (~{~a~^, ~}), which ~{~a~^, ~} doesn't allow by link static"

sbcl/src/expr.lisp (history) modified +3 -1

@@ -343,7 +343,6 @@
343343 ((untyped-p x) (takes x b) b)
344344 ((untyped-p y) (takes y a) a)
345345 ((same-type-p a b) a)
346- ((and (is a :literal) nil))
347346 (t (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b)))))))
348347
349348 (defun typed-const (item ty)
@@ -654,6 +653,9 @@
654653 (+ (ld :u64 ,base)
655654 (* ,(if check `(check-index ,lo (ld :i64 (+ ,base 8)) ,(where tk)) lo)
656655 ,size))))
656+ ((and (integerp lo) (not (< -1 lo len-form)))
657+ ;; a constant index out of an array would stop the program
658+ (fail-tok tk "index ~d is out of range for a length of ~d" lo len-form))
657659 (t `(+ ,base-form (* ,(if check `(check-index ,lo ,len-form ,(where tk)) lo) ,size))))
658660 :ro (if (is ty :array) (item-ro item) nil)
659661 :vol (and (is ty :array) (item-vol item))

sbcl/src/rt.lisp (history) modified +5 -3

@@ -271,16 +271,18 @@
271271 (write-bytes 2 (sb-ext:string-to-octets (format nil " in ~a~%" name)))))
272272
273273 (defmacro catching-faults (&body body)
274- "BODY, where a bad address or an exhausted stack stops the program."
275- `(let ((where nil))
274+ "BODY, where a bad address or an exhausted stack stops the program,
275+from the bottom of the raz stack, where there is room to stop."
276+ `(let ((where nil) (base *sp*))
276277 (handler-case
277278 (handler-bind ((sb-sys:memory-fault-error
278279 (lambda (c) (declare (ignore c)) (setf where (first (raz-frames))))))
279280 ,@body)
280281 (sb-sys:memory-fault-error (c)
282+ (setf *sp* base)
281283 (stop (format nil "in ~a: a nil pointer or a bad address (0x~(~x~))" where
282284 (fault-address c))))
283- ((or storage-condition stack-overflow) () (stop "a stack overflow")))))
285+ ((or storage-condition stack-overflow) () (setf *sp* base) (stop "a stack overflow")))))
284286
285287 (defun fault-address (c)
286288 (let ((a (ignore-errors (slot-value c 'sb-kernel::address))))