From cfa2bc209037fe14277d21062e9cc1e3472f89a5 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Wed, 14 Oct 2026 12:58:24 +0100 Subject: [PATCH] sbcl: a second raz compiler, in SBCL, from the report alone It turns each module into Lisp over raw memory and saves an SBCL image with the program as the executable. Its library, in sbcl/lib, is written from volume 2: Rt, Sys, Out, Lock, Mem, Str and C so far. conform/ passes: 301 of 301. --- diff --git a/sbcl/.gitignore b/sbcl/.gitignore new file mode 100644 index 0000000..50f1bdc --- /dev/null +++ b/sbcl/.gitignore @@ -0,0 +1,2 @@ +raz +build/ diff --git a/sbcl/Makefile b/sbcl/Makefile new file mode 100644 index 0000000..69a9897 --- /dev/null +++ b/sbcl/Makefile @@ -0,0 +1,15 @@ +# The raz compiler in SBCL. `make` builds ./raz; `make check` runs the +# conformance suite, conform/, of the repository above. + +SBCL = sbcl --control-stack-size 256MB --dynamic-space-size 4GB + +raz: build.lisp src/*.lisp + $(SBCL) --script build.lisp + +check: raz + cd .. && sh conform/check.sh sbcl/raz + +clean: + rm -rf raz build + +.PHONY: check clean diff --git a/sbcl/build.lisp b/sbcl/build.lisp new file mode 100644 index 0000000..51aa99c --- /dev/null +++ b/sbcl/build.lisp @@ -0,0 +1,21 @@ +;;;; build.lisp -- builds the compiler: `sbcl --script build.lisp` writes +;;;; ./raz, an SBCL image holding the compiler, which it saves again, with +;;;; the program added, as each executable it makes. + +(require :sb-introspect) + +(defparameter *sources* '("package" "scan" "types" "rt" "comp" "expr" "stmt" "decl" "driver")) + +(let ((*compile-verbose* nil) (*compile-print* nil)) + (handler-bind ((warning (lambda (w) + ;; style warnings about the order of definitions are no matter + (when (typep w 'style-warning) (muffle-warning w))))) + (with-compilation-unit () + (dolist (f *sources*) + (let ((src (format nil "src/~a.lisp" f)) + (fasl (format nil "build/~a.fasl" f))) + (ensure-directories-exist fasl) + (load (compile-file src :output-file (merge-pathnames fasl)))))))) + +(sb-ext:save-lisp-and-die "raz" :executable t :toplevel (intern "MAIN" :raz) + :save-runtime-options t) diff --git a/sbcl/lib/C.raz b/sbcl/lib/C.raz new file mode 100644 index 0000000..013db9d --- /dev/null +++ b/sbcl/lib/C.raz @@ -0,0 +1,14 @@ +(* The parts of the C library that programs use most: printf, fflush, + stdout and pthread_create. A program that imports C uses C. *) +module C; + +extern var stdout*: ^U8; (* C's FILE *stdout *) + +extern proc printf*(format: ^U8; ...): I32; +extern proc fflush*(f: ^U8): I32; +extern proc malloc*(size: UINT): ^U8; +extern proc free*(p: ^U8); +extern proc pthread_create*(thread: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32; +extern proc pthread_join*(thread: UINT; result: ^^U8): I32; + +end C. diff --git a/sbcl/lib/Lock.raz b/sbcl/lib/Lock.raz new file mode 100644 index 0000000..a93ae29 --- /dev/null +++ b/sbcl/lib/Lock.raz @@ -0,0 +1,22 @@ +(* A lock for short sections: a thread that finds it taken tries again, + giving up the processor now and then. Zero is free. *) +module Lock; +import Sys; + +type Lock* = record held: INT; end; + +proc take*(l: ^Lock); +var tries: INT; +begin + while not CAS(ADR(l^.held), 0, 1) do + INC(tries); + if tries mod 64 = 0 then Sys.yield; end; + end; +end; + +proc give*(l: ^Lock); +begin + _ := XCHG(ADR(l^.held), 0); +end; + +end Lock. diff --git a/sbcl/lib/Mem.raz b/sbcl/lib/Mem.raz new file mode 100644 index 0000000..87f5b18 --- /dev/null +++ b/sbcl/lib/Mem.raz @@ -0,0 +1,35 @@ +(* Allocator, the interface of every allocator, and pages from the system. *) +module Mem; +import Sys; + +type + Allocator* = record + alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *) + free*: proc(a: ^Allocator; p: ^U8); + end; + +const Page* = 4096; + +(* size bytes, in whole pages, zeroed; or nil *) +proc pages*(size: INT): ^U8; +begin + return Sys.mmap(size); +end; + +(* pages given back *) +proc unmap*(p: ^U8; size: INT); +begin + Sys.munmap(p, size); +end; + +proc alloc*(a: ^Allocator; size, align: INT): ^U8; +begin + return a^.alloc(a, size, align); +end; + +proc free*(a: ^Allocator; p: ^U8); +begin + a^.free(a, p); +end; + +end Mem. diff --git a/sbcl/lib/Out.raz b/sbcl/lib/Out.raz new file mode 100644 index 0000000..6be921b --- /dev/null +++ b/sbcl/lib/Out.raz @@ -0,0 +1,108 @@ +(* Writing text and numbers to standard output, buffered: written out when + the buffer is full, at each line feed when standard output is a + terminal, at flush, and when the program ends by Rt.exit. A lock keeps + what each call writes together. *) +module Out; +import Sys, Rt, Lock; + +const hexDigits = "0123456789ABCDEF"; + +var + buf: [Sys.outSize]U8; + len: INT; + lock: Lock.Lock; + terminal: BOOL; + +(* The buffer written out; the lock is held. *) +proc drain; +var n, done: INT; +begin + while done < len do + n := Sys.write(Sys.stdout, buf[done..len]); + if n <= 0 then len := 0; return; end; + done := done + n; + end; + len := 0; +end; + +(* s added to the buffer; the lock is held *) +proc put(s: []U8); +var i, n: INT; +begin + while i < LEN(s) do + if len = LEN(buf) then drain; end; + n := LEN(s) - i; + if n > LEN(buf) - len then n := LEN(buf) - len; end; + COPY(buf[len..len + n], s[i..i + n]); + len := len + n; + i := i + n; + end; +end; + +proc str*(s: []U8); +var i: INT; +begin + Lock.take(ADR(lock)); + put(s); + if terminal then + for i := 0 to LEN(s) - 1 do + if s[i] = 10 then drain; break; end; + end; + end; + Lock.give(ADR(lock)); +end; + +proc char*(c: U8); +var b: [1]U8; +begin + b[0] := c; + str(b); +end; + +(* a line feed *) +proc ln*; +begin + str("\n"); +end; + +(* n in decimal *) +proc int*(n: I64); +var digits: [20]U8; i: INT; u: U64; +begin + u := U64(n); + if n < 0 then u := 0 - u; end; + i := LEN(digits); + repeat + DEC(i); + digits[i] := U8(u mod 10) + '0'; + u := u div 10; + until u = 0; + if n < 0 then DEC(i); digits[i] := '-'; end; + str(digits[i..LEN(digits)]); +end; + +(* n in hexadecimal, digits digits at least *) +proc hex*(n: U64; digits: INT); +var d: [16]U8; i: INT; +begin + i := LEN(d); + repeat + DEC(i); + d[i] := hexDigits[INT(n & 0FH)]; + n := n shr 4; + until n = 0; + while i > LEN(d) - digits and i > 0 do DEC(i); d[i] := '0'; end; + str(d[i..LEN(d)]); +end; + +proc flush*; +begin + Lock.take(ADR(lock)); + drain; + Lock.give(ADR(lock)); +end; + +begin + terminal := Sys.isTerminal(Sys.stdout); + _ := Rt.atExit(flush); +end Out. diff --git a/sbcl/lib/Rt.raz b/sbcl/lib/Rt.raz new file mode 100644 index 0000000..1df23b5 --- /dev/null +++ b/sbcl/lib/Rt.raz @@ -0,0 +1,57 @@ +(* Ending the program: exit, atExit and stop; and trace, the calls under + way. The compiler's checks, and the faults the run time catches, end + in stop. *) +module Rt; +import Sys; + +const Full*: ERROR = "too many procedures to run at exit"; + +var + procs: [32]proc; (* the procedures to run at exit, the last on top *) + count: INT; + +(* p run when the program ends by exit *) +proc atExit*(p: proc): ERROR; +begin + if count = LEN(procs) then return Full; end; + procs[count] := p; + INC(count); + return nil; +end; + +(* The end: C's buffers flushed, then the process. *) +proc quit(status: INT); +code + (exit-now status); +end; + +(* The atExit procedures, the last first, each taken off the list before + it runs, so that it runs once even if it stops or calls exit itself; + then the end. *) +proc exit*(status: INT); +var p: proc; +begin + while count > 0 do + DEC(count); + p := procs[count]; + p; + end; + quit(status); +end; + +(* the calls under way, on standard error *) +proc trace*; +code + (trace-calls); +end; + +(* msg on standard error, then exit with status 2 *) +proc stop*(msg: []U8); +begin + _ := Sys.write(Sys.stderr, msg); + _ := Sys.write(Sys.stderr, "\n"); + trace; + exit(2); +end; + +end Rt. diff --git a/sbcl/lib/Str.raz b/sbcl/lib/Str.raz new file mode 100644 index 0000000..c2808f5 --- /dev/null +++ b/sbcl/lib/Str.raz @@ -0,0 +1,162 @@ +(* Operations on []U8 strings: comparing, hashing, finding, UTF-8, + reading a number, and numbers in a fixed byte order. *) +module Str; +import Mem, Rt; + +(* -1, 0 or 1 as a sorts before, with or after b, byte by byte *) +proc cmp*(a, b: []U8): INT; +var i: INT; +begin + while (i < LEN(a)) and (i < LEN(b)) do + if a[i] < b[i] then return -1; end; + if a[i] > b[i] then return 1; end; + INC(i); + end; + if LEN(a) < LEN(b) then return -1; end; + if LEN(a) > LEN(b) then return 1; end; + return 0; +end; + +proc eq*(a, b: []U8): BOOL; +begin + return a = b; +end; + +(* s's bytes in memory from a; false if a has none *) +proc copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL); +var p: ^U8; d: []U8; +begin + p := Mem.alloc(a, LEN(s), 1); + if (p = nil) and (LEN(s) > 0) then return "", false; end; + d := p[0..LEN(s)]; + COPY(d, s); + return d, true; +end; + +(* FNV-1a, 64 bits *) +proc hash*(s: []U8): U64; +var h: U64; i: INT; +begin + h := 0CBF29CE484222325H; + for i := 0 to LEN(s) - 1 do + h := (h xor U64(s[i])) * 100000001B3H; + end; + return h; +end; + +proc hasPrefix*(s, p: []U8): BOOL; +begin + return (LEN(p) <= LEN(s)) and (s[0..LEN(p)] = p); +end; + +(* where sub first starts in s, or -1 *) +proc find*(s, sub: []U8): INT; +var i: INT; +begin + for i := 0 to LEN(s) - LEN(sub) do + if s[i..i + LEN(sub)] = sub then return i; end; + end; + return -1; +end; + +(* c in UTF-8: its bytes, and how many *) +proc encode*(c: I32): ([4]U8, INT); +var b: [4]U8; +begin + if (c < 0) or (c > 10FFFFH) or ((c >= 0D800H) and (c <= 0DFFFH)) then c := 0FFFDH; end; + if c < 80H then + b[0] := U8(c); + return b, 1; + elsif c < 800H then + b[0] := U8(0C0H | (c shr 6)); b[1] := U8(80H | (c & 3FH)); + return b, 2; + elsif c < 10000H then + b[0] := U8(0E0H | (c shr 12)); b[1] := U8(80H | ((c shr 6) & 3FH)); + b[2] := U8(80H | (c & 3FH)); + return b, 3; + end; + b[0] := U8(0F0H | (c shr 18)); b[1] := U8(80H | ((c shr 12) & 3FH)); + b[2] := U8(80H | ((c shr 6) & 3FH)); b[3] := U8(80H | (c & 3FH)); + return b, 4; +end; + +(* the character s starts with, and its length in bytes *) +proc decode*(s: []U8): (I32, INT); +var c, least: I32; n, i: INT; b: U8; +begin + if LEN(s) = 0 then return 0, 0; end; + b := s[0]; + if b < 80H then return I32(b), 1; + elsif (b >= 0C2H) and (b < 0E0H) then n := 2; c := I32(b & 1FH); least := 80H; + elsif (b >= 0E0H) and (b < 0F0H) then n := 3; c := I32(b & 0FH); least := 800H; + elsif (b >= 0F0H) and (b < 0F5H) then n := 4; c := I32(b & 7H); least := 10000H; + else return 0FFFDH, 1; + end; + if LEN(s) < n then return 0FFFDH, 1; end; + for i := 1 to n - 1 do + if s[i] & 0C0H # 80H then return 0FFFDH, 1; end; + c := (c shl 6) | I32(s[i] & 3FH); + end; + if (c < least) or (c > 10FFFFH) or ((c >= 0D800H) and (c <= 0DFFFH)) then return 0FFFDH, 1; end; + return c, n; +end; + +(* s, in decimal; false if it isn't a number an I64 holds *) +proc toInt*(s: []U8): (I64, BOOL); +var i: INT; neg: BOOL; v: U64; d: U64; +begin + if LEN(s) = 0 then return 0, false; end; + if (s[0] = '-') or (s[0] = '+') then neg := s[0] = '-'; i := 1; end; + if i = LEN(s) then return 0, false; end; + while i < LEN(s) do + if (s[i] < '0') or (s[i] > '9') then return 0, false; end; + d := U64(s[i] - '0'); + if v > (8000000000000000H - d) div 10 then return 0, false; end; + v := v * 10 + d; + INC(i); + end; + if neg then return I64(0 - v), true; end; + if v > 7FFFFFFFFFFFFFFFH then return 0, false; end; + return I64(v), true; +end; + +proc tooLong(s: []U8); +begin + if LEN(s) > 8 then Rt.stop("Str: more than 8 bytes for a number"); end; +end; + +(* s, at most 8 bytes, the first the lowest *) +proc le*(s: []U8): U64; +var v: U64; i: INT; +begin + tooLong(s); + for i := LEN(s) - 1 to 0 by -1 do v := (v shl 8) | U64(s[i]); end; + return v; +end; + +(* s, at most 8 bytes, the first the highest *) +proc be*(s: []U8): U64; +var v: U64; i: INT; +begin + tooLong(s); + for i := 0 to LEN(s) - 1 do v := (v shl 8) | U64(s[i]); end; + return v; +end; + +(* v into s, the lowest byte first *) +proc putLE*(s: []U8; v: U64); +var i: INT; +begin + tooLong(s); + for i := 0 to LEN(s) - 1 do s[i] := U8(v & 0FFH); v := v shr 8; end; +end; + +(* v into s, the highest byte first *) +proc putBE*(s: []U8; v: U64); +var i: INT; +begin + tooLong(s); + for i := LEN(s) - 1 to 0 by -1 do s[i] := U8(v & 0FFH); v := v shr 8; end; +end; + +end Str. diff --git a/sbcl/lib/Sys.raz b/sbcl/lib/Sys.raz new file mode 100644 index 0000000..108d976 --- /dev/null +++ b/sbcl/lib/Sys.raz @@ -0,0 +1,293 @@ +(* System calls, for Linux on any machine SBCL runs on: through the C + library's syscall(), which the run time's SYSCALL calls. The numbers + are x86-64's. A result that can fail is a number, minus an errno, as + on Linux. *) +module Sys; + +const + stdin* = 0; stdout* = 1; stderr* = 2; + outSize* = 4096; (* the bytes Out keeps *) + sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13; + sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19; + sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28; + + (* system call numbers *) + sysRead = 0; sysWrite = 1; sysClose = 3; sysStat = 4; sysLstat = 6; + sysLseek = 8; sysMmap = 9; sysMunmap = 11; sysIoctl = 16; + sysYield = 24; sysNanosleep = 35; sysGetpid = 39; sysKill = 62; + sysGetcwd = 79; sysChdir = 80; sysRename = 82; sysMkdir = 83; + sysRmdir = 84; sysUnlink = 87; sysSymlink = 88; sysReadlink = 89; + sysChmod = 90; sysClockGettime = 228; sysExitGroup = 231; + sysOpenat = 257; sysGetrandom = 318; + + atFdCwd = -100; + pathMax = 4096; + +type + Access* = (reading, writing, creating, exclusive, truncating, appending); + Accesses* = set of Access; + Info* = record + size*: I64; (* in bytes *) + mtime*: I64; (* when its contents last changed, in nanoseconds since 1970 *) + mode*: INT; (* its permission bits *) + dir*: BOOL; (* a directory *) + file*: BOOL; (* a regular file *) + symlink*: BOOL; (* the path itself is a symbolic link *) + end; + Path = [pathMax]U8; (* a path with a zero after it, as Linux takes it *) + +var + linkBuf: [pathMax]U8; + dirBuf: [pathMax]U8; + envp: ^^U8; + +(* p, ended by a zero, in c; false if it is too long *) +proc cPath(p: []U8; var c: Path): BOOL; +begin + if LEN(p) >= LEN(c) then return false; end; + COPY(c, p); + c[LEN(p)] := 0; + return true; +end; + +proc write*(fd: INT; s: []U8): INT; +begin + return SYSCALL(sysWrite, fd, ADR(s[0]) , LEN(s)); +end; + +proc read*(fd: INT; buf: []U8): INT; +begin + if LEN(buf) = 0 then return 0; end; + return SYSCALL(sysRead, fd, ADR(buf[0]), LEN(buf)); +end; + +proc open*(path: []U8; how: Accesses): INT; +var c: Path; flags: INT; +begin + if not cPath(path, c) then return -36; end; + if (reading in how) and (writing in how) then flags := 2; + elsif writing in how then flags := 1; + end; + if creating in how then flags := flags | 40H; end; + if exclusive in how then flags := flags | 80H; end; + if truncating in how then flags := flags | 200H; end; + if appending in how then flags := flags | 400H; end; + return SYSCALL(sysOpenat, atFdCwd, ADR(c), flags | 80000H, 1A4H); +end; + +proc openRead*(path: []U8): INT; +begin + return open(path, {reading}); +end; + +proc create*(path: []U8): INT; +begin + return open(path, {writing, creating, truncating}); +end; + +proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; +var whence: INT; +begin + if fromEnd then whence := 2; end; + return SYSCALL(sysLseek, fd, pos, whence); +end; + +proc close*(fd: INT); +begin + _ := SYSCALL(sysClose, fd); +end; + +proc isTerminal*(fd: INT): BOOL; +var termios: [64]U8; +begin + return SYSCALL(sysIoctl, fd, 5401H, ADR(termios)) = 0; +end; + +(* size bytes of zeroed memory, in whole pages; or nil *) +proc mmap*(size: INT): ^U8; +var r: INT; +begin + r := SYSCALL(sysMmap, 0, size, 3, 22H, -1, 0); + if r < 0 then return nil; end; + return ^U8(r); +end; + +proc munmap*(p: ^U8; size: INT); +begin + _ := SYSCALL(sysMunmap, p, size); +end; + +proc yield*; +begin + _ := SYSCALL(sysYield); +end; + +(* the program ended at once, without Rt's atExit *) +proc exit*(status: INT); +begin + _ := SYSCALL(sysExitGroup, status); +end; + +proc rename*(old, new: []U8): INT; +var a, b: Path; +begin + if not cPath(old, a) or not cPath(new, b) then return -36; end; + return SYSCALL(sysRename, ADR(a), ADR(b)); +end; + +proc remove*(path: []U8): INT; +var c: Path; +begin + if not cPath(path, c) then return -36; end; + return SYSCALL(sysUnlink, ADR(c)); +end; + +proc removeDir*(path: []U8): INT; +var c: Path; +begin + if not cPath(path, c) then return -36; end; + return SYSCALL(sysRmdir, ADR(c)); +end; + +proc makeDir*(path: []U8): INT; +var c: Path; +begin + if not cPath(path, c) then return -36; end; + return SYSCALL(sysMkdir, ADR(c), 1EDH); +end; + +proc chmod*(path: []U8; mode: INT): INT; +var c: Path; +begin + if not cPath(path, c) then return -36; end; + return SYSCALL(sysChmod, ADR(c), mode); +end; + +proc symlink*(target, path: []U8): INT; +var a, b: Path; +begin + if not cPath(target, a) or not cPath(path, b) then return -36; end; + return SYSCALL(sysSymlink, ADR(a), ADR(b)); +end; + +(* what the link names, good until the next call *) +proc readLink*(path: []U8): ([]U8, INT); +var c: Path; n: INT; +begin + if not cPath(path, c) then return "", -36; end; + n := SYSCALL(sysReadlink, ADR(c), ADR(linkBuf), LEN(linkBuf)); + if n < 0 then return "", n; end; + return linkBuf[0..n], 0; +end; + +(* following a symbolic link *) +proc info*(path: []U8): (Info, INT); +var c: Path; st: [144]U8; r: INT; i: Info; mode: U32; +begin + if not cPath(path, c) then return i, -36; end; + r := SYSCALL(sysLstat, ADR(c), ADR(st)); + if r < 0 then return i, r; end; + i.symlink := ^U32(ADR(st[24]))^ & 0F000H = 0A000H; + if i.symlink then + r := SYSCALL(sysStat, ADR(c), ADR(st)); + if r < 0 then return i, r; end; + end; + mode := ^U32(ADR(st[24]))^; + i.size := ^I64(ADR(st[48]))^; + i.mtime := ^I64(ADR(st[88]))^ * 1000000000 + ^I64(ADR(st[96]))^; + i.mode := INT(mode & 1FFH); + i.dir := mode & 0F000H = 4000H; + i.file := mode & 0F000H = 8000H; + return i, 0; +end; + +(* C's environ, which the run time's C library keeps *) +proc environ: ^^U8; +code + (ld :u64 (sb-sys:find-foreign-symbol-address "environ")); +end; + +(* the environment variable's value; "" if unset *) +proc env*(name: []U8): []U8; +var e: ^U8; i, n: INT; +begin + if envp = nil then envp := environ(); end; + i := 0; + while envp[i] # nil do + e := envp[i]; + n := 0; + while e[n] # 0 do INC(n); end; + if n > LEN(name) and e[LEN(name)] = '=' and e[0..LEN(name)] = name then + return e[LEN(name) + 1..n]; + end; + INC(i); + end; + return ""; +end; + +(* the working directory, good until the next call *) +proc workDir*: ([]U8, INT); +var r: INT; +begin + r := SYSCALL(sysGetcwd, ADR(dirBuf), LEN(dirBuf)); + if r < 0 then return "", r; end; + r := 0; + while dirBuf[r] # 0 do INC(r); end; + return dirBuf[0..r], 0; +end; + +proc setWorkDir*(path: []U8): INT; +var c: Path; +begin + if not cPath(path, c) then return -36; end; + return SYSCALL(sysChdir, ADR(c)); +end; + +proc pid*: INT; +begin + return SYSCALL(sysGetpid); +end; + +proc kill*(pid, signal: INT): INT; +begin + return SYSCALL(sysKill, pid, signal); +end; + +proc clockOf(which: INT): I64; +var t: [2]I64; +begin + _ := SYSCALL(sysClockGettime, which, ADR(t)); + return t[0] * 1000000000 + t[1]; +end; + +(* nanoseconds, on a clock that only goes forward *) +proc clock*: I64; +begin + return clockOf(1); +end; + +(* nanoseconds since 1970-01-01, UTC *) +proc now*: I64; +begin + return clockOf(0); +end; + +proc sleep*(ms: INT); +var t: [2]I64; +begin + t[0] := ms div 1000; + t[1] := (ms mod 1000) * 1000000; + while SYSCALL(sysNanosleep, ADR(t), ADR(t)) = -4 do end; +end; + +(* b filled with random bytes *) +proc random*(b: []U8); +var done, n: INT; +begin + while done < LEN(b) do + n := SYSCALL(sysGetrandom, ADR(b[done]), LEN(b) - done, 0); + if n > 0 then done := done + n; end; + end; +end; + +end Sys. diff --git a/sbcl/src/comp.lisp b/sbcl/src/comp.lisp new file mode 100644 index 0000000..ab35d37 --- /dev/null +++ b/sbcl/src/comp.lisp @@ -0,0 +1,221 @@ +;;;; comp.lisp -- what the parts of the compiler share: modules, the +;;;; names they declare, the items an expression compiles to, procedures' +;;;; frames, the data block and reading tokens. +;;;; +;;;; The compiler reads each module once, from front to back, checking it +;;;; and turning it into Lisp as it goes, as Wirth's compilers do: an +;;;; expression becomes an ITEM, which says what it is (a constant, a +;;;; variable, a value, a procedure...) and holds the Lisp form that +;;;; computes it. Each procedure becomes a DEFUN, kept in *FORMS*; the +;;;; driver compiles them all with SBCL and saves the result as the +;;;; executable. + +(in-package :raz) + +;;; Modules. +;;; +;;; A generic module (section 3) is read only up to its parameters when +;;; it is imported; each distinct list of arguments then makes an +;;; INSTANCE, a module of its own, compiled from the same tokens with the +;;; parameters standing for the arguments. + +(defstruct module + name ; as written, "Out" + file toks ; its file and tokens + (exports (make-hash-table :test 'equal)) ; name -> obj, the exported names + scope ; its scope, for its own code + imports ; IMPORTs, in order, which decide the order of bodies + generic ; for a generic module: its parameters, (names . proc-params) + (instances '()) ; for a generic module: (args . module) for each instance + args ; for an instance: its arguments + lisp-name ; the prefix of its procedures' Lisp names, "Out" or "List(2)" + check-off ; it says `check off;` + static ; it says `link static;` + uses-c ; it has an extern or links a library + links ; the libraries it links + body ; the Lisp symbol of its body's function, if it has a body + (state :new)) ; :compiling while its declarations are read, then :done + +;;; An import: ALIAS is the name the importer uses; TARGET the module, +;;; or the generic module; ARGS the position of its arguments' tokens, +;;; read when the instance is made; INSTANCE then the instance. +(defstruct import alias target args instance tok) + +;;; A declared name. KIND is :const :type :var :proc :module :builtin or +;;; :case. For a :var, WHERE says where it lives: +;;; (:global address) a module variable, in the data block +;;; (:local offset) a procedure's, in its frame +;;; (:var-param offset) a var parameter: its frame holds the address +;;; (:at form) a match arm's name: FORM is the address +;;; (:extern name) a C variable +;;; For a :const, VAL is its value (for an array or record constant, its +;;; address in the data block). For a :proc, SYM is its Lisp function, +;;; SIG its signature, and EXTERN, CODE and FORWARD say what kind it is. + +(defstruct obj + name kind type val where exported module + sym sig extern code forward defined (handle nil) tok import) + +;;; The state of the compilation. Each is rebound while a module is read, +;;; since an instance of a generic module may be read in the middle of +;;; another module's procedure. + +(defvar *module* nil "The module being read.") +(defvar *scope* nil "The innermost scope.") +(defvar *toks* #() "The tokens of the module being read.") +(defvar *pos* 0 "The index of the next token.") +(defvar *proc* nil "The PROC being compiled, or nil outside procedures.") +(defvar *forms* '() "The program's top-level Lisp forms, the last first.") +(defvar *modules* (make-hash-table :test 'equal) "Every module read, by name.") + +;;; Scopes: a table of names and the scope around it. + +(defstruct scope (table (make-hash-table :test 'equal)) parent) + +(defvar *universe* nil "The scope around every module: the predeclared names.") + +(defun lookup (name &optional (scope *scope*)) + (loop for s = scope then (scope-parent s) while s + do (let ((o (gethash name (scope-table s)))) (when o (return o))))) + +(defun declare-name (obj &optional (scope *scope*)) + (when (gethash (obj-name obj) (scope-table scope)) + (fail-tok (obj-tok obj) "~a is declared twice" (obj-name obj))) + (setf (gethash (obj-name obj) (scope-table scope)) obj) + obj) + +;;; A procedure (or a module body) being compiled. Its frame grows by +;;; ALLOC as variables and temporaries are given places in it. DEFERS +;;; holds, for each statement list it is in, the innermost first, the +;;; forms of the statements deferred there, the last first (section 7.7). +;;; LOOPS holds, for each loop it is in, its block name and the DEFERS +;;; outside it. + +(defstruct proc + obj sig (size 0) block (defers '()) (loops '()) dests in-defer results) + +(defun alloc (size align) + "A place of SIZE bytes in the current frame: the form of its address." + (let ((off (round-up (proc-size *proc*) (max align 1)))) + (setf (proc-size *proc*) (+ off size)) + `(+ fp ,off))) + +(defun temp (ty) (alloc (ty-size ty) (ty-align ty))) + +;;; Items. MODE is +;;; :const a constant; VAL is its value +;;; :var a variable; FORM is its address +;;; :val a value; FORM computes it (the address of a copy, for an aggregate) +;;; :literal an array, record or set literal, waiting for the type it +;;; must have (6.5): VAL is (kind elements) +;;; :proc a procedure, OBJ; :builtin, VAL its name; :type, TYPE; +;;; :case a variant's case, VAL; :module, OBJ the import +;;; :multi a call with several results, TYPE their list +;;; :none a call with no result +;;; RO says why a variable can't be changed: :export (another module's, +;;; section 3), :const (a constant's part or a string's byte) or :value +;;; (a part of a value). VOL marks a volatile variable (7.6); NOADDR a +;;; field of a packed record that has no address (5.5). + +(defstruct item mode type form val ro vol noaddr obj tok) + +;;; Reading tokens. + +(defun tok (&optional (k 0)) (aref *toks* (min (+ *pos* k) (1- (length *toks*))))) +(defun kind (&optional (k 0)) (tok-kind (tok k))) +(defun next-tok () (prog1 (tok) (incf *pos*))) + +(defun fail-tok (tok fmt &rest args) + (apply #'fail-at (tok-line tok) (tok-col tok) fmt args)) + +(defun fail-here (fmt &rest args) (apply #'fail-tok (tok) fmt args)) + +(defun accept (kind) (when (eq (kind) kind) (next-tok))) + +(defun describe-tok (tok) + (case (tok-kind tok) + (:ident (format nil "~a" (tok-val tok))) + (:eof "the end of the file") + ((:int :real :char) "a number") + (:string "a string") + (:blank "_") + (t (format nil "~(~a~)" (tok-kind tok))))) + +(defun expect (kind &optional what) + (or (accept kind) + (fail-here "~a expected, not ~a" (or what (format nil "~(~a~)" kind)) (describe-tok (tok))))) + +(defun ident () + (let ((tk (tok))) + (unless (eq (tok-kind tk) :ident) + (fail-here "a name expected, not ~a" (describe-tok tk))) + (next-tok) + (tok-val tk))) + +(defun where (tok) + "TOK's place, as a stopping program says it." + (format nil "~a:~d:~d" *file* (tok-line tok) (tok-col tok))) + +;;; The data block (rt.lisp): the module variables, strings, constants +;;; and errors' messages, each at an address the compiler gives. + +(defvar *data* (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0)) +(defvar *strings* (make-hash-table :test 'equalp) "Bytes -> the address of a copy, with a 0 after it.") +(defvar *string-slices* (make-hash-table :test 'equalp) "Bytes -> the address of a slice of them.") + +(defun data-alloc (size align) + (loop until (zerop (mod (fill-pointer *data*) (max align 1))) do (vector-push-extend 0 *data*)) + (prog1 (+ +data-base+ (fill-pointer *data*)) + (loop repeat size do (vector-push-extend 0 *data*)))) + +(defun data-put (addr bytes) + (loop for b across bytes for i from (- addr +data-base+) do (setf (aref *data* i) b))) + +(defun data-put-int (addr value size) + (loop for i below size do (setf (aref *data* (+ (- addr +data-base+) i)) (ldb (byte 8 (* 8 i)) value)))) + +(defun string-address (bytes) + "The address of BYTES in the data block, followed by a zero byte, as C wants." + (or (gethash bytes *strings*) + (let ((a (data-alloc (1+ (length bytes)) 1))) + (data-put a bytes) + (setf (gethash bytes *strings*) a)))) + +(defun string-slice (bytes) + "The address of a slice of BYTES." + (or (gethash bytes *string-slices*) + (let ((s (data-alloc 16 8))) + (data-put-int s (string-address bytes) 8) + (data-put-int (+ s 8) (length bytes) 8) + (setf (gethash bytes *string-slices*) s)))) + +(defun error-value (message) + "A new ERROR (5.8): the address of a slice of its message, unique to +the declaration that makes it, so that MSG reads it there." + (let ((s (data-alloc 16 8))) + (data-put-int s (string-address message) 8) + (data-put-int (+ s 8) (length message) 8) + s)) + +;;; Procedure values: each procedure used as a value gets its index in +;;; the run time's *PROCS*. + +(defvar *proc-values* '() "(index . symbol) for each procedure value, the last first.") + +(defun proc-handle (obj) + (or (obj-handle obj) + (setf (obj-handle obj) + (let ((h (1+ (length *proc-values*)))) + (push (cons h (obj-sym obj)) *proc-values*) + h)))) + +;;; Emitting. + +(defun emit (form) (push form *forms*)) + +(defun lisp-name (name) + "The Lisp symbol of the current module's NAME." + (intern (format nil "~a.~a" (module-lisp-name *module*) name) :razp)) + +(defvar *gensym-count* 0) +(defun var-sym (prefix) (make-symbol (format nil "~a~d" prefix (incf *gensym-count*)))) diff --git a/sbcl/src/decl.lisp b/sbcl/src/decl.lisp new file mode 100644 index 0000000..cc68289 --- /dev/null +++ b/sbcl/src/decl.lisp @@ -0,0 +1,603 @@ +;;;; decl.lisp -- modules, imports, generic instances, declarations, +;;;; types and procedures (report, sections 3, 4, 5, 8 and 9). + +(in-package :raz) + +;;; The scope around every module (section 2). + +(defparameter *builtins* + '("SIZE" "ADR" "LEN" "NEW" "MSG" "COPY" "SYSCALL" "INC" "DEC" "FENCE" + "CAS" "XCHG" "XADD" "ARGC" "ARGV")) + +(defun make-universe () + (let ((*scope* (make-scope))) + (dolist (ty *basic-types*) + (declare-name (make-obj :name (ty-name ty) :kind :type :type ty))) + (declare-name (make-obj :name "true" :kind :const :type (basic "BOOL") :val t)) + (declare-name (make-obj :name "false" :kind :const :type (basic "BOOL") :val nil)) + (declare-name (make-obj :name "nil" :kind :const :type *nil-type* :val 0)) + (dolist (b *builtins*) (declare-name (make-obj :name b :kind :builtin))) + *scope*)) + +;;; Names declared at the top of a module may be exported. + +(defun ident-def (top) + "An IdentDef: the name, and whether it is exported (only at the top)." + (let ((tk (tok)) (name (ident))) + (values name (when (accept :*) + (unless top (fail-tok tk "only a module's own names are exported")) + t) + tk))) + +(defun declare-top (obj) + "Declares OBJ in the current scope, and among the module's exports if +it is exported." + (declare-name obj) + (when (obj-exported obj) + (setf (gethash (obj-name obj) (module-exports *module*)) obj)) + obj) + +;;; Types (section 5). + +(defvar *forward-types* nil + "In a `type` section, the pointers whose base is declared later in it, +(type name tok) for each; elsewhere :none.") +(defvar *type-exported* nil "Whether the type being declared is exported: its case and enumeration names are too.") +(defvar *top* nil "Whether the declarations being read are a module's own.") + +(defun parse-type () + (let ((tk (tok))) + (case (kind) + (:ident (named-type)) + (:|[| (next-tok) + (if (accept :|]|) + (make-slice-type (parse-type)) + (let ((n (constant-int "an array's length"))) + (unless (> n 0) (fail-tok tk "an array's length is greater than 0")) + (expect :|]|) + (check-size (make-array-type n (parse-type)) tk)))) + (:^ (next-tok) (pointer-type-rest)) + (:packed (next-tok) (expect :record) (record-type t tk)) + (:record (next-tok) (record-type nil tk)) + (:variant (next-tok) (variant-type)) + (:|(| (next-tok) (enum-type)) + (:set (next-tok) (expect :of) + (let ((e (named-type))) + (unless (is e :enum) (fail-tok tk "a set is of an enumeration")) + (when (> (length (ty-names e)) 64) (fail-tok tk "a set's enumeration has at most 64 names")) + (make-set-type e))) + (:proc (next-tok) (make-proc-type (signature nil))) + (t (fail-here "a type expected, not ~a" (describe-tok tk)))))) + +(defun check-size (ty tk) + (when (> (ty-size ty) (int-max (basic "INT"))) (fail-tok tk "the type is too big")) + ty) + +(defun named-type () + (multiple-value-bind (obj tk) (qualified-obj) + (unless (eq (obj-kind obj) :type) (fail-tok tk "~a isn't a type" (obj-name obj))) + (obj-type obj))) + +(defun pointer-type-rest () + "A pointer type, after its ^." + (let ((vol (accept :volatile))) + (if (and (listp *forward-types*) (eq (kind) :ident) (not (eq (kind 1) :|.|)) + (not (lookup (tok-val (tok))))) + ;; a type declared later in this section (section 4) + (let* ((tk (next-tok)) (ty (make-ptr-type (list :forward (tok-val tk)) vol))) + (push (list ty (tok-val tk) tk) *forward-types*) + ty) + (make-ptr-type (parse-type) vol)))) + +(defun resolve-forward-types () + (dolist (f *forward-types*) + (destructuring-bind (ty name tk) f + (let ((obj (lookup name))) + (unless (and obj (eq (obj-kind obj) :type)) + (fail-tok tk "~a isn't declared as a type" name)) + (setf (ty-base ty) (obj-type obj)))))) + +(defun field-list (fields &key exports) + "IdentList : Type, the names added to FIELDS (each name new)." + (let ((names (loop collect (multiple-value-list (if exports (ident-def *top*) (values (ident) nil (tok 0)))) + while (accept :|,|)))) + (expect :|:|) + (let ((ty (parse-type))) + (dolist (n names fields) + (destructuring-bind (name exported tk) n + (when (find name fields :key #'field-name :test #'string=) + (fail-tok tk "the field ~a is declared twice" name)) + (setf fields (append fields (list (make-field :name name :type ty :exported exported))))))))) + +(defun record-type (packed tk) + (let ((fields '())) + (loop until (accept :end) + do (setf fields (field-list fields :exports t)) (expect :|;|)) + (check-size (make-record-type fields packed *module*) tk))) + +(defun declare-member (name kind type val tk) + "A name a type declares in the scope around it: a case or an enumeration's name." + (declare-top (make-obj :name name :kind kind :type type :val val :tok tk + :exported *type-exported* :module *module*))) + +(defun variant-type () + (let ((cases '()) (ty (make-ty :kind :variant))) + (loop until (accept :end) + do (let* ((tk (tok)) (name (ident)) (fields '())) + (when (accept :|(|) + (loop (setf fields (field-list fields)) (unless (accept :|;|) (return))) + (expect :|)|)) + (when (find name cases :key #'vcase-name :test #'string=) + (fail-tok tk "the case ~a is declared twice" name)) + (setf cases (append cases (list (make-vcase :name name :index (length cases) :fields fields)))) + (push tk (ty-names ty))) + (expect :|;|)) + (let ((v (make-variant-type cases *module*))) + (loop for c in cases for tk in (reverse (ty-names ty)) + do (declare-member (vcase-name c) :case v c tk)) + v))) + +(defun enum-type () + (let ((names (loop collect (cons (tok) (ident)) while (accept :|,|)))) + (expect :|)|) + (when (> (length names) 256) (fail-tok (car (first names)) "an enumeration has at most 256 names")) + (let ((ty (make-enum-type (mapcar #'cdr names) *module*))) + (loop for (tk . name) in names for i from 0 + do (declare-member name :const ty i tk)) + ty))) + +(defun signature (extern) + "A Signature: its parameters, `...` for an EXTERN, and its results." + (let ((params '()) (varargs nil)) + (when (accept :|(|) + (unless (eq (kind) :|)|) + (loop + (when (eq (kind) :...) + (unless (and extern params) (fail-here "... is for an extern, after its parameters")) + (next-tok) (setf varargs t) (return)) + (let* ((var (accept :var)) + (names (loop collect (cons (tok) (ident)) while (accept :|,|)))) + (expect :|:|) + (let ((ty (parse-type))) + (dolist (n names) + (when (find (cdr n) params :key #'first :test #'string=) + (fail-tok (car n) "the parameter ~a is declared twice" (cdr n))) + (setf params (append params (list (list (cdr n) ty (and var t)))))))) + (unless (accept :|;|) (return)))) + (expect :|)|)) + (make-sig :params params :varargs varargs + :results (when (accept :|:|) + (if (accept :|(|) + (prog1 (loop collect (parse-type) while (accept :|,|)) (expect :|)|)) + (list (parse-type))))))) + +;;; Constants (section 4). + +(defun constant-int (what) + (let* ((tk (tok)) (x (need-value (expression)))) + (unless (and (const-p x) (member (ty-kind (item-type x)) '(:int :untyped-int))) + (fail-tok tk "~a is an integer constant" what)) + (item-val x))) + +(defun write-const (addr ty item tk) + "Writes the constant ITEM, as a TY, at ADDR in the data block." + (let ((why (assign-error item ty))) + (when why (fail-tok tk "~a" why))) + (case (item-mode item) + (:literal + (destructuring-bind (kind elems) (item-val item) + (ecase kind + (:empty) + (:array (if (is ty :slice) + (let ((arr (data-alloc (* (length elems) (ty-size (ty-elem ty))) (ty-align (ty-elem ty))))) + (loop for e in elems for i from 0 + do (write-const (+ arr (* i (ty-size (ty-elem ty)))) (ty-elem ty) e tk)) + (data-put-int addr arr 8) (data-put-int (+ addr 8) (length elems) 8)) + (loop for e in elems for i from 0 + do (write-const (+ addr (* i (ty-size (ty-elem ty)))) (ty-elem ty) e tk)))) + (:record (loop for (name . e) in elems + for f = (find-field ty name tk) + do (write-const (+ addr (field-offset f)) (field-type f) e tk))) + (:set (write-const addr ty (const-item ty (build-literal item ty)) tk))))) + (:proc (data-put-int addr (proc-handle (item-obj item)) 8)) + (:const + (let ((v (item-val item)) (from (item-type item))) + (case (ty-kind ty) + ((:int :enum :set :error :ptr :proc) (data-put-int addr v (ty-size ty))) + (:bool (data-put-int addr (if v 1 0) 1)) + (:real (if (= (ty-bits ty) 32) + (data-put-int addr (sb-kernel:single-float-bits (coerce v 'single-float)) 4) + (data-put-int addr (sb-kernel:double-float-bits (coerce v 'double-float)) 8))) + (:slice (data-put-int addr (string-address v) 8) (data-put-int (+ addr 8) (length v) 8)) + (:array (data-put addr v)) + (t (fail-tok tk "~a isn't a constant of ~a" (type-name from) (type-name ty)))))) + (:var + (unless (eq (item-ro item) :const) (fail-tok tk "this isn't a constant")) + (let ((src (item-form item)) (from (item-type item))) + (if (is ty :slice) + (progn (data-put-int addr src 8) (data-put-int (+ addr 8) (ty-len from) 8)) + (let ((off (- src +data-base+))) + (data-put addr (subseq *data* off (+ off (ty-size ty)))))))) + (t (fail-tok tk "this isn't a constant")))) + +(defun const-section () + (loop while (eq (kind) :ident) + do (multiple-value-bind (name exported tk) (ident-def *top*) + (let ((ty (when (accept :|:|) (parse-type)))) + (expect :=) + (let* ((etk (tok)) (x (expression))) + (declare-top + (cond + ((null ty) + (unless (or (const-p x) (and (eq (item-mode x) :var) (eq (item-ro x) :const))) + (fail-tok etk "a constant's value is a constant")) + (make-obj :name name :kind :const :type (item-type x) :tok tk :exported exported + :val (if (const-p x) (item-val x) (item-form x)))) + ((is ty :error) + (unless (and (const-p x) (is (item-type x) :string)) + (fail-tok etk "an ERROR is made by a string")) + (make-obj :name name :kind :const :type ty :tok tk :exported exported + :val (error-value (item-val x)))) + ((member (ty-kind ty) '(:array :record)) + (let ((addr (data-alloc (ty-size ty) (ty-align ty)))) + (write-const addr ty x etk) + (make-obj :name name :kind :const :type ty :tok tk :exported exported :val addr))) + (t (fail-tok tk "a constant with a type is an ERROR, an array or a record"))))))) + (expect :|;|))) + +(defun type-section () + (let ((*forward-types* '())) + (loop while (eq (kind) :ident) + do (multiple-value-bind (name exported tk) (ident-def *top*) + (expect :=) + (let* ((alias (and (eq (kind) :ident) (member (kind (if (eq (kind 1) :|.|) 3 1)) '(:|;|)))) + (ty (let ((*type-exported* exported)) (parse-type)))) + ;; `type A = B` names B's type; anything else makes a new one + (unless (or alias (ty-name ty)) (setf (ty-name ty) name)) + (declare-top (make-obj :name name :kind :type :type ty :tok tk :exported exported)))) + (expect :|;|)) + (resolve-forward-types))) + +(defun var-section () + (loop while (eq (kind) :ident) + do (let ((names (loop collect (multiple-value-list (ident-def *top*)) while (accept :|,|)))) + (expect :|:|) + (let ((ty (parse-type))) + (dolist (n names) + (destructuring-bind (name exported tk) n + (declare-top + (make-obj :name name :kind :var :type ty :tok tk :exported exported + :module (when *top* *module*) + :where (if *top* + (list :global (data-alloc (ty-size ty) (ty-align ty))) + (list :local (alloc-offset (ty-size ty) (ty-align ty))))))))) + (expect :|;|)))) + +(defun alloc-offset (size align) + (third (alloc size align))) + +(defun declarations () + "Const, type and var sections, and at a module's top procedures and externs." + (loop + (case (kind) + (:const (next-tok) (const-section)) + (:type (next-tok) (type-section)) + (:var (next-tok) (var-section)) + (:proc (if *top* (progn (next-tok) (proc-declaration)) (fail-here "procedures don't nest"))) + (:extern (if *top* (progn (next-tok) (extern-declaration)) (fail-here "an extern is a module's"))) + (t (return))))) + +;;; Procedures (section 8). + +(defun proc-declaration () + (multiple-value-bind (name exported tk) (ident-def t) + (let* ((sig (signature nil)) + (old (gethash name (scope-table *scope*))) + (obj (if (and old (eq (obj-kind old) :proc) (obj-forward old) (not (obj-defined old))) + (progn + (unless (sig-alike-p sig (obj-sig old)) + (fail-tok tk "~a's signature isn't its forward declaration's" name)) + (setf (obj-sig old) sig) + old) + (declare-top (make-obj :name name :kind :proc :sig sig :tok tk :exported exported + :sym (lisp-name name)))))) + (expect :|;|) + (cond ((accept :forward) + (when (eq obj old) (fail-tok tk "~a is declared forward twice" name)) + (setf (obj-forward obj) t)) + ((eq (kind) :code) (next-tok) (code-procedure obj)) + (t (procedure-body obj) + (setf (obj-defined obj) t))) + (when (eq (kind) :ident) + (unless (string= (tok-val (tok)) name) + (fail-here "the procedure ends with its own name, ~a" name)) + (next-tok)) + (expect :|;|)))) + +(defun procedure-body (obj) + "Compiles a procedure's declarations and statements into a DEFUN." + (let* ((sig (obj-sig obj)) + (*scope* (make-scope :parent *scope*)) + (*proc* (make-proc :obj obj :sig sig :block (gensym "PROC") :results (sig-results sig))) + (*top* nil) + (psyms '()) (stores '())) + (setf (proc-dests *proc*) (loop for r in (sig-results sig) collect (when (aggregate-p r) (var-sym "D")))) + (dolist (p (sig-params sig)) + (destructuring-bind (name ty var) p + (let ((s (var-sym "P"))) + (push s psyms) + (if var + (let ((off (alloc-offset 8 8))) + (push `(st :u64 (+ fp ,off) ,s) stores) + (declare-name (make-obj :name name :kind :var :type ty :where (list :var-param off) :tok (tok)))) + (let ((off (alloc-offset (ty-size ty) (ty-align ty)))) + (push (if (aggregate-p ty) `(move (+ fp ,off) ,s ,(ty-size ty)) `(st ,(access-kind ty) (+ fp ,off) ,s)) + stores) + (declare-name (make-obj :name name :kind :var :type ty :where (list :local off) :tok (tok)))))))) + (declarations) + (expect :begin) + (let ((body (statements :end))) + (expect :end) + (emit (procedure-defun (obj-sym obj) (reverse psyms) (remove nil (proc-dests *proc*)) + (reverse stores) body (zeros-form (sig-results sig))))))) + +(defun procedure-defun (sym params dests stores body end) + `(defun ,sym (,@params ,@dests) + (let* ((fp *sp*) (*sp* (+ fp ,(proc-size *proc*)))) + (declare (ignorable fp)) + (enter fp ,(proc-size *proc*)) + ,@stores + (block ,(proc-block *proc*) ,@body ,end)))) + +(defun code-procedure (obj) + "A code procedure (section 8). This implementation's target is SBCL's +Lisp, so its instructions are Lisp forms, one to each `;`, which see the +parameters by their names; the value of the last is the result." + (let ((code (tok)) (sig (obj-sig obj))) + (expect :code) + (when (some #'aggregate-p (sig-results sig)) + (fail-tok code "a code procedure here returns no aggregate")) + (let* ((params (mapcar (lambda (p) (intern (string-upcase (first p)) :raz)) (sig-params sig))) + (forms (loop for (text line col) in (tok-val code) + collect (handler-case (let ((*package* (find-package :raz))) (read-from-string text)) + (error (e) (fail-at line col "the instruction isn't Lisp: ~a" e)))))) + (emit `(defun ,(obj-sym obj) ,params (declare (ignorable ,@params)) ,@forms)) + (setf (obj-defined obj) t (obj-code obj) t)) + (expect :end))) + +;;; Calling C (section 9). + +(defun extern-declaration () + (setf (module-uses-c *module*) t) + (cond ((accept :proc) + (multiple-value-bind (name exported tk) (ident-def t) + (let ((sig (signature t))) + (dolist (p (sig-params sig)) + (unless (and (not (third p)) (member (ty-kind (second p)) '(:int :bool :real :ptr :proc))) + (fail-tok tk "~a's parameter ~a isn't of a type C takes" name (first p)))) + (when (or (rest (sig-results sig)) + (and (sig-results sig) + (not (member (ty-kind (first (sig-results sig))) '(:int :bool :real :ptr :proc))))) + (fail-tok tk "~a's result isn't of a type C gives" name)) + (let ((obj (declare-top (make-obj :name name :kind :proc :sig sig :tok tk :exported exported + :sym (lisp-name name) :extern name :defined t)))) + (unless (sig-varargs sig) (emit (extern-wrapper obj))))))) + ((accept :var) + (multiple-value-bind (name exported tk) (ident-def t) + (expect :|:|) + (declare-top (make-obj :name name :kind :var :type (parse-type) :tok tk :exported exported + :module *module* :where (list :extern name))))) + (t (fail-here "extern proc or extern var expected"))) + (expect :|;|)) + +;;; A Lisp function calling a C procedure, for calls and for its value. +(defun extern-wrapper (obj) + (let* ((sig (obj-sig obj)) (result (first (sig-results sig))) + (ps (loop for p in (sig-params sig) collect (var-sym "P")))) + `(defun ,(obj-sym obj) ,ps + ,(c-result-form + result + `(sb-alien:alien-funcall + (sb-alien:extern-alien ,(obj-extern obj) + (function ,(if result (alien-type result) 'sb-alien:void) + ,@(mapcar (lambda (p) (alien-type (second p))) (sig-params sig)))) + ,@(loop for p in (sig-params sig) for s in ps collect (c-value-form (second p) s))))))) + +;;; Modules (section 3). + +(defvar *search-dirs* '() "Where modules are looked for, in order.") +(defvar *target-names* '("linux-sbcl" "linux" "sbcl")) + +(defun find-module-file (name tk) + "The file of module NAME: in the first directory that has one, which +must be the only one, or the same file through a symbolic link." + (let ((found '())) + (dolist (dir *search-dirs*) + (let ((f (loop for suffix in (append (mapcar (lambda (s) (format nil ".~a" s)) *target-names*) '("")) + for path = (format nil "~a/~a~a.raz" dir name suffix) + when (probe-file path) return path))) + (when f (push f found)))) + (setf found (nreverse found)) + (unless found (fail-tok tk "the module ~a can't be found" name)) + (unless (every (lambda (f) (equal (truename f) (truename (first found)))) found) + (fail-tok tk "the module ~a has files in more than one directory: ~{~a~^, ~}" name found)) + (namestring (truename (first found))))) + +(defun load-module (name tk &optional file) + "Module NAME, read if it hasn't been; a generic module only as far as +its parameters." + (let ((m (gethash name *modules*))) + (cond ((null m) + (let* ((file (or file (find-module-file name tk))) + (toks (let ((*file* file)) (scan (read-bytes file))))) + (setf m (make-module :name name :file file :toks toks :lisp-name name)) + (setf (gethash name *modules*) m) + (if (and (eq (tok-kind (aref toks 2)) :|(|)) + (read-generic-header m) + (read-module m)))) + ((eq (module-state m) :compiling) + (fail-tok tk "the module ~a imports itself" name))) + m)) + +(defmacro with-module ((m) &body body) + "BODY reading module M from its start." + `(let ((*module* ,m) (*toks* (module-toks ,m)) (*pos* 0) (*file* (module-file ,m)) + (*scope* (make-scope :parent *universe*)) (*proc* nil) (*top* t) (*forward-types* :none)) + (setf (module-scope ,m) *scope*) + ,@body)) + +(defun module-header () + "module Name ( and the name's check against the file's." + (expect :module) + (let ((tk (tok)) (name (ident))) + (unless (string= name (module-name *module*)) + (fail-tok tk "the module ~a is in the file of ~a" name (module-name *module*))))) + +(defun read-generic-header (m) + "A generic module's parameters, counted: the module is compiled only for +each list of arguments." + (with-module (m) + (module-header) + (expect :|(|) + (let ((types (loop collect (ident) while (accept :|,|))) (procs '())) + (loop while (accept :|;|) + do (push (ident) procs) (expect :|:|) (expect :proc) + ;; skip the signature: its types are known only in an instance + (let ((depth 0)) + (loop until (and (= depth 0) (member (kind) '(:|;| :|)|))) + do (case (kind) (:|(| (incf depth)) (:|)| (decf depth))) + (next-tok)))) + (setf (module-generic m) (cons types (nreverse procs)) (module-state m) :done)))) + +(defun read-module (m &optional args) + "Reads and compiles module M; for an instance, ARGS are its arguments." + (setf (module-state m) :compiling) + (with-module (m) + (module-header) + (when (accept :|(|) (bind-module-params args)) + (expect :|;|) + (loop while (accept :import) do (import-list)) + (loop while (and (eq (kind) :link)) + do (next-tok) + (cond ((eq (kind) :string) + (let ((lib (sb-ext:octets-to-string (tok-val (next-tok)) :external-format :utf-8))) + (handler-case (sb-alien:load-shared-object lib) + (error () (fail-tok (tok -1) "the library ~a can't be loaded" lib))) + (push lib (module-links m)) + (setf (module-uses-c m) t))) + ((and (eq (kind) :ident) (string= (tok-val (tok)) "static")) + (next-tok) (setf (module-static m) t)) + (t (fail-here "link takes a library's name or static"))) + (expect :|;|)) + (when (and (eq (kind) :ident) (string= (tok-val (tok)) "check")) + (next-tok) + (unless (and (eq (kind) :ident) (string= (tok-val (tok)) "off")) (fail-here "check off expected")) + (next-tok) (expect :|;|) + (setf (module-check-off m) t)) + (declarations) + (when (eq (kind) :begin) + (next-tok) + (let* ((sym (lisp-name "(body)")) + (*proc* (make-proc :block (gensym "BODY"))) + (*scope* (make-scope :parent *scope*)) + (body (statements :end))) + (emit (procedure-defun sym '() '() '() body nil)) + (setf (module-body m) sym))) + (expect :end) + (let ((tk (tok))) + (unless (equal (ident) (module-name m)) (fail-tok tk "the module ends with its own name, ~a" (module-name m)))) + (expect :|.|) + (unless (eq (kind) :eof) (fail-here "nothing follows the module's end")) + (maphash (lambda (name o) + (when (and (eq (obj-kind o) :proc) (not (obj-defined o))) + (fail-tok (obj-tok o) "~a is declared forward and never defined" name))) + (scope-table *scope*))) + (setf (module-state m) :done) + m) + +(defun import-list () + (loop + (let* ((tk (tok)) (alias (ident)) (name alias) (args nil)) + (when (accept :|:=|) + (setf name (ident)) + (when (eq (kind) :|(|) + ;; the arguments are read where the instance is made + (setf args *pos*) + (let ((depth 0)) + (loop do (case (kind) (:|(| (incf depth)) (:|)| (decf depth)) (:eof (fail-here "the import isn't closed"))) + (next-tok) + until (= depth 0))))) + (when (string= name (module-name *module*)) (fail-tok tk "the module ~a imports itself" name)) + (let* ((target (load-module name tk)) + (imp (make-import :alias alias :target target :args args :tok tk))) + (cond ((and args (not (module-generic target))) + (fail-tok tk "~a isn't generic and takes no arguments" name)) + ((and (module-generic target) (not args)) + (fail-tok tk "~a is generic: give its arguments" name))) + (push imp (module-imports *module*)) + (declare-name (make-obj :name alias :kind :module :val imp :tok tk)))) + (unless (accept :|,|) (return))) + (expect :|;|)) + +(defun import-module (imp tk) + "The module an import stands for: for a generic module, the instance +for its arguments, made now if it hasn't been (section 3)." + (cond ((import-instance imp)) + ((not (module-generic (import-target imp))) (import-target imp)) + (t (setf (import-instance imp) (make-instance-module imp tk))))) + +(defun read-type-args () + "A generic module's arguments, after its (: each a type, or (:proc obj)." + (loop collect (let ((start *pos*)) + (if (eq (kind) :ident) + (let ((obj (qualified-obj))) + (if (eq (obj-kind obj) :proc) + (list :proc obj) + (progn (setf *pos* start) (parse-type)))) + (parse-type))) + while (accept :|,|))) + +(defun same-args-p (a b) + (and (= (length a) (length b)) + (every (lambda (x y) + (if (consp x) + (and (consp y) (eq (second x) (second y))) + (and (ty-p y) (same-type-p x y)))) + a b))) + +(defun make-instance-module (imp tk) + (let* ((g (import-target imp)) + (args (let ((saved *pos*)) + (setf *pos* (1+ (import-args imp))) + (prog1 (read-type-args) (setf *pos* saved)))) + (ntypes (length (car (module-generic g)))) + (nprocs (length (cdr (module-generic g))))) + (unless (and (= (length args) (+ ntypes nprocs)) + (notany #'consp (subseq args 0 (min ntypes (length args)))) + (every #'consp (nthcdr ntypes args))) + (fail-tok tk "~a takes ~d types and ~d procedures" (module-name g) ntypes nprocs)) + (let ((old (assoc args (module-instances g) :test #'same-args-p))) + (if old + (cdr old) + (let ((m (make-module :name (module-name g) :file (module-file g) :toks (module-toks g) + :lisp-name (format nil "~a(~d)" (module-name g) (1+ (length (module-instances g)))) + :args args))) + (push (cons args m) (module-instances g)) + (read-module m args)))))) + +(defun bind-module-params (args) + "An instance's parameters: each type parameter names its argument, and +each procedure parameter its procedure, whose signature must be the +parameter's with the types put in." + (let ((types (loop collect (cons (tok) (ident)) while (accept :|,|)))) + (loop for (tk . name) in types for a in args + do (declare-name (make-obj :name name :kind :type :type a :tok tk))) + (let ((procs (nthcdr (length types) args))) + (loop while (accept :|;|) + do (let ((tk (tok)) (name (ident))) + (expect :|:|) (expect :proc) + (let ((sig (signature nil)) (actual (second (pop procs)))) + (unless (sig-alike-p sig (obj-sig actual)) + (fail-tok tk "~a's signature isn't the parameter ~a's" (obj-name actual) name)) + (setf (gethash name (scope-table *scope*)) actual))))) + (expect :|)|))) diff --git a/sbcl/src/driver.lisp b/sbcl/src/driver.lisp new file mode 100644 index 0000000..babf4f4 --- /dev/null +++ b/sbcl/src/driver.lisp @@ -0,0 +1,133 @@ +;;;; driver.lisp -- the command line, and a program's modules made into +;;;; one executable. +;;;; +;;;; raz [-I dir]... [-o exe] [-S] file.raz +;;;; +;;;; The compiler reads the main module and, through their imports, every +;;;; module it needs, Rt always among them. It then compiles the Lisp it +;;;; made with SBCL, into this very image, and saves the image as the +;;;; executable, to start at the run time's START (rt.lisp). -S also +;;;; writes the Lisp to exe.lisp, for whoever wants to read it. + +(in-package :raz) + +(defparameter *version* "raz-sbcl 0.1.0, report 2026-10.22") + +(defun body-order (roots) + "The modules whose bodies run, in order (section 3): each after those +it imports, in the order of its imports." + (let ((seen '()) (order '())) + (labels ((visit (m) + (unless (member m seen) + (push m seen) + (dolist (imp (reverse (module-imports m))) + (let ((target (if (module-generic (import-target imp)) + (import-instance imp) + (import-target imp)))) + (when target (visit target)))) + (push m order)))) + (mapc #'visit roots)) + (nreverse order))) + +(defun all-modules () + "Every module of the program, each generic module's instances in its place." + (let ((ms '())) + (maphash (lambda (name m) (declare (ignore name)) + (if (module-generic m) + (dolist (i (module-instances m)) (push (cdr i) ms)) + (push m ms))) + *modules*) + ms)) + +(defun main-form (main) + "The program's function: every body, then main; its value the status." + (let* ((obj (gethash "main" (module-exports main))) + (call (cond ((null obj) 0) + ((not (eq (obj-kind obj) :proc)) + (fail-tok (obj-tok obj) "main is a procedure")) + ((and (null (sig-params (obj-sig obj))) (null (sig-results (obj-sig obj)))) + `(progn (,(obj-sym obj)) 0)) + ((and (null (sig-params (obj-sig obj))) + (equal (sig-results (obj-sig obj)) (list (basic "INT")))) + `(,(obj-sym obj))) + (t (fail-tok (obj-tok obj) "main is proc main*; or proc main*: INT;"))))) + `(lambda () + ,@(loop for m in (body-order (list (gethash "Rt" *modules*) main)) + when (module-body m) collect `(,(module-body m))) + ,call))) + +(defun compile-forms (forms) + "Compiles FORMS into this image, quietly." + (handler-bind ((warning #'muffle-warning) + (sb-ext:compiler-note #'muffle-warning)) + (let ((*error-output* (make-broadcast-stream))) + (with-compilation-unit () + (dolist (f forms) + (let ((*package* (find-package :raz))) + (funcall (compile nil `(lambda () ,f))))))))) + +(defun compile-program (file out includes dump) + (let* ((path (probe-file file)) + (name (pathname-name file)) + (*search-dirs* (append (list (directory-namestring (or path #p"./"))) + includes + (list (namestring (merge-pathnames "lib/" (directory-namestring sb-ext:*runtime-pathname*)))))) + (*file* file)) + (unless path (error 'raz-error :text (format nil "~a: no such file" file))) + (setf *universe* (make-universe)) + (let* ((none (make-tok :eof nil 1 1)) + (main (progn (load-module "Rt" none) (load-module name none (namestring path)))) + (modules (all-modules))) + (when (and (some #'module-static modules) (some #'module-uses-c modules)) + (error 'raz-error + :text (format nil "~a: the program uses C (~{~a~^, ~}), which ~{~a~^, ~} doesn't allow by link static" + file (mapcar #'module-name (remove-if-not #'module-uses-c modules)) + (mapcar #'module-name (remove-if-not #'module-static modules))))) + (let ((forms (reverse *forms*)) (entry (let ((*file* file)) (main-form main)))) + (when dump + (with-open-file (s (format nil "~a.lisp" out) :direction :output :if-exists :supersede) + (let ((*package* (find-package :raz)) (*print-circle* t) (*print-right-margin* 110)) + (dolist (f (append forms (list entry))) (pprint f s) (terpri s))))) + (compile-forms forms) + (setf *main* (let ((*package* (find-package :raz))) (compile nil entry))) + (setf *procs* (let ((v (make-array (1+ (length *proc-values*)) :initial-element nil))) + (loop for (h . sym) in *proc-values* do (setf (svref v h) (symbol-function sym))) + v)) + (setf *data-image* (coerce *data* '(simple-array (unsigned-byte 8) (*)))))))) + +(defun usage () + (format *error-output* "usage: raz [-I dir]... [-o exe] [-S] file.raz~%") + (sb-ext:exit :code 2 :abort t)) + +(defun main () + "The compiler's command line." + (let ((args (rest sb-ext:*posix-argv*)) (includes '()) (out nil) (dump nil) (file nil)) + (loop while args + do (let ((a (pop args))) + (cond ((string= a "-I") (unless args (usage)) (setf includes (append includes (list (pop args))))) + ((string= a "-o") (unless args (usage)) (setf out (pop args))) + ((string= a "-S") (setf dump t)) + ((string= a "-Werror")) ; this compiler gives no warnings + ((string= a "--version") (format t "~a~%" *version*) (sb-ext:exit :code 0)) + ((and (> (length a) 1) (char= (char a 0) #\-)) (usage)) + (file (usage)) + (t (setf file a))))) + (unless file (usage)) + (let ((out (or out (pathname-name file)))) + (handler-case + ;; with RAZ_DEBUG set, the compiler's own mistakes come with a backtrace + (handler-bind ((error (lambda (e) + (when (and (sb-ext:posix-getenv "RAZ_DEBUG") (not (typep e 'raz-error))) + (sb-debug:print-backtrace :count 25) + (format *error-output* "~a~%" e) + (sb-ext:exit :code 3 :abort t))))) + (sb-int:with-float-traps-masked (:overflow :invalid :inexact :divide-by-zero :underflow) + (compile-program file out includes dump))) + (raz-error (e) + (format *error-output* "~a~%" (raz-error-text e)) + (sb-ext:exit :code 1 :abort t)) + (error (e) + ;; a mistake of the compiler's own, not the program's + (format *error-output* "raz: internal error: ~a~%" e) + (sb-ext:exit :code 3 :abort t))) + (sb-ext:save-lisp-and-die out :executable t :toplevel #'start :save-runtime-options t)))) diff --git a/sbcl/src/expr.lisp b/sbcl/src/expr.lisp new file mode 100644 index 0000000..d01f4de --- /dev/null +++ b/sbcl/src/expr.lisp @@ -0,0 +1,993 @@ +;;;; expr.lisp -- expressions (report, section 6): each read, checked and +;;;; turned into an ITEM (comp.lisp) holding the Lisp form that computes it. +;;;; +;;;; Constants are folded here, as the compiler must evaluate them +;;;; (section 4); everything else becomes Lisp over the run time's memory +;;;; operations (rt.lisp). + +(in-package :raz) + +;;; Values of items. + +(defun const-item (type val &optional tok) + (make-item :mode :const :type type :val val :tok tok)) + +(defun val-item (type form &optional tok) + (make-item :mode :val :type type :form form :tok tok)) + +(defun const-p (item) (eq (item-mode item) :const)) + +(defun untyped-p (item) + (member (ty-kind (item-type item)) '(:untyped-int :untyped-real))) + +(defun need-value (item) + "ITEM, checked to be a value: not a type, a module, nor a call without one." + (let ((tk (item-tok item))) + (case (item-mode item) + ((:const :var :val) item) + (:literal (fail-tok tk "the literal's type isn't known here")) + (:proc (let ((sig (obj-sig (item-obj item)))) + (val-item (make-proc-type sig) (proc-handle (item-obj item)) tk))) + (:case (build-case item nil)) + (:type (fail-tok tk "the type ~a isn't a value" (type-name (item-type item)))) + (:multi (fail-tok tk "a call with several results isn't one value")) + (:none (fail-tok tk "the procedure has no result")) + (:builtin (fail-tok tk "~a is a built-in procedure, not a value" (item-val item))) + (:module (fail-tok tk "a module isn't a value")) + (t (fail-tok tk "this isn't a value"))))) + +(defun const-form (item) + "The Lisp value of a constant ITEM, as the compiled code holds it." + (let ((ty (item-type item)) (v (item-val item))) + (case (ty-kind ty) + (:string (string-slice v)) + (:untyped-real v) + (t v)))) + +(defun value-form (item) + "The Lisp form of ITEM's value: a scalar's value, an aggregate's address." + (let ((item (need-value item))) + (ecase (item-mode item) + (:const (const-form item)) + (:var (if (aggregate-p (item-type item)) + (item-form item) + `(ld ,(access-kind (item-type item)) ,(item-form item)))) + (:val (item-form item)) + (:literal (fail-tok (item-tok item) "the literal's type isn't known here"))))) + +;;; Assignability (5.10): whether a value of ITEM can go where a TY is +;;; wanted, and the form of it there. + +(defun assign-error (item ty) + "Nil if ITEM can be assigned to a TY, or why not." + (let* ((from (item-type item)) (fk (and from (ty-kind from))) (tk (ty-kind ty))) + (cond ((eq (item-mode item) :literal) (literal-error item ty)) + ((and (eq (item-mode item) :proc)) + (unless (and (eq tk :proc) (sig-alike-p (obj-sig (item-obj item)) (ty-sig ty))) + "the procedure's signature isn't the type's")) + ((eq (item-mode item) :case) + (unless (and (eq tk :variant) (eq (vcase-variant (item-val item)) ty)) + "the case isn't of this variant")) + ((same-type-p from ty) nil) + ((eq fk :untyped-int) + (cond ((not (eq tk :int)) (format nil "an integer constant isn't ~a" (type-name ty))) + ((not (fits-p (item-val item) ty)) + (format nil "~d doesn't fit ~a" (item-val item) (type-name ty))))) + ((eq fk :untyped-real) (unless (eq tk :real) (format nil "a real constant isn't ~a" (type-name ty)))) + ((eq fk :nil) (unless (nil-able-p ty) (format nil "nil isn't ~a" (type-name ty)))) + ((eq fk :string) + (unless (or (and (eq tk :slice) (same-type-p (ty-elem ty) (basic "U8"))) + (and (eq tk :ptr) (same-type-p (ptr-base ty) (basic "U8")) (not (ty-vol ty))) + (and (eq tk :array) (same-type-p (ty-elem ty) (basic "U8")) + (>= (ty-len ty) (ty-len from)))) + (format nil "a string isn't ~a" (type-name ty)))) + ((and (eq fk :ptr) (eq tk :ptr) (ty-vol ty) (not (ty-vol from)) + (same-type-p (ptr-base from) (ptr-base ty))) + nil) + ((and (eq fk :array) (eq tk :slice) (same-type-p (ty-elem from) (ty-elem ty))) + (cond ((eq (item-ro item) :export) "another module's array can't be used as a slice") + ((item-vol item) "a volatile array can't be used as a slice") + ((item-noaddr item) "a field of a packed record has no address"))) + ((and (eq fk :int) (eq tk :int) + (or (and (eq from (basic "INT")) (eq ty (basic "I64"))) + (and (eq from (basic "UINT")) (eq ty (basic "U64"))))) + nil) + (t (format nil "~a isn't ~a" (type-name from) (type-name ty)))))) + +(defun coerce-item (item ty &optional (tok (item-tok item))) + "The form of ITEM's value as a TY, which it must be assignable to." + (unless (member (item-mode item) '(:literal :proc :case)) + (need-value item)) + (let ((why (assign-error item ty))) + (when why (fail-tok tok "~a" why))) + (when (and (item-vol item) (aggregate-p ty)) + (fail-tok tok "a whole record or array can't be copied through a volatile pointer")) + (let ((from (item-type item))) + (cond ((eq (item-mode item) :literal) (build-literal item ty)) + ((eq (item-mode item) :case) (value-form (build-case item nil))) + ((eq (item-mode item) :proc) (proc-handle (item-obj item))) + ((is from :untyped-real) (if (= (ty-bits ty) 32) (coerce (item-val item) 'single-float) (item-val item))) + ((is from :nil) 0) + ((is from :string) + (let ((bytes (item-val item))) + (ecase (ty-kind ty) + (:slice (string-slice bytes)) + (:ptr (string-address bytes)) + (:array (let ((padded (make-array (ty-len ty) :element-type '(unsigned-byte 8) :initial-element 0))) + (replace padded bytes) + ;; a padded copy, the rest zero, to copy from + (let ((a (data-alloc (ty-len ty) 1))) (data-put a padded) a)))))) + ((and (is from :array) (is ty :slice)) + (let ((tmp (temp ty))) + `(slice ,tmp ,(item-form item) ,(ty-len from)))) + (t (value-form item))))) + +;;; Storing: the form that puts ITEM, as a TY, at ADDR. +(defun store-form (addr ty item &optional (tok (item-tok item))) + (let ((v (coerce-item item ty tok))) + (if (aggregate-p ty) + `(move ,addr ,v ,(ty-size ty)) + `(st ,(access-kind ty) ,addr ,v)))) + +;;; Literals (6.5), built once their type is known. + +(defun literal-error (item ty) + (destructuring-bind (kind elems) (item-val item) + (ecase kind + (:array (cond ((not (member (ty-kind ty) '(:array :slice))) + (format nil "an array literal isn't ~a" (type-name ty))) + ((and (is ty :array) (/= (length elems) (ty-len ty))) + (format nil "the literal has ~d elements, not ~d" (length elems) (ty-len ty))) + (t (loop for e in elems thereis (assign-error e (ty-elem ty)))))) + (:record (if (not (is ty :record)) + (format nil "a record literal isn't ~a" (type-name ty)) + (loop for (name . e) in elems + for f = (find-field ty name (item-tok e)) + thereis (assign-error e (field-type f))))) + (:set (if (not (is ty :set)) + (format nil "a set literal isn't ~a" (type-name ty)) + (loop for e in elems thereis (assign-error e (ty-enum ty))))) + (:empty (unless (member (ty-kind ty) '(:record :set)) + (format nil "{} isn't ~a" (type-name ty))))))) + +(defun build-literal (item ty) + "The form of the literal ITEM's value as a TY: the address of a +temporary holding it, or a set's bits." + (destructuring-bind (kind elems) (item-val item) + (cond ((is ty :set) + (let ((consts (remove-if-not #'const-p elems)) (vars (remove-if #'const-p elems))) + (let ((bits (reduce #'logior (mapcar (lambda (e) (ash 1 (item-val e))) consts) :initial-value 0))) + (if vars + `(logior ,bits ,@(mapcar (lambda (e) `(ash 1 ,(value-form e))) vars)) + bits)))) + ((is ty :slice) + ;; a hidden array of the procedure (6.5), and a slice of it + (let* ((arr (make-array-type (max 1 (length elems)) (ty-elem ty))) + (a (build-literal item (if elems arr (make-array-type 1 (ty-elem ty))))) + (s (temp ty))) + `(slice ,s ,a ,(length elems)))) + (t + (let ((tmp (temp ty)) (es (ty-size (or (ty-elem ty) ty)))) + `(let ((at ,tmp)) + (zero at ,(ty-size ty)) + ,@(if (eq kind :array) + (loop for e in elems for i from 0 + collect (store-form `(+ at ,(* i es)) (ty-elem ty) e)) + (let ((seen '())) + (loop for (name . e) in elems + for f = (find-field ty name (item-tok e)) + do (when (member name seen :test #'string=) + (fail-tok (item-tok e) "the field ~a is given twice" name)) + (push name seen) + collect (store-form `(+ at ,(field-offset f)) (field-type f) e)))) + at)))))) + +(defun find-field (ty name tok) + (let ((f (find name (ty-fields ty) :key #'field-name :test #'string=))) + (unless f (fail-tok tok "~a has no field ~a" (type-name ty) name)) + (unless (or (field-exported f) (eq (ty-module ty) *module*)) + (fail-tok tok "the field ~a isn't exported" name)) + f)) + +;;; A variant's case, built by calling it (5.6): a temporary holding its +;;; tag and its fields. +(defun build-case (item args) + (let* ((c (item-val item)) (vty (vcase-variant c)) (fields (vcase-fields c)) + (tok (item-tok item))) + (when (and (null args) fields) + (fail-tok tok "the case ~a needs its fields" (vcase-name c))) + (unless (= (length args) (length fields)) + (fail-tok tok "the case ~a has ~d fields, not ~d" (vcase-name c) (length fields) (length args))) + (let ((tmp (temp vty))) + (val-item vty `(let ((at ,tmp)) + (zero at ,(ty-size vty)) + (st :i64 at ,(vcase-index c)) + ,@(loop for f in fields for a in args + collect (store-form `(+ at ,(field-offset f)) (field-type f) a)) + at) + tok)))) + +;;; Expressions, by the grammar of section 6. + +(defun expression () + (let ((x (conjunct))) + (loop while (eq (kind) :or) + do (let* ((tk (next-tok)) (y (conjunct))) + (setf x (logical :or x y tk)))) + x)) + +(defun conjunct () + (let ((x (relation))) + (loop while (eq (kind) :and) + do (let* ((tk (next-tok)) (y (relation))) + (setf x (logical :and x y tk)))) + x)) + +(defun logical (op x y tk) + (dolist (i (list x y)) + (unless (is (item-type (need-value i)) :bool) + (fail-tok tk "~(~a~) is for BOOLs only" op))) + (if (and (const-p x) (const-p y)) + (const-item (basic "BOOL") (if (eq op :and) (and (item-val x) (item-val y)) (or (item-val x) (item-val y))) tk) + (val-item (basic "BOOL") `(,(if (eq op :and) 'and 'or) ,(value-form x) ,(value-form y)) tk))) + +(defun relation () + (let ((x (simple-expr))) + (if (member (kind) '(:= :|#| :< :<= :> :>= :in)) + (let* ((tk (next-tok)) (y (simple-expr))) + (compare (tok-kind tk) x y tk)) + x))) + +(defun simple-expr () + (let ((x (if (eq (kind) :-) + (let ((tk (next-tok))) (negate (term) tk)) + (term)))) + (loop while (member (kind) '(:+ :- :|\|| :xor)) + do (let* ((tk (next-tok)) (y (term))) + (setf x (arith (tok-kind tk) x y tk)))) + x)) + +(defun term () + (let ((x (factor))) + (loop while (member (kind) '(:* :/ :div :mod :& :shl :shr)) + do (let* ((tk (next-tok)) (y (factor))) + (setf x (arith (tok-kind tk) x y tk)))) + x)) + +(defun factor () + (let ((tk (tok))) + (case (kind) + (:int (next-tok) + (const-item (if (> (tok-val tk) (int-max (basic "I64"))) (basic "U64") *untyped-int*) (tok-val tk) tk)) + (:char (next-tok) (const-item *untyped-int* (tok-val tk) tk)) + (:real (next-tok) (const-item *untyped-real* (tok-val tk) tk)) + (:string (next-tok) (const-item (string-type (length (tok-val tk))) (tok-val tk) tk)) + (:|(| (next-tok) (prog1 (expression) (expect :|)|))) + (:not (next-tok) + (let ((x (need-value (factor)))) + (unless (is (item-type x) :bool) (fail-tok tk "not is for BOOLs only")) + (if (const-p x) + (const-item (item-type x) (not (item-val x)) tk) + (val-item (item-type x) `(not ,(value-form x)) tk)))) + (:~ (next-tok) + (let* ((x (need-value (factor))) (ty (item-type x))) + (unless (member (ty-kind ty) '(:int :untyped-int)) (fail-tok tk "~~ is for integers only")) + (cond ((and (const-p x) (is ty :untyped-int)) (const-item ty (lognot (item-val x)) tk)) + ((const-p x) (const-item ty (wrap-int (lognot (item-val x)) ty) tk)) + (t (val-item ty (wrap-form ty `(lognot ,(value-form x))) tk))))) + (:|[| (next-tok) + (let ((elems '())) + (unless (eq (kind) :|]|) + (loop (push (expression) elems) (unless (accept :|,|) (return)))) + (expect :|]|) + (make-item :mode :literal :val (list :array (nreverse elems)) :tok tk))) + (:{ (next-tok) (brace-literal tk)) + (:^ (next-tok) + (let ((ty (pointer-type-rest))) + (expect :|(|) + ;; selectors may follow, as in ^T(x)^ (section 6) + (selectors (prog1 (convert ty (expression) tk) (expect :|)|))))) + (:try (next-tok) (try-item tk)) + (:ident (designator)) + (t (fail-here "an expression expected, not ~a" (describe-tok tk)))))) + +(defun brace-literal (tk) + "{...}: a record literal if its first element names a field, else a set." + (cond ((accept :}) + (make-item :mode :literal :val (list :empty nil) :tok tk)) + ((and (eq (kind) :ident) (eq (kind 1) :|:|)) + (let ((fields '())) + (loop (let ((ftk (tok)) (name (ident))) + (expect :|:|) + (let ((e (expression))) (setf (item-tok e) (or (item-tok e) ftk)) (push (cons name e) fields))) + (unless (accept :|,|) (return))) + (expect :}) + (make-item :mode :literal :val (list :record (nreverse fields)) :tok tk))) + (t + (let ((elems '())) + (loop (push (need-value (expression)) elems) (unless (accept :|,|) (return))) + (expect :}) + (setf elems (nreverse elems)) + ;; the set's type is its first name's enumeration's set (6.6) + (let ((enum (item-type (first elems)))) + (unless (is enum :enum) (fail-tok tk "a set's elements are names of an enumeration")) + (dolist (e elems) + (unless (same-type-p (item-type e) enum) + (fail-tok (item-tok e) "the set's elements are of two enumerations"))) + (let ((item (make-item :mode :literal :val (list :set elems) :tok tk)) + (sty (set-type-of enum))) + (if (every #'const-p elems) + (const-item sty (build-literal item sty) tk) + (val-item sty (build-literal item sty) tk)))))))) + +(defun set-type-of (enum) + "The anonymous set type of ENUM: alike wherever it is made." + (make-set-type enum)) + +;;; Integers and reals: the operands' common type (6.1, 6.3). + +(defun wrap-form (ty form) + (if (ty-signed ty) + `(sb-c::mask-signed-field ,(ty-bits ty) ,form) + `(ldb (byte ,(ty-bits ty) 0) ,form))) + +(defun unify (x y tk) + "The type both X and Y have, an untyped constant taking the other's." + (let ((a (item-type x)) (b (item-type y))) + (flet ((takes (c ty) ; constant C taking type TY + (let ((why (assign-error c ty))) + (when why (fail-tok tk "~a" why))))) + (cond ((and (untyped-p x) (untyped-p y)) + (unless (eq a b) (fail-tok tk "an integer and a real don't mix")) + a) + ((untyped-p x) (takes x b) b) + ((untyped-p y) (takes y a) a) + ((same-type-p a b) a) + ((and (is a :literal) nil)) + (t (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b))))))) + +(defun typed-const (item ty) + "The value of constant ITEM as a TY." + (let ((v (item-val item))) + (if (and (is ty :real) (= (ty-bits ty) 32) (typep v 'double-float)) (coerce v 'single-float) v))) + +(defun check-const-int (v tk) + (unless (<= (- (expt 2 63)) v (1- (expt 2 63))) + (fail-tok tk "the constant ~d is beyond the I64s" v)) + v) + +(defun arith (op x y tk) + "X op Y for the adding and multiplying operators." + (setf x (need-value x) y (need-value y)) + (let ((a (item-type x)) (b (item-type y))) + (cond + ;; strings join (section 4) + ((and (eq op :+) (is a :string) (is b :string) (const-p x) (const-p y)) + (let ((s (concatenate '(vector (unsigned-byte 8)) (item-val x) (item-val y)))) + (const-item (string-type (length s)) (coerce s '(simple-array (unsigned-byte 8) (*))) tk))) + ;; pointers move by elements (6.4) + ((and (is a :ptr) (member op '(:+ :-)) (member (ty-kind b) '(:int :untyped-int))) + (val-item a `(ldb (byte 64 0) (,(if (eq op :+) '+ '-) ,(value-form x) + (* ,(value-form y) ,(ty-size (ptr-base a))))) + tk)) + ((and (is a :ptr) (eq op :-) (is b :ptr)) + (unless (same-type-p a b) (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b))) + (val-item (basic "INT") `(values (truncate (sb-c::mask-signed-field 64 (- ,(value-form x) ,(value-form y))) + ,(max 1 (ty-size (ptr-base a))))) + tk)) + ((member op '(:shl :shr)) (shift op x y tk)) + (t + (let ((ty (unify x y tk))) + (case (ty-kind ty) + ((:int :untyped-int) (int-arith op x y ty tk)) + ((:real :untyped-real) (real-arith op x y ty tk)) + (:set (set-arith op x y ty tk)) + (t (fail-tok tk "~(~a~) isn't defined on ~a" op (type-name ty))))))))) + +(defun int-arith (op x y ty tk) + (unless (member op '(:+ :- :* :div :mod :& :|\|| :xor)) + (fail-tok tk "~(~a~) isn't defined on integers~@[; div divides them~]" op (eq op :/))) + (let ((lisp-op (ecase op (:+ '+) (:- '-) (:* '*) (:& 'logand) (:|\|| 'logior) (:xor 'logxor) + (:div 'div) (:mod 'mod)))) + (if (and (const-p x) (const-p y)) + (let* ((a (item-val x)) (b (item-val y)) + (v (case lisp-op + ((div mod) + (when (= b 0) (fail-tok tk "a division by zero in a constant")) + (when (and (is ty :int) (ty-signed ty) (= b -1) (= a (int-min ty))) + (fail-tok tk "the smallest ~a divided by -1 in a constant" (type-name ty))) + (if (eq lisp-op 'mod) (rem a b) (values (truncate a b)))) + (t (funcall lisp-op a b))))) + (const-item ty (if (is ty :untyped-int) (check-const-int v tk) (wrap-int v ty)) tk)) + (let* ((ty (if (is ty :untyped-int) (basic "INT") ty)) + (a (coerce-item x ty tk)) (b (coerce-item y ty tk))) + (val-item ty + (if (member lisp-op '(div mod)) + `(divide ,a ,b ,(ty-bits ty) ,(ty-signed ty) ,(where tk) ,(eq lisp-op 'mod)) + (wrap-form ty `(,lisp-op ,a ,b))) + tk))))) + +(defun real-arith (op x y ty tk) + (unless (member op '(:+ :- :* :/)) + (fail-tok tk "~(~a~) isn't defined on reals" op)) + (let ((lisp-op (ecase op (:+ '+) (:- '-) (:* '*) (:/ '/)))) + (if (and (const-p x) (const-p y)) + (const-item ty (funcall lisp-op (typed-const x ty) (typed-const y ty)) tk) + (val-item ty `(,lisp-op ,(coerce-item x ty tk) ,(coerce-item y ty tk)) tk)))) + +(defun set-arith (op x y ty tk) + (let ((f (case op (:+ 'logior) (:* 'logand) (:- 'logandc2) + (t (fail-tok tk "~(~a~) isn't defined on sets" op))))) + (if (and (const-p x) (const-p y)) + (const-item ty (funcall f (item-val x) (item-val y)) tk) + (val-item ty `(,f ,(value-form x) ,(value-form y)) tk)))) + +(defun shift (op x y tk) + ;; by y modulo the width of x's type; an untyped x stays untyped (6.1) + (let ((a (item-type x)) (b (item-type y))) + (unless (member (ty-kind b) '(:int :untyped-int)) (fail-tok tk "a shift's count is an integer")) + (unless (member (ty-kind a) '(:int :untyped-int)) (fail-tok tk "~(~a~) is for integers" op)) + (when (and (is a :untyped-int) (not (const-p y))) + (setf a (basic "INT"))) + (cond ((and (is a :untyped-int) (const-p x)) + (let ((n (item-val y))) + (when (< n 0) (fail-tok tk "a negative shift of a constant")) + (const-item a (check-const-int (if (eq op :shl) (ash (item-val x) (min n 64)) (ash (item-val x) (- n))) tk) tk))) + ((and (const-p x) (const-p y)) + (let ((n (mod (item-val y) (ty-bits a)))) + (const-item a (wrap-int (ash (item-val x) (if (eq op :shl) n (- n))) a) tk))) + (t (let ((n `(mod ,(value-form y) ,(ty-bits a)))) + (val-item a (if (eq op :shl) + (wrap-form a `(ash ,(coerce-item x a tk) ,n)) + `(ash ,(coerce-item x a tk) (- ,n))) + tk)))))) + +(defun negate (x tk) + (let* ((x (need-value x)) (ty (item-type x))) + (case (ty-kind ty) + (:untyped-int (if (const-p x) (const-item ty (- (item-val x)) tk) (fail-tok tk "?"))) + (:untyped-real (const-item ty (- (item-val x)) tk)) + (:int (if (const-p x) + (const-item ty (wrap-int (- (item-val x)) ty) tk) + (val-item ty (wrap-form ty `(- ,(value-form x))) tk))) + (:real (if (const-p x) + (const-item ty (- (item-val x)) tk) + (val-item ty `(- ,(value-form x)) tk))) + (t (fail-tok tk "- isn't defined on ~a" (type-name ty)))))) + +;;; Relations. + +(defun sequence-parts (item) + "For an array, a slice or a string: the forms of its first element's +address and its length, and its element type." + (let ((ty (item-type item))) + (ecase (ty-kind ty) + (:string (values (string-address (item-val item)) (length (item-val item)) (basic "U8"))) + (:array (values (value-form item) (ty-len ty) (ty-elem ty))) + (:slice (let ((s (var-sym "S"))) + (values `(ld :u64 ,s) `(ld :i64 (+ ,s 8)) (ty-elem ty) s (value-form item))))))) + +(defun compare (op x y tk) + (when (eq op :in) (return-from compare (membership x y tk))) + ;; a literal or nil takes the other side's type + (when (eq (item-mode x) :literal) (rotatef x y) (setf op (case op (:< :>) (:> :<) (:<= :>=) (:>= :<=) (t op)))) + (setf x (need-value x)) + (when (eq (item-mode y) :literal) + (setf y (val-item (item-type x) (coerce-item y (item-type x) tk) tk))) + (setf y (need-value y)) + (let ((a (item-type x)) (b (item-type y)) (bool (basic "BOOL"))) + (cond + ((and (member (ty-kind a) '(:array :slice :string)) (member (ty-kind b) '(:array :slice :string))) + (sequence-compare op x y tk)) + ((or (is a :nil) (is b :nil)) + (let ((other (if (is a :nil) b a))) + (unless (or (nil-able-p other) (is other :nil)) (fail-tok tk "nil isn't ~a" (type-name other))) + (unless (member op '(:= :|#|)) (fail-tok tk "~(~a~) doesn't compare nil" op)) + (val-item bool `(,(if (eq op :=) '= '/=) ,(value-form x) ,(value-form y)) tk))) + (t + (let* ((ty (unify x y tk)) (k (ty-kind ty))) + (unless (member k '(:int :untyped-int :real :untyped-real :bool :enum :set :ptr :proc :error)) + (fail-tok tk "~a doesn't compare" (type-name ty))) + (when (and (member k '(:bool :proc :error)) (not (member op '(:= :|#|)))) + (fail-tok tk "~a compares with = and # only" (type-name ty))) + (when (and (eq k :set) (member op '(:< :>))) + (fail-tok tk "sets compare with =, #, <= and >=")) + (let ((f (if (eq k :set) + (ecase op (:= '=) (:|#| '/=) (:<= 'subset) (:>= 'superset)) + (ecase op (:= (if (eq k :bool) 'eq '=)) (:|#| (if (eq k :bool) 'neq '/=)) + (:< '<) (:<= '<=) (:> '>) (:>= '>=))))) + (if (and (const-p x) (const-p y)) + (const-item bool (funcall f (typed-const x ty) (typed-const y ty)) tk) + (val-item bool `(,f ,(coerce-item x ty tk) ,(coerce-item y ty tk)) tk)))))))) + +(defun neq (a b) (not (eq a b))) +(defun subset (a b) (= 0 (logandc2 a b))) +(defun superset (a b) (= 0 (logandc2 b a))) + +(defun sequence-compare (op x y tk) + ;; equal lengths and equal elements, for elements that compare by bytes (6.5) + (unless (member op '(:= :|#|)) (fail-tok tk "arrays and strings compare with = and # only")) + (multiple-value-bind (pa la ea sa fa) (sequence-parts x) + (multiple-value-bind (pb lb eb sb fb) (sequence-parts y) + (unless (same-type-p ea eb) (fail-tok tk "the two sides' elements are of two types")) + (unless (bytewise-comparable-p ea) + (fail-tok tk "arrays of ~a don't compare" (type-name ea))) + (when (or (item-vol x) (item-vol y)) (fail-tok tk "a volatile array doesn't compare")) + (let ((form `(let* (,@(when sa `((,sa ,fa))) ,@(when sb `((,sb ,fb))) + (la ,la) (lb ,lb)) + (and (= la lb) (bytes-equal ,pa ,pb (* la ,(ty-size ea))))))) + (val-item (basic "BOOL") (if (eq op :=) form `(not ,form)) tk))))) + +(defun membership (x y tk) + (setf x (need-value x) y (need-value y)) + (unless (and (is (item-type y) :set) (same-type-p (item-type x) (ty-enum (item-type y)))) + (fail-tok tk "in takes a name of an enumeration and a set of it")) + (if (and (const-p x) (const-p y)) + (const-item (basic "BOOL") (logbitp (item-val x) (item-val y)) tk) + (val-item (basic "BOOL") `(logbitp ,(value-form x) ,(value-form y)) tk))) + +;;; Designators: a name and its selectors (section 6). + +(defun qualified-obj () + "The object a QualIdent names, a module's export if it starts with a module." + (let* ((tk (tok)) (name (ident)) (obj (lookup name))) + (unless obj (fail-tok tk "~a isn't declared" name)) + (if (eq (obj-kind obj) :module) + (progn + (expect :|.|) + (let* ((mtk (tok)) (member (ident)) (m (import-module (obj-val obj) tk)) + (o (gethash member (module-exports m)))) + (unless o + (fail-tok mtk "~a has no export ~a" (obj-name obj) member)) + (values o mtk))) + (values obj tk)))) + +(defun obj-item (obj tk) + "The item of a name." + (ecase (obj-kind obj) + (:const (if (aggregate-p (obj-type obj)) + (if (is (obj-type obj) :string) + (const-item (obj-type obj) (obj-val obj) tk) + (make-item :mode :var :type (obj-type obj) :form (obj-val obj) :ro :const :tok tk)) + (const-item (obj-type obj) (obj-val obj) tk))) + (:type (make-item :mode :type :type (obj-type obj) :tok tk)) + (:var (make-item :mode :var :type (obj-type obj) :form (var-address obj) :tok tk + :ro (when (and (obj-module obj) (not (eq (obj-module obj) *module*))) :export))) + (:proc (make-item :mode :proc :obj obj :tok tk)) + (:builtin (make-item :mode :builtin :val (obj-name obj) :tok tk)) + (:case (make-item :mode :case :val (obj-val obj) :type (vcase-variant (obj-val obj)) :tok tk)))) + +(defun var-address (obj) + (let ((w (obj-where obj))) + (ecase (first w) + (:global (second w)) + (:local `(+ fp ,(second w))) + (:var-param `(ld :u64 (+ fp ,(second w)))) + (:at (second w)) + (:extern `(sb-sys:find-foreign-symbol-address ,(second w)))))) + +(defun designator () + (multiple-value-bind (obj tk) (qualified-obj) + (selectors (obj-item obj tk)))) + +(defun selectors (item) + (loop + (let ((tk (tok))) + (case (kind) + (:|.| (next-tok) (setf item (select-field item (ident) tk))) + (:^ (next-tok) (setf item (dereference item tk))) + (:|[| (next-tok) (setf item (index item tk))) + (:|(| (setf item (call item tk))) + (t (return item)))))) + +(defun select-field (item name tk) + (let* ((item (need-value item)) (ty (item-type item))) + (case (ty-kind ty) + (:record + (let ((f (find-field ty name tk))) + (make-item :mode :var :type (field-type f) :tok tk + :form `(+ ,(value-form item) ,(field-offset f)) + :ro (or (item-ro item) (and (eq (item-mode item) :val) :value)) + :vol (item-vol item) + :noaddr (or (item-noaddr item) + (and (ty-packed ty) (> (ty-align (field-type f)) 1)))))) + (:ptr (fail-tok tk "a pointer's fields are p^.~a" name)) + (:variant (fail-tok tk "a variant's fields are read by match")) + (t (fail-tok tk "~a has no fields" (type-name ty)))))) + +(defun dereference (item tk) + (let* ((item (need-value item)) (ty (item-type item))) + (unless (is ty :ptr) (fail-tok tk "^ follows a pointer, not ~a" (type-name ty))) + (make-item :mode :var :type (ptr-base ty) :form (value-form item) :vol (ty-vol ty) :tok tk))) + +(defun integer-operand (tk what) + "An expression of any integer type (6.1): the form of its value." + (let ((x (need-value (expression)))) + (unless (member (ty-kind (item-type x)) '(:int :untyped-int)) + (fail-tok tk "~a is an integer, not ~a" what (type-name (item-type x)))) + (value-form x))) + +(defun index (item tk) + "a[i] or a[lo..hi]; the `[` is read." + (let* ((item (need-value item)) (ty (item-type item)) (check (not (module-check-off *module*)))) + (when (is ty :string) + ;; a string constant is indexed and sliced as an array of U8 + (setf ty (make-array-type (ty-len ty) (basic "U8")) + item (make-item :mode :var :type ty :form (string-address (item-val item)) :ro :const :tok tk))) + (unless (member (ty-kind ty) '(:array :slice :ptr)) + (fail-tok tk "~a can't be indexed" (type-name ty))) + (when (and (is ty :ptr) (is (ptr-base ty) :array)) + (fail-tok tk "a pointer to an array is indexed as p^[i]")) + (let* ((elem (if (is ty :ptr) (ptr-base ty) (ty-elem ty))) + (size (ty-size elem)) + (base (var-sym "A")) (len (var-sym "N")) + (lo (integer-operand tk "an index"))) + (multiple-value-bind (base-form len-form) + (ecase (ty-kind ty) + (:array (values (value-form item) (ty-len ty))) + (:slice (values `(ld :u64 ,(value-form item)) `(ld :i64 (+ ,(value-form item) 8)))) + (:ptr (values (value-form item) nil))) + (if (accept :..) + (let ((hi (integer-operand tk "a slice's bound")) (h (var-sym "H")) (l (var-sym "L")) + (sty (make-slice-type elem))) + (expect :|]|) + (when (is ty :array) + (case (item-ro item) + (:export (fail-tok tk "another module's array can't be sliced"))) + (when (item-vol item) (fail-tok tk "a volatile array can't be sliced"))) + (when (and (item-noaddr item) (> (ty-align elem) 1)) + (fail-tok tk "a field of a packed record has no address to slice")) + (val-item sty + `(let* ((,base ,(if (is ty :slice) (value-form item) base-form)) + (,l ,lo) (,h ,hi) + ,@(when (is ty :slice) `((,len (ld :i64 (+ ,base 8))) (,base (ld :u64 ,base))))) + ,(when (or check (is ty :ptr)) + `(check-slice ,l ,h ,(cond ((is ty :ptr) nil) ((is ty :slice) len) (t len-form)) ,(where tk))) + (slice ,(temp sty) (ldb (byte 64 0) (+ ,base (* ,l ,size))) (- ,h ,l))) + tk)) + (progn + (expect :|]|) + (make-item :mode :var :type elem :tok tk + :form (cond ((is ty :ptr) `(ldb (byte 64 0) (+ ,base-form (* ,lo ,size)))) + ((is ty :slice) + `(let ((,base ,(value-form item))) + (+ (ld :u64 ,base) + (* ,(if check `(check-index ,lo (ld :i64 (+ ,base 8)) ,(where tk)) lo) + ,size)))) + (t `(+ ,base-form (* ,(if check `(check-index ,lo ,len-form ,(where tk)) lo) ,size)))) + :ro (if (is ty :array) (item-ro item) nil) + :vol (and (is ty :array) (item-vol item)) + :noaddr (and (is ty :array) (item-noaddr item))))))))) + +;;; Conversions (6.7). + +(defun convert (ty x tk) + (let* ((x (need-value x)) (from (item-type x)) (fk (ty-kind from)) (tk2 (ty-kind ty))) + (flet ((bad () (fail-tok tk "~a doesn't convert to ~a" (type-name from) (type-name ty))) + (result (const form) (if (const-p x) (const-item ty const tk) (val-item ty form tk)))) + (let ((v (unless (const-p x) (value-form x))) (c (when (const-p x) (item-val x)))) + (case tk2 + (:int + (case fk + ((:int :untyped-int) (result (and c (wrap-int c ty)) (wrap-form ty v))) + ((:real :untyped-real) + (result (and c (real-to-int c (ty-bits ty) (ty-signed ty))) + `(real-to-int ,v ,(ty-bits ty) ,(ty-signed ty)))) + ((:enum :set) (result c v)) + ((:ptr :proc) + (unless (member (ty-name ty) '("INT" "UINT") :test #'equal) (bad)) + (val-item ty (if (ty-signed ty) `(sb-c::mask-signed-field 64 ,v) v) tk)) + (t (bad)))) + (:real + (let ((lisp-ty (if (= (ty-bits ty) 32) 'single-float 'double-float))) + (case fk + ((:int :untyped-int :real :untyped-real) (result (and c (coerce c lisp-ty)) `(coerce ,v ',lisp-ty))) + (t (bad))))) + (:enum + (unless (member fk '(:int :untyped-int)) (if (same-type-p from ty) (return-from convert x) (bad))) + (let ((n (length (ty-names ty)))) + (when (and c (not (< -1 c n))) (fail-tok tk "~d is no position of the enumeration" c)) + (result c `(check-enum ,v ,n ,(where tk))))) + (:set + (unless (member fk '(:int :untyped-int)) (if (same-type-p from ty) (return-from convert x) (bad))) + (result (and c (ldb (byte (* 8 (ty-size ty)) 0) c)) `(ldb (byte ,(* 8 (ty-size ty)) 0) ,v))) + ((:ptr :proc) + (cond ((member fk '(:ptr :proc)) (val-item ty (value-form x) tk)) + ((or (eq fk :untyped-int) + (and (eq fk :int) (member (ty-name from) '("INT" "UINT") :test #'equal))) + (val-item ty `(ldb (byte 64 0) ,(value-form x)) tk)) + ((eq fk :nil) (val-item ty 0 tk)) + (t (bad)))) + (:bool (if (eq fk :bool) x (bad))) + (t (bad))))))) + +;;; Calls (section 8): of procedures, procedure values, built-ins, +;;; conversions and variants' cases. + +(defun call (item tk) + "ITEM applied to the arguments that follow, `(` and all." + (case (item-mode item) + (:type (next-tok) + (prog1 (convert (item-type item) (expression) tk) (expect :|)|))) + (:builtin (next-tok) (builtin (item-val item) tk)) + (:case (next-tok) + (let ((args (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))))) + (expect :|)|) + (when (null args) (fail-tok tk "() after a case without fields")) + (build-case item args))) + (:proc (call-proc (item-obj item) nil tk)) + (t (let ((v (need-value item))) + (unless (is (item-type v) :proc) (fail-tok tk "~a isn't a procedure" (type-name (item-type v)))) + (call-proc nil v tk))))) + +(defun read-args () + "The arguments in parentheses, if there are parentheses." + (when (accept :|(|) + (prog1 (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))) + (expect :|)|)))) + +(defun arg-forms (sig args tk) + "The forms passing ARGS to the parameters of SIG." + (let ((params (sig-params sig))) + (when (or (< (length args) (length params)) + (and (> (length args) (length params)) (not (sig-varargs sig)))) + (fail-tok tk "~d arguments for ~d parameters" (length args) (length params))) + (loop for a in args for i from 0 + for p = (nth i params) + collect (cond ((null p) (vararg-form a)) + ((third p) (var-arg-form a (second p))) + (t (coerce-item a (second p) (item-tok a))))))) + +(defun var-arg-form (a ty) + "A `var` argument: the address of a variable of exactly the type." + (let ((tk (item-tok a))) + (unless (eq (item-mode a) :var) (fail-tok tk "a var parameter takes a variable")) + (check-writable a tk "passed as a var argument") + (when (item-noaddr a) (fail-tok tk "a field of a packed record has no address")) + (unless (same-type-p (item-type a) ty) + (fail-tok tk "a var parameter of ~a takes a variable of it, not ~a" (type-name ty) (type-name (item-type a)))) + (item-form a))) + +(defun check-writable (a tk what) + (when (item-vol a) (fail-tok tk "a volatile variable can't be ~a" what)) + (case (item-ro a) + (:export (fail-tok tk "another module's variable can't be ~a" what)) + (:const (fail-tok tk "a constant can't be ~a" what)) + (:value (fail-tok tk "a part of a value can't be ~a" what)))) + +(defun vararg-form (a) + "An argument past an extern's parameters (section 9): as C takes it." + (let* ((a (need-value a)) (ty (item-type a)) (tk (item-tok a))) + (case (ty-kind ty) + (:untyped-int (list 'sb-alien:long (item-val a))) + (:untyped-real (list 'double-float (item-val a))) + (:string (list 'sb-alien:unsigned-long (string-address (item-val a)))) + (:real (when (= (ty-bits ty) 32) (fail-tok tk "C takes no F32 past the parameters: F64(x)")) + (list 'double-float (value-form a))) + ((:int :bool :ptr :proc) (list (alien-type ty) (c-value-form ty (value-form a)))) + (t (fail-tok tk "~a doesn't go to C" (type-name ty)))))) + +(defun alien-type (ty) + (ecase (ty-kind ty) + (:int `(,(if (ty-signed ty) 'sb-alien:signed 'sb-alien:unsigned) ,(ty-bits ty))) + (:bool '(sb-alien:unsigned 8)) + (:real (if (= (ty-bits ty) 32) 'single-float 'double-float)) + ((:ptr :proc :error) 'sb-alien:unsigned-long))) + +(defun c-value-form (ty form) + "FORM's value as C takes it: a BOOL as 0 or 1, a procedure as the +address of a C function that calls it." + (case (ty-kind ty) + (:bool `(if ,form 1 0)) + (:proc (callback-form (ty-sig ty) form)) + (t form))) + +(defun callback-form (sig form) + "The address of a C function calling the procedure value FORM, made by +SBCL the first time that value goes to C (section 9)." + (let* ((params (sig-params sig)) (result (first (sig-results sig))) + (args (loop for p in params collect (var-sym "A")))) + `(c-callback ,form + (lambda (fn) + (sb-alien::alien-sap + (sb-alien::alien-lambda ,(if result (alien-type result) 'sb-alien:void) + ,(loop for a in args for p in params collect (list a (alien-type (second p)))) + (in-raz-thread + ,(let ((call `(funcall fn ,@(loop for a in args for p in params + collect (if (is (second p) :bool) `(/= 0 ,a) a))))) + (cond ((null result) `(progn ,call (values))) + ((is result :bool) `(if ,call 1 0)) + (t call)))))))))) + +(defun call-proc (obj value tk) + "A call of procedure OBJ, or of the procedure VALUE: an item of its results." + (let* ((sig (if obj (obj-sig obj) (ty-sig (item-type value)))) + (fn (when value (value-form value))) + (args (read-args)) + (forms (arg-forms sig args tk)) + (results (sig-results sig)) + (dests (loop for r in results when (aggregate-p r) collect (temp r))) + (form (cond ((and obj (sig-varargs sig)) + (extern-call-form obj sig forms)) + (obj `(,(obj-sym obj) ,@forms ,@dests)) + (t `(funcall (proc-fn ,fn) ,@forms ,@dests))))) + (let ((item (cond ((null results) (make-item :mode :none :form form :tok tk)) + ((null (rest results)) (val-item (first results) form tk)) + (t (make-item :mode :multi :type results :form form :tok tk))))) + (setf (item-obj item) (list :call results)) + item))) + +(defun extern-call-form (obj sig forms) + "A call of a C procedure with `...`: the arguments past its parameters +as VARARG-FORM made them, (alien-type form)." + (let* ((params (sig-params sig)) (n (length params)) (r (first (sig-results sig)))) + (c-result-form r + `(sb-alien:alien-funcall + (sb-alien:extern-alien ,(obj-extern obj) + (function ,(if r (alien-type r) 'sb-alien:void) + ,@(mapcar (lambda (p) (alien-type (second p))) params) + ,@(mapcar #'first (nthcdr n forms)))) + ,@(loop for p in params for f in forms collect (c-value-form (second p) f)) + ,@(mapcar #'second (nthcdr n forms)))))) + +(defun c-result-form (ty form) + (cond ((null ty) `(progn ,form (values))) + ((is ty :bool) `(/= 0 ,form)) + (t form))) + +;;; try (7.8): the call's error looked at; if it isn't nil, the procedure +;;; returns it at once. + +(defun try-item (tk) + (when (and *proc* (proc-in-defer *proc*)) (fail-tok tk "try can't leave a deferred statement")) + (let* ((item (designator)) + (item (if (eq (item-mode item) :proc) (call-proc (item-obj item) nil tk) item)) + (call (item-obj item))) + (unless (and (consp call) (eq (first call) :call)) + (fail-tok tk "try is applied to a call of a procedure")) + (let ((results (second call))) + (unless (and results (is (car (last results)) :error)) + (fail-tok tk "try needs a procedure whose last result is an ERROR")) + (unless (and *proc* (proc-results *proc*) (is (car (last (proc-results *proc*))) :error)) + (fail-tok tk "try stands in a procedure whose last result is an ERROR")) + (let* ((vals (butlast results)) + (syms (loop repeat (length vals) collect (var-sym "V"))) + (e (var-sym "E")) + (form `(multiple-value-bind (,@syms ,e) ,(item-form item) + (unless (= ,e 0) ,(return-zeros-form e)) + (values ,@syms)))) + (cond ((null vals) (make-item :mode :none :form form :tok tk)) + ((null (rest vals)) (val-item (first vals) form tk)) + (t (make-item :mode :multi :type vals :form form :tok tk))))))) + +;;; The built-in procedures (6.8); the `(` is read. + +(defun builtin-args () + (prog1 (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))) + (expect :|)|))) + +(defun builtin (name tk) + "The item of a call of the built-in procedure NAME, marked as a call so +that it may stand as a statement." + (let ((item (builtin-call name tk))) + (unless (item-obj item) (setf (item-obj item) (list :builtin))) + item)) + +(defun builtin-call (name tk) + (flet ((arity (args n &optional (m n)) + (unless (<= n (length args) m) + (fail-tok tk "~a takes ~d arguments, not ~d" name n (length args))) + args)) + (cond + ((string= name "SIZE") + (let ((ty (parse-type))) + (expect :|)|) + (const-item *untyped-int* (ty-size ty) tk))) + (t + (let ((args (builtin-args))) + (macrolet ((arg (i) `(nth ,i args))) + (cond + ((string= name "ADR") + (arity args 1) + (let ((x (arg 0))) + (unless (eq (item-mode x) :var) (fail-tok tk "ADR takes a variable")) + (check-writable x tk "given to ADR") + (when (item-noaddr x) (fail-tok tk "a field of a packed record has no address")) + (val-item (make-ptr-type (item-type x) nil) (item-form x) tk))) + ((string= name "LEN") + (arity args 1) + (let* ((x (need-value (arg 0))) (ty (item-type x))) + (case (ty-kind ty) + (:array (const-item *untyped-int* (ty-len ty) tk)) + (:string (const-item *untyped-int* (ty-len ty) tk)) + (:slice (val-item (basic "INT") `(ld :i64 (+ ,(value-form x) 8)) tk)) + (t (fail-tok tk "LEN takes an array, a slice or a string, not ~a" (type-name ty)))))) + ((string= name "MSG") + (arity args 1) + (val-item (make-slice-type (basic "U8")) + `(let ((e ,(coerce-item (arg 0) (basic "ERROR")))) (if (= e 0) ,(string-slice #()) e)) + tk)) + ((string= name "NEW") (arity args 2) (new-form (arg 0) (arg 1) tk)) + ((string= name "COPY") (arity args 2) (copy-form (arg 0) (arg 1) tk)) + ((member name '("INC" "DEC") :test #'string=) (arity args 1 2) (inc-form name args tk)) + ((string= name "FENCE") (arity args 0) + (make-item :mode :none :form '(sb-thread:barrier (:memory)) :tok tk)) + ((member name '("CAS" "XCHG" "XADD") :test #'string=) (atomic name args tk)) + ((string= name "SYSCALL") + (arity args 1 7) + (val-item (basic "INT") + `(syscall ,@(loop for a in args + collect (let* ((a (need-value a)) (ty (item-type a))) + (unless (or (member (ty-kind ty) '(:int :untyped-int :ptr))) + (fail-tok tk "SYSCALL takes integers and pointers")) + (value-form a)))) + tk)) + ((string= name "ARGC") (arity args 0) (val-item (basic "INT") '(argc) tk)) + ((string= name "ARGV") (arity args 0) + (val-item (make-ptr-type (make-ptr-type (basic "U8") nil) nil) '(argv) tk)) + (t (fail-tok tk "~a isn't a built-in procedure" name))))))))) + +(defun writable-var (x tk what) + (unless (eq (item-mode x) :var) (fail-tok tk "~a takes a variable" what)) + (check-writable x tk (format nil "changed by ~a" what)) + x) + +(defun inc-form (name args tk) + (let* ((v (writable-var (first args) tk name)) (ty (item-type v)) (a (var-sym "A"))) + (unless (is ty :int) (fail-tok tk "~a takes an integer variable" name)) + (let ((k (if (second args) (exact-form (second args) ty tk "the step") 1))) + (make-item :mode :none :tok tk + :form `(let ((,a ,(item-form v))) + (st ,(access-kind ty) ,a + ,(wrap-form ty `(,(if (string= name "INC") '+ '-) (ld ,(access-kind ty) ,a) ,k)))))))) + +(defun new-form (p a tk) + ;; a^.alloc(a, SIZE(T), alignment), zeroed if not nil + (let* ((p (writable-var p tk "NEW")) (ty (item-type p))) + (unless (is ty :ptr) (fail-tok tk "NEW takes a pointer variable")) + (let* ((alloc-ty (allocator-type tk)) + (af (coerce-item a (make-ptr-type alloc-ty nil))) + (base (ptr-base ty))) + (make-item :mode :none :tok tk + :form `(let* ((pa ,(item-form p)) (al ,af) + (r (funcall (proc-fn (ld :u64 al)) al ,(ty-size base) ,(ty-align base)))) + (unless (= r 0) (zero r ,(ty-size base))) + (st :u64 pa r)))))) + +(defun allocator-type (tk) + (let* ((m (gethash "Mem" *modules*)) + (o (and m (gethash "Allocator" (module-exports m))))) + (unless o (fail-tok tk "NEW needs the library's Mem.Allocator, which no module imports")) + (obj-type o))) + +(defun copy-form (d s tk) + ;; the elements of s to the start of d, as one block (6.8) + (let ((d (need-value d)) (s (need-value s))) + (dolist (x (list d s)) + (unless (member (ty-kind (item-type x)) '(:array :slice :string)) + (fail-tok tk "COPY takes arrays and slices"))) + (when (and (is (item-type d) :array) (not (eq (item-mode d) :var))) (fail-tok tk "COPY's first is a variable")) + (when (is (item-type d) :array) (check-writable d tk "changed by COPY")) + (when (is (item-type d) :string) (fail-tok tk "COPY can't write a string")) + (multiple-value-bind (pd ld ed sd fd) (sequence-parts d) + (multiple-value-bind (ps ls es ss fs) (sequence-parts s) + (unless (same-type-p ed es) (fail-tok tk "COPY's two sides' elements are of two types")) + (make-item :mode :none :tok tk + :form `(let* (,@(when sd `((,sd ,fd))) ,@(when ss `((,ss ,fs))) (ld ,ld) (ls ,ls)) + ,(unless (module-check-off *module*) `(check-copy ls ld ,(where tk))) + (move ,pd ,ps (* ls ,(ty-size ed))))))))) + +(defun atomic (name args tk) + (let* ((n (if (string= name "CAS") 3 2))) + (unless (= (length args) n) (fail-tok tk "~a takes ~d arguments" name n)) + (let* ((p (need-value (first args))) (pty (item-type p))) + (unless (is pty :ptr) (fail-tok tk "~a takes a pointer" name)) + (let* ((ty (ptr-base pty)) (k (ty-kind ty))) + (unless (or (member (ty-name ty) '("INT" "UINT") :test #'equal) + (and (eq k :ptr) (not (string= name "XADD")))) + (fail-tok tk "~a works on ~:[INT, UINT and pointers~;INT and UINT~]" name (string= name "XADD"))) + (let ((signed (and (is ty :int) (ty-signed ty))) + (rest (mapcar (lambda (a) (coerce-item a ty)) (rest args)))) + (if (string= name "CAS") + (val-item (basic "BOOL") `(cas ,(value-form p) ,@rest ,signed) tk) + (val-item ty `(,(if (string= name "XCHG") 'xchg 'xadd) ,(value-form p) ,@rest ,signed) tk))))))) diff --git a/sbcl/src/package.lisp b/sbcl/src/package.lisp new file mode 100644 index 0000000..eb71f19 --- /dev/null +++ b/sbcl/src/package.lisp @@ -0,0 +1,13 @@ +;;;; package.lisp -- the packages of the compiler. +;;;; +;;;; RAZ holds the compiler and the run time that compiled programs call. +;;;; RAZP holds the names the compiler makes for a program's procedures, +;;;; such as |Out.str|, so that they never meet the compiler's own. + +(defpackage :raz + (:use :common-lisp) + (:shadow #:import #:*modules*) + (:export #:main)) + +(defpackage :razp + (:use)) diff --git a/sbcl/src/rt.lisp b/sbcl/src/rt.lisp new file mode 100644 index 0000000..2dcdf13 --- /dev/null +++ b/sbcl/src/rt.lisp @@ -0,0 +1,323 @@ +;;;; rt.lisp -- the run time: what the compiled code calls. +;;;; +;;;; A compiled program is Lisp code over raw memory. Every raz variable +;;;; lives at an address, as the report wants (ADR works on any of them): +;;;; +;;;; - the module variables, the string literals, the constant arrays +;;;; and records and the errors' messages lie in one block, the data, +;;;; mapped at the fixed address +DATA-BASE+, so that each of their +;;;; addresses is a number the compiler knows; +;;;; - a procedure's parameters, variables and temporaries lie in its +;;;; frame, on a raz stack of its thread: *SP* is the first free byte. +;;;; +;;;; Values in Lisp: an integer, pointer, ERROR or set is an integer, +;;;; kept within its type's range; a BOOL is T or NIL; a real a +;;;; DOUBLE-FLOAT or SINGLE-FLOAT; a procedure value a number, its index +;;;; in *PROCS*. An array, record, variant or slice is handled by its +;;;; address. This file holds the operations on these that are more than +;;;; a Lisp function the compiler can name directly. + +(in-package :raz) + +(defconstant +data-base+ #x200000000000 + "Where the data block is mapped, out of the way of SBCL's own memory.") + +(sb-ext:defglobal *data-image* (make-array 0 :element-type '(unsigned-byte 8)) + "The data block's first contents, made by the compiler.") + +(sb-ext:defglobal *procs* (vector nil) + "The procedures that are values: a procedure value is an index here; 0 is nil.") + +(sb-ext:defglobal *main* nil + "The program: a function that runs the module bodies and main, and returns the status.") + +(defvar *sp* 0 "The first free byte of this thread's raz stack.") +(defvar *stack-end* 0 "The end of this thread's raz stack.") + +;;; Memory. LD reads a scalar of an access kind (types.lisp, ACCESS-KIND) +;;; at an address, ST writes one. + +(defmacro ld (kind addr) + (let ((sap `(sb-sys:int-sap ,addr))) + (ecase kind + (:i8 `(sb-sys:signed-sap-ref-8 ,sap 0)) + (:i16 `(sb-sys:signed-sap-ref-16 ,sap 0)) + (:i32 `(sb-sys:signed-sap-ref-32 ,sap 0)) + (:i64 `(sb-sys:signed-sap-ref-64 ,sap 0)) + (:u8 `(sb-sys:sap-ref-8 ,sap 0)) + (:u16 `(sb-sys:sap-ref-16 ,sap 0)) + (:u32 `(sb-sys:sap-ref-32 ,sap 0)) + (:u64 `(sb-sys:sap-ref-64 ,sap 0)) + (:bool `(/= 0 (sb-sys:sap-ref-8 ,sap 0))) + (:f32 `(sb-sys:sap-ref-single ,sap 0)) + (:f64 `(sb-sys:sap-ref-double ,sap 0))))) + +(defmacro st (kind addr value) + (if (eq kind :bool) + `(setf (sb-sys:sap-ref-8 (sb-sys:int-sap ,addr) 0) (if ,value 1 0)) + `(setf (ld ,kind ,addr) ,value))) + +(defmacro c-call (name result &rest typed-args) + "Calls the C function NAME; TYPED-ARGS alternate alien types and values." + (let ((types (loop for (ty) on typed-args by #'cddr collect ty)) + (vals (loop for (nil v) on typed-args by #'cddr collect v))) + `(sb-alien:alien-funcall + (sb-alien:extern-alien ,name (function ,result ,@types)) ,@vals))) + +(defun move (dst src n) + "Copies N bytes from SRC to DST, which may overlap." + (when (> n 0) + (c-call "memmove" sb-alien:unsigned-long sb-alien:unsigned-long dst sb-alien:unsigned-long src + sb-alien:unsigned-long n)) + dst) + +(defun zero (dst n) + (when (> n 0) + (c-call "memset" sb-alien:unsigned-long sb-alien:unsigned-long dst sb-alien:int 0 + sb-alien:unsigned-long n)) + dst) + +(defun bytes-equal (a b n) + (or (= n 0) + (= 0 (c-call "memcmp" sb-alien:int sb-alien:unsigned-long a sb-alien:unsigned-long b + sb-alien:unsigned-long n)))) + +(defun slice (addr ptr len) + "Writes the slice (PTR, LEN) at ADDR, and gives ADDR." + (st :u64 addr ptr) + (st :i64 (+ addr 8) len) + addr) + +;;; Frames. ENTER is the first thing a procedure does: its frame is the +;;; SIZE bytes from FP, which must fit the stack, and start at zero. + +(define-condition stack-overflow (error) ()) + +(defun enter (fp size) + (when (> (+ fp size) *stack-end*) + ;; stopped at the top of the stack, where there is room to stop + (error 'stack-overflow)) + (zero fp size)) + +;;; Stopping (section 10). A failed check, and every fault, comes to +;;; STOP, which hands its message to the library's Rt.stop: it writes it, +;;; runs the procedures registered with Rt.atExit and ends with status 2. + +(defvar *stopping* nil) + +(defun stop (text) + (let ((bytes (sb-ext:string-to-octets text :external-format :utf-8))) + (when *stopping* + ;; a stop while stopping: say it and end, with no more of the library + (write-bytes 2 bytes) + (write-bytes 2 #(10)) + (exit-now 2)) + (let ((*stopping* t) + (buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long (+ 16 (length bytes))))) + (loop for b across bytes for i from 16 do (st :u8 (+ buf i) b)) + (funcall 'razp::|Rt.stop| (slice buf (+ buf 16) (length bytes)))) + (exit-now 2))) + +(defun write-bytes (fd bytes) + (let ((buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long (max 1 (length bytes))))) + (loop for b across bytes for i from 0 do (st :u8 (+ buf i) b)) + (c-call "write" sb-alien:long sb-alien:int fd sb-alien:unsigned-long buf + sb-alien:unsigned-long (length bytes)))) + +(defun exit-now (status) + "Ends the program at once: C's buffers flushed, then the process." + (c-call "fflush" sb-alien:int sb-alien:unsigned-long 0) + (c-call "_exit" sb-alien:void sb-alien:int (logand status #xFF))) + +;;; The checks of section 6.5, and those of division (6.1). WHERE is the +;;; place, "file:line:col". + +(defun check-index (i n where) + (if (and (<= 0 i) (< i n)) + i + (stop (format nil "~a: index ~d is out of range for a length of ~d" where i n)))) + +(defun check-slice (lo hi n where) + (cond ((< lo 0) (stop (format nil "~a: slice bound ~d is below 0" where lo))) + ((< hi lo) (stop (format nil "~a: slice [~d..~d] runs backwards" where lo hi))) + ((and n (> hi n)) (stop (format nil "~a: slice bound ~d is beyond the length ~d" where hi n))) + (t lo))) + +(defun check-copy (ls ld where) + (when (> ls ld) + (stop (format nil "~a: COPY of ~d elements into ~d" where ls ld)))) + +(defun check-enum (i n where) + (if (and (<= 0 i) (< i n)) + i + (stop (format nil "~a: ~d is no position of the enumeration, which has ~d names" where i n)))) + +(defun divide (a b bits signed where mod) + "A div B, or A mod B with MOD, of a BITS-wide integer type." + (cond ((= b 0) (stop (format nil "~a: a division by zero" where))) + ((and signed (= b -1) (= a (- (expt 2 (1- bits))))) + (stop (format nil "~a: a division of the smallest ~d-bit integer by -1" where bits))) + (mod (rem a b)) + (t (values (truncate a b))))) + +;;; Conversions (6.7) that are more than a Lisp function. + +(defun real-to-int (x bits signed) + "Rounded toward zero; a NaN or a value out of I64's range is the smallest I64, then cut." + (let ((i (if (and (= x x) (>= x -9223372036854775808d0) (< x 9223372036854775808d0)) + (truncate x) + (- (expt 2 63))))) + (if signed (sb-c::mask-signed-field bits i) (ldb (byte bits 0) i)))) + +;;; Procedure values. + +(defun proc-fn (h) + "The function of procedure value H; nil stops the program." + (if (and (< 0 h) (< h (length *procs*))) + (svref *procs* h) + (stop (if (= h 0) "a call of a nil procedure" "a call of a bad procedure value")))) + +;;; Procedures given to C: a C function for each, made once. + +(sb-ext:defglobal *callbacks* (make-hash-table) "Procedure value -> the address of its C function.") +(sb-ext:defglobal *callbacks-lock* (sb-thread:make-mutex) "") + +(defun c-callback (h make) + (if (= h 0) + 0 + (sb-thread:with-mutex (*callbacks-lock*) + (or (gethash h *callbacks*) + (setf (gethash h *callbacks*) (sb-sys:sap-int (funcall make (proc-fn h)))))))) + +(defmacro in-raz-thread (&body body) + "BODY, on a raz stack: a thread C started has none until it calls raz." + `(flet ((run () ,@body)) + (if (= *stack-end* 0) (with-raz-thread (run)) (run)))) + +;;; The atomic built-ins (6.8), on INT, UINT and pointers. A CAS on a +;;; word is the one the machine has; XCHG and XADD loop on it. + +(defun cas (addr old new signed) + (declare (type (unsigned-byte 64) addr)) + (if signed + (let ((old old) (new new)) + (declare (type (signed-byte 64) old new)) + (= old (sb-ext:cas (sb-sys:signed-sap-ref-64 (sb-sys:int-sap addr) 0) old new))) + (let ((old old) (new new)) + (declare (type (unsigned-byte 64) old new)) + (= old (sb-ext:cas (sb-sys:sap-ref-64 (sb-sys:int-sap addr) 0) old new))))) + +(defun xchg (addr x signed) + (loop (let ((old (if signed (ld :i64 addr) (ld :u64 addr)))) + (when (cas addr old x signed) (return old))))) + +(defun xadd (addr x signed) + (loop (let* ((old (if signed (ld :i64 addr) (ld :u64 addr))) + (new (if signed (sb-c::mask-signed-field 64 (+ old x)) (ldb (byte 64 0) (+ old x))))) + (when (cas addr old new signed) (return old))))) + +;;; SYSCALL, through the C library's syscall(), which gives -1 and errno +;;; where Linux gives minus the errno. + +(defun syscall (n &optional (a 0) (b 0) (c 0) (d 0) (e 0) (f 0)) + (flet ((w (x) (ldb (byte 64 0) x))) + (let ((r (c-call "syscall" sb-alien:long sb-alien:long n + sb-alien:unsigned-long (w a) sb-alien:unsigned-long (w b) + sb-alien:unsigned-long (w c) sb-alien:unsigned-long (w d) + sb-alien:unsigned-long (w e) sb-alien:unsigned-long (w f)))) + (if (= r -1) (- (sb-alien:get-errno)) r)))) + +;;; The command line: C's own argv, which SBCL's run time keeps. + +(defun argv () (ld :u64 (sb-sys:find-foreign-symbol-address "posix_argv"))) + +(defun argc () + (loop with a = (argv) for i from 0 while (/= 0 (ld :u64 (+ a (* 8 i)))) finally (return i))) + +;;; Raz stacks: memory mapped for each thread, not reserved, so that it +;;; costs only what it uses. + +(defconstant +stack-size+ (* 256 1024 1024)) + +(defun map-memory (size &optional (at 0)) + ;; mmap(at, size, read|write, private|anonymous|noreserve, and + ;; fixed_noreplace if AT is given) + (let ((r (syscall 9 at size 3 (logior #x22 #x4000 (if (= at 0) 0 #x100000)) -1 0))) + (when (or (< r 0) (and (/= at 0) (/= r at))) + (write-bytes 2 (sb-ext:string-to-octets (format nil "can't map ~d bytes of memory~%" size))) + (exit-now 2)) + r)) + +(defmacro with-raz-thread (&body body) + "Runs BODY on a raz stack of its own, with the reals' traps off (6.3)." + `(let* ((*sp* (map-memory +stack-size+)) + (*stack-end* (+ *sp* +stack-size+))) + (sb-int:with-float-traps-masked (:overflow :invalid :inexact :divide-by-zero :underflow) + (catching-faults ,@body)))) + +(defun raz-frames () + "The names of the raz procedures under way, the innermost first." + (let ((names '())) + (sb-debug:map-backtrace + (lambda (frame) + (let ((name (sb-di:debug-fun-name (sb-di:frame-debug-fun frame)))) + (when (and (symbolp name) (eq (symbol-package name) (find-package :razp))) + (push (symbol-name name) names))))) + (nreverse names))) + +(defun trace-calls () + "Rt.trace: the calls under way, on standard error." + (dolist (name (raz-frames)) + (write-bytes 2 (sb-ext:string-to-octets (format nil " in ~a~%" name))))) + +(defmacro catching-faults (&body body) + "BODY, where a bad address or an exhausted stack stops the program." + `(let ((where nil)) + (handler-case + (handler-bind ((sb-sys:memory-fault-error + (lambda (c) (declare (ignore c)) (setf where (first (raz-frames)))))) + ,@body) + (sb-sys:memory-fault-error (c) + (stop (format nil "in ~a: a nil pointer or a bad address (0x~(~x~))" where + (fault-address c)))) + ((or storage-condition stack-overflow) () (stop "a stack overflow"))))) + +(defun fault-address (c) + (let ((a (ignore-errors (slot-value c 'sb-kernel::address)))) + (if (integerp a) a 0))) + +;;; Threads (the library's Thread): each a Lisp thread on a raz stack of +;;; its own. A thread is known to raz code by a number. + +(sb-ext:defglobal *threads* (make-hash-table) "") +(sb-ext:defglobal *thread-count* 0 "") +(sb-ext:defglobal *threads-lock* (sb-thread:make-mutex) "") + +(defun thread-spawn (proc arg) + (let ((fn (proc-fn proc))) + (sb-thread:with-mutex (*threads-lock*) + (let ((id (incf *thread-count*))) + (setf (gethash id *threads*) + (sb-thread:make-thread (lambda () (with-raz-thread (funcall fn arg))))) + id)))) + +(defun thread-join (id) + (let ((th (sb-thread:with-mutex (*threads-lock*) (gethash id *threads*)))) + (when th + (sb-thread:join-thread th :default nil) + (sb-thread:with-mutex (*threads-lock*) (remhash id *threads*))))) + +;;; The start. The saved program begins here: the data block mapped and +;;; filled, then the program run on the main thread's raz stack, and its +;;; status given to Rt.exit. + +(defun start () + (let ((size (length *data-image*))) + (when (> size 0) + (map-memory (round-up size 4096) +data-base+) + (sb-sys:with-pinned-objects (*data-image*) + (move +data-base+ (sb-sys:sap-int (sb-sys:vector-sap *data-image*)) size)))) + (with-raz-thread + (let ((status (funcall *main*))) + (funcall 'razp::|Rt.exit| status))) + (exit-now 0)) diff --git a/sbcl/src/scan.lisp b/sbcl/src/scan.lisp new file mode 100644 index 0000000..06566a0 --- /dev/null +++ b/sbcl/src/scan.lisp @@ -0,0 +1,279 @@ +;;;; scan.lisp -- the scanner: a file's bytes into a vector of tokens. +;;;; +;;;; Report, section 2. The whole file is checked to be UTF-8 first, then +;;;; cut into tokens, each with its line and column (counted in +;;;; characters), which the parser reads by index. Reading the whole file +;;;; at once lets the parser go back, as it does to read a generic +;;;; module's type arguments where the instance is made (section 3). +;;;; +;;;; A code procedure's body (section 8) isn't raz: after the word `code` +;;;; the scanner takes each instruction, up to its `;`, as raw text, until +;;;; an instruction that starts with `end`. + +(in-package :raz) + +;;; Errors. Every error the compiler finds is a RAZ-ERROR, whose text +;;; already says where it is; the driver prints it and stops (appendix A +;;; lets an implementation report as few errors as one). + +(define-condition raz-error (error) + ((text :initarg :text :reader raz-error-text)) + (:report (lambda (c s) (write-string (raz-error-text c) s)))) + +(defvar *file* "?" "The name of the file being read, for messages.") + +(defun fail-at (line col fmt &rest args) + (error 'raz-error + :text (format nil "~a:~d:~d: ~?" *file* line col fmt args))) + +;;; Tokens. KIND is :ident, :int, :real, :char, :string, :code, :blank, +;;; :eof, or a keyword naming a reserved word or an operator, such as +;;; :begin or :|:=|. VAL is an identifier's text, a number's value, a +;;; string's bytes, or a code body's instructions. + +(defstruct (tok (:constructor make-tok (kind val line col))) + kind val line col) + +(defparameter *reserved* + '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else" + "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link" + "match" "mod" "module" "not" "of" "or" "packed" "proc" "record" + "repeat" "return" "set" "shl" "shr" "then" "to" "try" "type" "until" + "var" "variant" "VOLATILE" "while" "xor")) + +;;; Operators, longest first, so that `:=` is found before `:`. +(defparameter *operators* + '("..." ".." ":=" "<=" ">=" "+" "-" "*" "/" "&" "|" "~" "=" "#" "<" ">" + ":" ";" "," "." "(" ")" "[" "]" "{" "}" "^")) + +(defun keyword-of (text) (intern text :keyword)) + +;;; UTF-8. Section 2: no malformed or overlong sequence, no surrogate, +;;; nothing past 10FFFFH, and no NUL byte anywhere. + +(defun check-utf8 (bytes) + (let ((i 0) (n (length bytes)) (line 1)) + (flet ((bad () (fail-at line 1 "the file isn't valid UTF-8"))) + (loop while (< i n) do + (let* ((b (aref bytes i)) + (len (cond ((< b #x80) 1) ((< b #xC2) 0) ((< b #xE0) 2) + ((< b #xF0) 3) ((< b #xF5) 4) (t 0)))) + (when (= b 0) (fail-at line 1 "the file has a NUL byte")) + (when (= b 10) (incf line)) + (when (or (= len 0) (> (+ i len) n)) (bad)) + (let ((cp (if (= len 1) b (logand b (ash #x7F (- len)))))) + (loop for k from 1 below len + for c = (aref bytes (+ i k)) + do (unless (= (logand c #xC0) #x80) (bad)) + (setf cp (logior (ash cp 6) (logand c #x3F)))) + ;; the least code point each length may hold, against overlong forms + (when (or (< cp (aref #(0 0 #x80 #x800 #x10000) len)) + (<= #xD800 cp #xDFFF) (> cp #x10FFFF)) + (bad))) + (incf i len)))))) + +(defun utf8-encode (cp) + "The UTF-8 bytes of code point CP, as a list." + (cond ((< cp #x80) (list cp)) + ((< cp #x800) (list (logior #xC0 (ash cp -6)) (logior #x80 (logand cp #x3F)))) + ((< cp #x10000) (list (logior #xE0 (ash cp -12)) + (logior #x80 (logand (ash cp -6) #x3F)) + (logior #x80 (logand cp #x3F)))) + (t (list (logior #xF0 (ash cp -18)) + (logior #x80 (logand (ash cp -12) #x3F)) + (logior #x80 (logand (ash cp -6) #x3F)) + (logior #x80 (logand cp #x3F)))))) + +;;; The scanner proper. It walks the bytes with POS, keeping LINE and the +;;; column COL of the byte at POS, in characters. + +(defun scan (bytes) + "The tokens of BYTES, a file's contents, ending in an :eof token." + (check-utf8 bytes) + (let ((pos 0) (line 1) (col 1) (toks '()) (n (length bytes))) + (labels ((peek (&optional (k 0)) + (if (< (+ pos k) n) (aref bytes (+ pos k)) 0)) + (next () + (let ((b (aref bytes pos))) + (incf pos) + (cond ((= b 10) (incf line) (setf col 1)) + ;; a continuation byte doesn't start a character + ((/= (logand b #xC0) #x80) (incf col))) + b)) + (err (fmt &rest args) (apply #'fail-at line col fmt args)) + (letter-p (b) (or (<= 65 b 90) (<= 97 b 122) (= b 95))) + (digit-p (b) (<= 48 b 57)) + (hex-p (b) (or (digit-p b) (<= 65 b 70))) + (any-hex-p (b) (or (hex-p b) (<= 97 b 102))) + (hex-value (b) (digit-char-p (code-char b) 16)) + (skip-space-and-comments () + (loop + (cond ((member (peek) '(32 9 10 13)) (next)) + ((and (= (peek) 40) (= (peek 1) 42)) (comment)) + (t (return))))) + (comment () + ;; comments nest: `(*` opens one more, `*)` closes one + (let ((l line) (c col) (depth 0)) + (loop + (cond ((>= pos n) (fail-at l c "the comment never ends")) + ((and (= (peek) 40) (= (peek 1) 42)) (next) (next) (incf depth)) + ((and (= (peek) 42) (= (peek 1) 41)) (next) (next) + (when (= (decf depth) 0) (return))) + (t (next)))))) + (add (kind val l c) (push (make-tok kind val l c) toks)) + (word (l c) + (let ((start pos)) + (loop while (or (letter-p (peek)) (digit-p (peek))) do (next)) + (let ((text (map 'string #'code-char (subseq bytes start pos)))) + (when (> (length text) 63) + (fail-at l c "the name ~a... is longer than 63 characters" (subseq text 0 20))) + (cond ((string= text "_") (add :blank nil l c)) + ((member text *reserved* :test #'string=) + (add (keyword-of (string-upcase text)) nil l c) + (when (string= text "code") (code-body))) + (t (add :ident text l c)))))) + (number (l c) + ;; digits and capitals A-F; then H for hexadecimal, or a + ;; point and a digit for a real + (let ((start pos)) + (loop while (hex-p (peek)) do (next)) + (let ((text (map 'string #'code-char (subseq bytes start pos)))) + (cond ((= (peek) 72) ; H + (next) + (let ((v (parse-integer text :radix 16))) + (when (>= v (expt 2 64)) + (fail-at l c "the number ~aH is above the largest U64" text)) + (add :int v l c))) + ((find-if (lambda (ch) (char<= #\A ch #\F)) text) + (fail-at l c "a hexadecimal number ends in H: ~a" text)) + ((and (= (peek) 46) (digit-p (peek 1))) + (real-number text l c)) + ((or (letter-p (peek))) + (err "a number is followed by a letter")) + (t (let ((v (parse-integer text))) + (when (>= v (expt 2 63)) + (fail-at l c "the number ~a is above the largest I64" text)) + (add :int v l c))))))) + (real-number (whole l c) + ;; the value as an exact fraction, rounded once to an F64 + (next) ; the point + (let ((start pos) (exp 0)) + (loop while (digit-p (peek)) do (next)) + (let* ((frac (map 'string #'code-char (subseq bytes start pos))) + (mant (parse-integer (concatenate 'string whole frac)))) + (when (= (peek) 69) ; E + (next) + (let ((sign 1) (s pos)) + (cond ((= (peek) 43) (next)) ((= (peek) 45) (next) (setf sign -1))) + (setf s pos) + (unless (digit-p (peek)) (err "an exponent needs digits")) + (loop while (digit-p (peek)) do (next)) + (setf exp (* sign (parse-integer (map 'string #'code-char (subseq bytes s pos))))))) + (when (or (letter-p (peek)) (digit-p (peek))) + (err "a real is followed by ~a" (code-char (peek)))) + ;; an exponent too far out either way needn't be computed + (let ((value (cond ((= mant 0) 0d0) + ((> (+ exp (length whole)) 400) nil) + ((< (+ exp (length whole)) -400) 0d0) + (t (let ((r (* mant (expt 10 (- exp (length frac)))))) + (if (> r most-positive-double-float) + nil + (coerce r 'double-float))))))) + (unless value (fail-at l c "the real is above the largest F64")) + (add :real value l c))))) + (escape (in-string) + ;; after a backslash: the code point, or (:byte b) for \xHH + (let ((b (if (< pos n) (next) 0))) + (case (code-char b) + (#\n 10) (#\t 9) (#\r 13) (#\0 0) (#\\ 92) (#\' 39) (#\" 34) + (#\x (unless in-string (err "\\x is for strings only")) + (unless (and (any-hex-p (peek)) (any-hex-p (peek 1))) + (err "\\x takes two hexadecimal digits")) + (list :byte (+ (* 16 (hex-value (next))) (hex-value (next))))) + (#\u (unless (= (next) 123) (err "\\u is followed by {")) + (let ((v 0) (k 0)) + (loop while (any-hex-p (peek)) + do (setf v (+ (* v 16) (hex-value (next)))) (incf k) + (when (> v #x10FFFF) (err "\\u{...} is above 10FFFFH"))) + (unless (and (> k 0) (= (peek) 125)) (err "\\u{...} wants hexadecimal digits and }")) + (next) + (when (<= #xD800 v #xDFFF) (err "\\u{...} is a surrogate")) + v)) + (t (err "unknown escape \\~a" (code-char b)))))) + (char-code-at () + ;; the code point of the UTF-8 character at pos + (let* ((b (next)) (len (cond ((< b #x80) 1) ((< b #xE0) 2) ((< b #xF0) 3) (t 4))) + (cp (if (= len 1) b (logand b (ash #x7F (- len)))))) + (loop repeat (1- len) do (setf cp (logior (ash cp 6) (logand (next) #x3F)))) + cp)) + (char-literal (l c) + (next) + (when (member (peek) '(39 10 0)) (fail-at l c "a character literal holds one character")) + (let ((v (if (= (peek) 92) (progn (next) (escape nil)) (char-code-at)))) + (unless (= (peek) 39) (fail-at l c "the character literal isn't closed")) + (next) + (add :char v l c))) + (string-literal (l c) + (next) + (let ((out (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0))) + (loop + (let ((b (peek))) + (cond ((or (>= pos n) (= b 10)) (fail-at l c "the string isn't closed on its line")) + ((= b 34) (next) (return)) + ((= b 92) (next) + (let ((e (escape t))) + (if (consp e) + (vector-push-extend (second e) out) + (dolist (x (utf8-encode e)) (vector-push-extend x out))))) + (t (vector-push-extend (next) out))))) + (add :string (coerce out '(simple-array (unsigned-byte 8) (*))) l c))) + (code-body () + ;; raw instructions up to the one that starts with `end` + (let ((instrs '())) + (loop + ;; only spaces: `(*` here is Lisp's multiplication + (loop while (member (peek) '(32 9 10 13)) do (next)) + (when (>= pos n) (err "the code procedure never ends")) + (let ((l line) (c col) (start pos) (depth 0) (in-str nil)) + (loop while (< pos n) + do (let ((b (peek))) + (cond (in-str (when (= b 92) (next)) (when (= b 34) (setf in-str nil))) + ((= b 34) (setf in-str t)) + ((= b 40) (incf depth)) + ((= b 41) (decf depth)) + ((and (= b 59) (= depth 0)) (return))) + (next))) + (let ((text (string-trim '(#\Space #\Tab #\Newline #\Return) + (sb-ext:octets-to-string (subseq bytes start pos) :external-format :utf-8)))) + (when (and (>= (length text) 3) (string= "end" text :end2 3) + (or (= (length text) 3) (not (alphanumericp (char text 3))))) + ;; give back the `end` for the parser + (setf pos start line l col c) + (return)) + (push (list text l c) instrs) + (when (< pos n) (next))))) + (add :code (nreverse instrs) line col))) + (operator (l c) + (dolist (op *operators* (err "unknown character ~a" (code-char (peek)))) + (when (loop for k below (length op) + always (= (peek k) (char-code (char op k)))) + (loop repeat (length op) do (next)) + (return (add (keyword-of op) nil l c)))))) + (loop + (skip-space-and-comments) + (when (>= pos n) (return)) + (let ((b (peek)) (l line) (c col)) + (cond ((letter-p b) (word l c)) + ((digit-p b) (number l c)) + ((= b 39) (char-literal l c)) + ((= b 34) (string-literal l c)) + ((>= b 128) (err "a character outside ASCII, outside a string or a comment")) + (t (operator l c))))) + (add :eof nil line col) + (coerce (nreverse toks) 'vector)))) + +(defun read-bytes (path) + (with-open-file (s path :element-type '(unsigned-byte 8)) + (let ((v (make-array (file-length s) :element-type '(unsigned-byte 8)))) + (read-sequence v s) + v))) diff --git a/sbcl/src/stmt.lisp b/sbcl/src/stmt.lisp new file mode 100644 index 0000000..eae4dc2 --- /dev/null +++ b/sbcl/src/stmt.lisp @@ -0,0 +1,372 @@ +;;;; stmt.lisp -- statements (report, section 7), each turned into a list +;;;; of Lisp forms. +;;;; +;;;; A procedure's body is a Lisp BLOCK, left by RETURN-FROM; each loop is +;;;; a block of its own, which `break` leaves. Deferred statements (7.7) +;;;; are known where they are written, so the compiler puts a copy of each +;;;; wherever its statement list can be left: at its end, and before each +;;;; `return`, `try` and `break` that leaves it. The program never needs to +;;;; keep a list of them as it runs. + +(in-package :raz) + +(defun in-loop (fn) + "The forms FN makes, given the name of the loop's block, within that +block, which `break` leaves." + (let ((blk (gensym "LOOP"))) + (push (list blk (length (proc-defers *proc*))) (proc-loops *proc*)) + (let ((forms (unwind-protect (funcall fn blk) (pop (proc-loops *proc*))))) + (list `(block ,blk ,@forms))))) + +(defmacro with-loop ((blk) &body body) `(in-loop (lambda (,blk) ,@body))) + +(defun statements (&rest enders) + "Statements up to one of the tokens ENDERS: their forms, and after them +the statements deferred among them, the last first." + (push '() (proc-defers *proc*)) + (let ((forms (loop until (member (kind) enders) + append (prog1 (statement) (expect :|;| "; after a statement"))))) + (append forms (pop (proc-defers *proc*))))) + +(defun pending-defers (&optional (depth 0)) + "The deferred statements of the lists the program leaves, the innermost +first: all of them, or those inside the DEPTH outer lists." + (let ((frames (proc-defers *proc*))) + (apply #'append (subseq frames 0 (- (length frames) depth))))) + +(defun statement () + (let ((tk (tok))) + (case (kind) + ((:ident :blank) (assignment-or-call)) + (:if (next-tok) (if-statement)) + (:while (next-tok) + (let ((c (condition-form))) + (expect :do) + (with-loop (blk) + (prog1 `((loop (unless ,c (return-from ,blk)) ,@(statements :end))) + (expect :end))))) + (:repeat (next-tok) + (with-loop (blk) + (let ((body (statements :until))) + (expect :until) + `((loop ,@body (when ,(condition-form) (return-from ,blk))))))) + (:for (next-tok) (for-statement tk)) + (:match (next-tok) (match-statement tk)) + (:return (next-tok) (list (return-statement tk))) + (:break (next-tok) + (let ((l (first (proc-loops *proc*)))) + (unless l (fail-tok tk "break stands outside a loop~:[~; of the deferred statement~]" + (proc-in-defer *proc*))) + `(,@(pending-defers (second l)) (return-from ,(first l))))) + (:defer (next-tok) (defer-statement tk) '()) + (:try (let ((item (try-item (next-tok)))) + (list (item-form item)))) + (t (fail-here "a statement expected, not ~a" (describe-tok tk)))))) + +(defun condition-form () + (let* ((tk (tok)) (c (need-value (expression)))) + (unless (is (item-type c) :bool) (fail-tok tk "the condition is ~a, not a BOOL" (type-name (item-type c)))) + (value-form c))) + +(defun if-statement () + (let ((clauses '())) + (loop + (let ((c (condition-form))) + (expect :then) + (push (cons c (statements :elsif :else :end)) clauses)) + (unless (accept :elsif) (return))) + (when (accept :else) + (push (cons t (statements :end)) clauses)) + (expect :end) + (list `(cond ,@(reverse clauses))))) + +;;; Assignments and calls (7.1). + +(defun check-target (x tk) + "X, which must be a variable that can be assigned." + (unless (eq (item-mode x) :var) (fail-tok tk "only a variable can be assigned")) + (check-writable x tk "assigned") + (when (and (item-vol x) (aggregate-p (item-type x))) + (fail-tok tk "a whole record or array can't be copied through a volatile pointer")) + x) + +(defun target () + "An assignment's target: a writable variable's item, or nil for `_`." + (if (accept :blank) nil (let ((tk (tok))) (check-target (designator) tk)))) + +(defun assignment-or-call () + (let ((tk (tok))) + (if (or (eq (kind) :blank) (multiple-targets-p)) + (assignment (loop collect (target) while (accept :|,|))) + (let ((x (designator))) + (if (eq (kind) :|:=|) + (assignment (list (check-target x tk))) + (list (call-statement x tk))))))) + +(defun multiple-targets-p () + "Whether the statement is `a, b := ...`: a comma before the := at the +statement's own level." + (let ((depth 0)) + (loop for k from 0 + for kd = (kind k) + do (case kd + ((:|(| :|[| :{) (incf depth)) + ((:|)| :|]| :}) (decf depth)) + (:|,| (when (= depth 0) (return t))) + ((:|:=| :|;| :eof :end) (return nil)))))) + +(defun call-statement (x tk) + "A designator standing alone: a call, whose results are dropped." + (case (item-mode x) + (:proc (item-form (call-proc (item-obj x) nil tk))) + ((:none :multi) (item-form x)) + (t (if (consp (item-obj x)) + (item-form x) ; a call with one result + (if (and (member (item-mode x) '(:var :val)) (is (item-type x) :proc)) + (item-form (call-proc nil x tk)) + (fail-tok tk "this isn't a statement")))))) + +(defun assignment (targets) + (progn + (expect :|:=|) + (let* ((rtk (tok)) (e (expression)) (syms (loop repeat (length targets) collect (var-sym "T")))) + (if (rest targets) + ;; several results, of exactly the targets' types + (progn + (unless (eq (item-mode e) :multi) + (fail-tok rtk "~d targets need a call with ~:*~d results" (length targets))) + (unless (= (length (item-type e)) (length targets)) + (fail-tok rtk "~d targets for ~d results" (length targets) (length (item-type e)))) + (let ((vals (loop repeat (length targets) collect (var-sym "V")))) + (list `(let ,(loop for s in syms for x in targets when x collect `(,s ,(item-form x))) + (multiple-value-bind ,vals ,(item-form e) + ,@(loop for s in syms for x in targets for v in vals for ty in (item-type e) + when x + collect (progn + (unless (same-type-p (item-type x) ty) + (fail-tok rtk "a result of ~a goes to ~a" (type-name ty) (type-name (item-type x)))) + (if (aggregate-p ty) + `(move ,s ,v ,(ty-size ty)) + `(st ,(access-kind ty) ,s ,v))))))))) + (let ((x (first targets))) + (if x + (list `(let ((,(first syms) ,(item-form x))) + ,(store-form (first syms) (item-type x) e rtk))) + ;; `_ := e`: e evaluated, and dropped + (list (if (member (item-mode e) '(:none :multi)) + (fail-tok rtk "_ takes one value") + (value-form e))))))))) + +;;; for (7.2). + +(defun exact-form (item ty tk what) + "ITEM's value as TY, which it must be, or an untyped constant that fits: +an INT doesn't widen here (5.10)." + (let ((item (need-value item))) + (unless (or (and (untyped-p item) (not (assign-error item ty))) + (same-type-p (item-type item) ty)) + (fail-tok tk "~a is ~a, not ~a" what (type-name (item-type item)) (type-name ty))) + (coerce-item item ty tk))) + +(defun for-statement (tk) + (let* ((vtk (tok)) (name (ident)) (obj (lookup name))) + (unless (and obj (eq (obj-kind obj) :var)) (fail-tok vtk "~a isn't a variable" name)) + (unless (eq (kind) :|:=|) (fail-tok (tok) "the for variable is named by its name alone")) + (expect :|:=|) + (let* ((v (obj-item obj vtk)) (ty (item-type v))) + (check-writable v vtk "a for variable") + (unless (member (ty-kind ty) '(:int :enum)) + (fail-tok vtk "a for variable is an integer or an enumeration, not ~a" (type-name ty))) + (let* ((a (exact-form (expression) ty tk "the start")) + (b (progn (expect :to) (exact-form (expression) ty tk "the limit"))) + (s (if (accept :by) + (let* ((stk (tok)) (s (need-value (expression)))) + (unless (and (const-p s) (member (ty-kind (item-type s)) '(:untyped-int :int))) + (fail-tok stk "a for loop's step is an integer constant")) + (when (= (item-val s) 0) (fail-tok stk "a for loop's step isn't 0")) + (item-val s)) + 1)) + (k (access-kind ty)) + (wrap (if (is ty :enum) (basic "U8") ty))) + (expect :do) + (with-loop (blk) + (let ((body (statements :end))) + (expect :end) + ;; at a round's end: stop if one more step would pass the limit + `((let* ((at ,(item-form v)) (lo ,a) (hi ,b)) + (st ,k at lo) + (when ,(if (> s 0) '(<= lo hi) '(>= lo hi)) + (loop ,@body + (let ((i (ld ,k at))) + (when ,(if (> s 0) `(and (<= i hi) (< (- hi i) ,s)) `(and (>= i hi) (< (- i hi) ,(- s)))) + (return-from ,blk)) + (st ,k at ,(wrap-form wrap `(+ i ,s))) + (unless ,(if (> s 0) `(<= (ld ,k at) hi) `(>= (ld ,k at) hi)) + (return-from ,blk))))))))))))) + +;;; match (7.4). + +(defun match-statement (tk) + (let* ((etk (tok)) (x (need-value (expression))) (ty (item-type x))) + (expect :of) + (case (ty-kind ty) + (:variant (match-variant x ty tk)) + (:enum (match-enum x ty tk)) + ((:int :untyped-int) (match-int x (if (is ty :int) ty (basic "INT")) tk)) + (t (fail-tok etk "match takes a variant, an enumeration or an integer, not ~a" (type-name ty)))))) + +(defun arm-else-p () (and (eq (kind) :else) (eq (kind 1) :|:|))) + +(defun match-variant (x ty tk) + ;; the arms' names stand for the fields of x itself if it is a variable + ;; that may change, else of a copy + (let* ((s (var-sym "S")) + (src (if (and (eq (item-mode x) :var) (not (item-ro x))) + (item-form x) + `(move ,(temp ty) ,(value-form x) ,(ty-size ty)))) + (arms '()) (seen '()) (else nil)) + (loop while (accept :|\||) + do (let ((atk (tok))) + (when else (fail-tok atk "else is the last arm")) + (if (arm-else-p) + (progn (next-tok) (next-tok) (setf else (cons t (statements :|\|| :end)))) + (let* ((name (ident)) + (c (find name (ty-cases ty) :key #'vcase-name :test #'string=))) + (unless c (fail-tok atk "~a isn't a case of the variant" name)) + (when (member c seen) (fail-tok atk "the case ~a has two arms" name)) + (push c seen) + (let ((names (when (accept :|(|) + (prog1 (loop collect (cons (tok) (ident)) while (accept :|,|)) + (expect :|)|))))) + (when (and names (/= (length names) (length (vcase-fields c)))) + (fail-tok atk "the case ~a has ~d fields" name (length (vcase-fields c)))) + (expect :|:|) + (let ((*scope* (make-scope :parent *scope*))) + (loop for (ntk . n) in names for f in (vcase-fields c) + do (declare-name (make-obj :name n :kind :var :type (field-type f) :tok ntk + :where (list :at `(+ ,s ,(field-offset f)))))) + (push (cons (list (vcase-index c)) (statements :|\|| :end)) arms))))))) + (expect :end) + (unless (or else (= (length seen) (length (ty-cases ty)))) + (fail-tok tk "the case ~a has no arm" (vcase-name (find-if-not (lambda (c) (member c seen)) (ty-cases ty))))) + (list `(let ((,s ,src)) + (case (ld :i64 ,s) ,@(reverse arms) ,@(when else `((t ,@(rest else))))))))) + +(defun match-enum (x ty tk) + (let ((arms '()) (seen '()) (else nil) (v (var-sym "V"))) + (loop while (accept :|\||) + do (let ((atk (tok))) + (when else (fail-tok atk "else is the last arm")) + (if (arm-else-p) + (progn (next-tok) (next-tok) (setf else (cons t (statements :|\|| :end)))) + (let ((positions + (loop collect (let* ((ntk (tok)) (name (ident)) + (i (position name (ty-names ty) :test #'string=))) + (unless i (fail-tok ntk "~a isn't a name of the enumeration" name)) + (when (member i seen) (fail-tok ntk "~a has two arms" name)) + (push i seen) + i) + while (accept :|,|)))) + (expect :|:|) + (push (cons positions (statements :|\|| :end)) arms))))) + (expect :end) + (unless (or else (= (length seen) (length (ty-names ty)))) + (fail-tok tk "the name ~a has no arm" + (loop for n in (ty-names ty) for i from 0 unless (member i seen) return n))) + (list `(let ((,v ,(value-form x))) + (case ,v ,@(reverse arms) ,@(when else `((t ,@(rest else))))))))) + +(defun match-int (x ty tk) + (let ((arms '()) (ranges '()) (else nil) (v (var-sym "V"))) + (loop while (accept :|\||) + do (let ((atk (tok))) + (when else (fail-tok atk "else is the last arm")) + (if (arm-else-p) + (progn (next-tok) (next-tok) (setf else (cons t (statements :|\|| :end)))) + (let ((tests + (loop collect + (let* ((ltk (tok)) (lo (label-value ty ltk)) + (hi (if (accept :..) (label-value ty ltk) lo))) + (when (> lo hi) (fail-tok ltk "the label's range runs backwards")) + (dolist (r ranges) + (when (and (<= lo (cdr r)) (>= hi (car r))) + (fail-tok ltk "a value is in two labels"))) + (push (cons lo hi) ranges) + (if (= lo hi) `(= ,v ,lo) `(<= ,lo ,v ,hi))) + while (accept :|,|)))) + (expect :|:|) + (push `((or ,@tests) ,@(statements :|\|| :end)) arms))))) + (expect :end) + (unless else (fail-tok tk "a match on an integer has an else arm")) + (list `(let ((,v ,(value-form x))) + (cond ,@(reverse arms) (t ,@(rest else))))))) + +(defun label-value (ty tk) + (let ((x (need-value (expression)))) + (unless (and (const-p x) (member (ty-kind (item-type x)) '(:int :untyped-int))) + (fail-tok tk "a label is an integer constant")) + (let ((why (assign-error x ty))) + (when why (fail-tok tk "~a" why))) + (item-val x))) + +;;; return (7.3), and the return that `try` makes (7.8). + +(defun result-forms (forms) + "The forms of the results to return: an aggregate one copied to its +destination first." + (loop for f in forms for d in (proc-dests *proc*) for ty in (proc-results *proc*) + collect (if d `(move ,d ,f ,(ty-size ty)) f))) + +(defun leave-form (values-form) + "Returns VALUES-FORM, evaluated before the pending deferred statements run." + `(return-from ,(proc-block *proc*) (multiple-value-prog1 ,values-form ,@(pending-defers)))) + +(defun zeros-form (results) + "Each result as a variable of its type starts (section 4)." + `(values ,@(loop for ty in results for d in (proc-dests *proc*) + collect (if d `(zero ,d ,(ty-size ty)) (zero-value ty))))) + +(defun return-zeros-form (err) + "Return zeros and the error ERR, as try does." + (let ((results (proc-results *proc*))) + (leave-form `(values ,@(rest (zeros-form (butlast results))) ,err)))) + +(defun return-statement (tk) + (when (proc-in-defer *proc*) (fail-tok tk "return can't leave a deferred statement")) + (let ((results (proc-results *proc*))) + (if (member (kind) '(:|;| :end :else :elsif :until :|\||)) + (progn + (when results (fail-tok tk "the procedure returns ~d results" (length results))) + (leave-form '(values))) + (let ((items (loop collect (expression) while (accept :|,|)))) + (unless results (fail-tok tk "the procedure has no results to return")) + (if (and (null (rest items)) (rest results)) + ;; return f(x): f's results, exactly the procedure's + (let ((e (first items))) + (unless (and (eq (item-mode e) :multi) + (= (length (item-type e)) (length results)) + (every #'same-type-p (item-type e) results)) + (fail-tok tk "the procedure returns ~d results, of its own types" (length results))) + (let ((vals (loop repeat (length results) collect (var-sym "V")))) + (leave-form `(multiple-value-bind ,vals ,(item-form e) + (values ,@(result-forms vals)))))) + (progn + (unless (= (length items) (length results)) + (fail-tok tk "~d results for a procedure of ~d" (length items) (length results))) + (when (some (lambda (i) (member (item-mode i) '(:multi :none))) items) + (fail-tok tk "a call with several results or none returned among others")) + (leave-form `(values ,@(result-forms + (loop for i in items for ty in results + collect (coerce-item i ty))))))))))) + +;;; defer (7.7): the statement compiled now, run where the list is left. + +(defun defer-statement (tk) + (when (proc-in-defer *proc*) (fail-tok tk "a deferred statement can't defer")) + (let ((forms (let ((saved-loops (proc-loops *proc*))) + (setf (proc-in-defer *proc*) t (proc-loops *proc*) '()) + (push '() (proc-defers *proc*)) + (unwind-protect (statement) + (pop (proc-defers *proc*)) + (setf (proc-in-defer *proc*) nil (proc-loops *proc*) saved-loops))))) + (push `(progn ,@forms) (first (proc-defers *proc*))))) diff --git a/sbcl/src/types.lisp b/sbcl/src/types.lisp new file mode 100644 index 0000000..f5a2a30 --- /dev/null +++ b/sbcl/src/types.lisp @@ -0,0 +1,214 @@ +;;;; types.lisp -- raz's types: what they are, their layout, and when two +;;;; are the same or one is assignable to another. +;;;; +;;;; Report, section 5. A type is a TY. Every type the program writes out +;;;; is a fresh TY; a declaration `type P = ^Node` makes one with a name, +;;;; and `type Count = I64` makes no type at all, only another name for +;;;; I64's. Sameness (5.10) is then a matter of NAME and of what the type +;;;; is built of. + +(in-package :raz) + +;;; KIND is one of +;;; :int :bool :real :error the basic types (BITS and SIGNED for :int, BITS for :real) +;;; :ptr BASE, the type pointed at, and VOL for ^VOLATILE +;;; :array LEN elements of ELEM; :slice elements of ELEM +;;; :record FIELDS, PACKED; :variant CASES +;;; :enum NAMES, strings in order; :set ENUM, an :enum +;;; :proc SIG, a SIG +;;; and, for the values that have no type of their own yet, +;;; :untyped-int, :untyped-real, :string (a string literal), :nil. +;;; MODULE is the module that declared the type, which decides who may +;;; see its unexported fields. + +(defstruct (ty (:print-function (lambda (ty s d) (declare (ignore d)) + (write-string (type-name ty) s)))) + kind name (size 0) (align 1) + bits signed base vol len elem fields packed cases names enum sig module) + +;;; A field of a record, or of a case of a variant: its OFFSET from the +;;; record's start (from the variant's, for a case). +(defstruct field name type offset exported) + +;;; A case of a variant: its INDEX, which is its tag, and its FIELDS. +(defstruct vcase name index fields variant) + +;;; A procedure's signature: PARAMS are (name type var-p) lists, RESULTS +;;; types; VARARGS for an extern's `...`. +(defstruct sig params results varargs) + +(defun word-size () 8) + +;;; The basic types, made once. + +(defun make-int-type (name bits signed) + (make-ty :kind :int :name name :bits bits :signed signed + :size (/ bits 8) :align (/ bits 8))) + +(defparameter *basic-types* + (list (make-int-type "I8" 8 t) (make-int-type "I16" 16 t) + (make-int-type "I32" 32 t) (make-int-type "I64" 64 t) + (make-int-type "U8" 8 nil) (make-int-type "U16" 16 nil) + (make-int-type "U32" 32 nil) (make-int-type "U64" 64 nil) + (make-int-type "INT" 64 t) (make-int-type "UINT" 64 nil) + (make-ty :kind :bool :name "BOOL" :size 1 :align 1) + (make-ty :kind :real :name "F32" :bits 32 :size 4 :align 4) + (make-ty :kind :real :name "F64" :bits 64 :size 8 :align 8) + (make-ty :kind :error :name "ERROR" :size 8 :align 8))) + +(defun basic (name) (find name *basic-types* :key #'ty-name :test #'string=)) + +(defparameter *untyped-int* (make-ty :kind :untyped-int :name "an integer constant")) +(defparameter *untyped-real* (make-ty :kind :untyped-real :name "a real constant")) +(defparameter *nil-type* (make-ty :kind :nil :name "nil")) + +(defun string-type (len) + (make-ty :kind :string :name "a string" :len len)) + +(defun type-name (ty) + (or (ty-name ty) + (case (ty-kind ty) + (:ptr (format nil "^~:[~;VOLATILE ~]~a" (ty-vol ty) (type-name* (ty-base ty)))) + (:array (format nil "[~d]~a" (ty-len ty) (type-name (ty-elem ty)))) + (:slice (format nil "[]~a" (type-name (ty-elem ty)))) + (:record "a record") (:variant "a variant") (:enum "an enumeration") + (:set (format nil "set of ~a" (type-name (ty-enum ty)))) + (:proc "a procedure type") + (t (string-downcase (ty-kind ty)))))) + +(defun type-name* (x) (if (ty-p x) (type-name x) (format nil "~a" (second x)))) + +;;; Kinds of types, as the rules ask about them. + +(defun int-p (ty) (eq (ty-kind ty) :int)) +(defun real-p (ty) (eq (ty-kind ty) :real)) +(defun ptr-p (ty) (eq (ty-kind ty) :ptr)) +(defun aggregate-p (ty) + "A type whose values the compiled code handles by address." + (member (ty-kind ty) '(:array :slice :record :variant :string))) +(defun is (ty kind) (eq (ty-kind ty) kind)) + +;;; A pointer's base may name a type declared later in its `type` +;;; section (section 4): until then BASE is (:forward name), and the +;;; section's end puts the type in its place. +(defun ptr-base (ty) + (let ((b (ty-base ty))) + (when (consp b) (error "pointer base still forward")) + b)) + +;;; Layout (5.5, 5.6). Each field at the next multiple of its alignment, +;;; the whole padded to the largest; a packed record has no padding. + +(defun round-up (n align) (* align (ceiling n align))) + +(defun lay-out-fields (fields start packed) + "Sets each field's offset, from START; returns the end and the largest alignment." + (let ((off start) (align 1)) + (dolist (f fields) + (let ((ft (field-type f))) + (unless packed (setf off (round-up off (ty-align ft)))) + (setf (field-offset f) off) + (incf off (ty-size ft)) + (setf align (max align (if packed 1 (ty-align ft)))))) + (values off align))) + +(defun make-record-type (fields packed module) + (multiple-value-bind (end align) (lay-out-fields fields 0 packed) + (make-ty :kind :record :fields fields :packed packed :module module + :size (round-up end align) :align align))) + +(defun make-variant-type (cases module) + ;; an INT tag, then each case's fields as a record's after it + (let ((size 8) (align 8) (ty (make-ty :kind :variant :cases cases :module module))) + (dolist (c cases) + (setf (vcase-variant c) ty) + (multiple-value-bind (end a) (lay-out-fields (vcase-fields c) 8 nil) + (setf size (max size end) align (max align a)))) + (setf (ty-size ty) (round-up size align) (ty-align ty) align) + ty)) + +(defun make-enum-type (names module) + (make-ty :kind :enum :names names :size 1 :align 1 :module module)) + +(defun make-set-type (enum) + (let ((n (length (ty-names enum)))) + (let ((size (cond ((<= n 8) 1) ((<= n 16) 2) ((<= n 32) 4) (t 8)))) + (make-ty :kind :set :enum enum :size size :align size)))) + +(defun make-ptr-type (base vol) + (make-ty :kind :ptr :base base :vol vol :size 8 :align 8)) + +(defun make-array-type (len elem) + (make-ty :kind :array :len len :elem elem + :size (* len (ty-size elem)) :align (ty-align elem))) + +(defun make-slice-type (elem) + (make-ty :kind :slice :elem elem :size 16 :align 8)) + +(defun make-proc-type (sig) + (make-ty :kind :proc :sig sig :size 8 :align 8)) + +;;; Sameness (5.10). Two named types are the same only if they are one +;;; declaration. A record, variant or enumeration is its own type +;;; wherever it is written. Anonymous pointers, arrays, slices, sets and +;;; procedure types are the same if built alike, and a named type is the +;;; same as an anonymous one it is built like. + +(defun same-type-p (a b) + (cond ((eq a b) t) + ((and (ty-name a) (ty-name b)) nil) + ((not (eq (ty-kind a) (ty-kind b))) nil) + (t (case (ty-kind a) + (:ptr (and (eq (ty-vol a) (ty-vol b)) (same-type-p (ptr-base a) (ptr-base b)))) + (:array (and (= (ty-len a) (ty-len b)) (same-type-p (ty-elem a) (ty-elem b)))) + (:slice (same-type-p (ty-elem a) (ty-elem b))) + (:set (same-type-p (ty-enum a) (ty-enum b))) + (:proc (sig-alike-p (ty-sig a) (ty-sig b))) + (t nil))))) + +(defun sig-alike-p (a b) + "Two signatures are alike: their parameters' types, each var or not +alike, and their results' types (5.9)." + (and (= (length (sig-params a)) (length (sig-params b))) + (= (length (sig-results a)) (length (sig-results b))) + (eq (sig-varargs a) (sig-varargs b)) + (every (lambda (p q) (and (eq (third p) (third q)) (same-type-p (second p) (second q)))) + (sig-params a) (sig-params b)) + (every #'same-type-p (sig-results a) (sig-results b)))) + +;;; Integer ranges. + +(defun int-min (ty) (if (ty-signed ty) (- (expt 2 (1- (ty-bits ty)))) 0)) +(defun int-max (ty) (if (ty-signed ty) (1- (expt 2 (1- (ty-bits ty)))) (1- (expt 2 (ty-bits ty))))) +(defun fits-p (v ty) (<= (int-min ty) v (int-max ty))) + +(defun wrap-int (v ty) + "V cut to TY's width, as the program's arithmetic wraps." + (if (ty-signed ty) + (sb-c::mask-signed-field (ty-bits ty) v) + (ldb (byte (ty-bits ty) 0) v))) + +;;; What can hold a nil, and what compares only for equality. +(defun nil-able-p (ty) (member (ty-kind ty) '(:ptr :proc :error))) + +;;; Elements whose arrays compare with = and # (6.5). +(defun bytewise-comparable-p (ty) + (member (ty-kind ty) '(:int :bool :enum :set :ptr))) + +;;; The kind of memory access a scalar type needs: a keyword the run +;;; time's LD and ST take (rt.lisp). +(defun access-kind (ty) + (ecase (ty-kind ty) + (:int (intern (format nil "~:[U~;I~]~d" (ty-signed ty) (ty-bits ty)) :keyword)) + (:bool :bool) + (:real (if (= (ty-bits ty) 32) :f32 :f64)) + ((:ptr :proc :error) :u64) + (:enum :u8) + (:set (intern (format nil "U~d" (* 8 (ty-size ty))) :keyword)))) + +(defun zero-value (ty) + "The Lisp value a scalar of TY starts at." + (case (ty-kind ty) + (:bool nil) + (:real (if (= (ty-bits ty) 32) 0f0 0d0)) + (t 0)))