Compare commits
37 Commits
a8f8b23b49
...
ae9cdbbf31
| Author | SHA1 | Date | |
|---|---|---|---|
| ae9cdbbf31 | |||
| 66d088f6fc | |||
| 3737f90641 | |||
| 58f145bd95 | |||
| e6b6ca799d | |||
| a6689b8c81 | |||
| b717aa808d | |||
| b49bb8f716 | |||
| a048925c7a | |||
| a14484d1dc | |||
| 42fe477e35 | |||
| 062cb18c60 | |||
| 4e0938ab1f | |||
| 2bad5db114 | |||
| 3e01fe41e8 | |||
| 52228e6fc6 | |||
| 08853d2c77 | |||
| 6fbeaedbe6 | |||
| 9d4454afe3 | |||
| 5a887c0654 | |||
| b5de28342b | |||
| dff4a5af53 | |||
| f24adfa2db | |||
| 82629867c1 | |||
| b0dd2d9f94 | |||
| 169933ff2e | |||
| 0a565046af | |||
| b51cda0af3 | |||
| 9c5f678830 | |||
| 427177d50f | |||
| e91b44dbe1 | |||
| 9af9113bf5 | |||
| 224ef8fb6b | |||
| bb2f05fa36 | |||
| 3baaafafc3 | |||
| 5ba55f05a5 | |||
| f5c53cdd41 |
1
Makefile
1
Makefile
@@ -118,6 +118,7 @@ SEX_TEST_PROGRAMS = c11 \
|
||||
lists \
|
||||
operators \
|
||||
ops \
|
||||
precedence \
|
||||
records \
|
||||
serialize \
|
||||
specs \
|
||||
|
||||
@@ -150,7 +150,8 @@ may be both:
|
||||
#+end_src
|
||||
|
||||
A receiver whose type cannot be worked out --- something out of a header
|
||||
nothing has parsed --- is read as a value, with a warning saying so.
|
||||
nothing has parsed --- is read as a value, with a warning saying so. For a
|
||||
pointer there, ~(%-> p x)~ writes ~p->x~ whatever ~p~ is.
|
||||
|
||||
A method is ~(.name receiver args ...)~ and a field is ~(. receiver
|
||||
name)~, so the shape of a form says which of the two it is without
|
||||
|
||||
@@ -46,10 +46,10 @@ source location. Only statement positions may be walked this way: a
|
||||
(append-map (lambda (s)
|
||||
(let ((src (form-source s)))
|
||||
(if src
|
||||
(list (line-directive src) (walk-expr s))
|
||||
(list (walk-expr s)))))
|
||||
(list (line-directive src) (walk-statement s))
|
||||
(list (walk-statement s)))))
|
||||
(pack-comments stmts))
|
||||
(map walk-expr (pack-comments stmts))))
|
||||
(map walk-statement (pack-comments stmts))))
|
||||
|
||||
(define (walk-stmt s)
|
||||
"A statement in a slot that holds exactly one form -- an `if' arm.
|
||||
@@ -59,8 +59,18 @@ as an `else if' chain, so the anchor and the statement are wrapped in
|
||||
surrounding c-block supplies them)."
|
||||
(let ((src (and (pair? s) (anchor-statements?) (form-source s))))
|
||||
(if src
|
||||
`(%begin ,(line-directive src) ,(walk-expr s))
|
||||
(walk-expr s))))
|
||||
`(%begin ,(line-directive src) ,(walk-statement s))
|
||||
(walk-statement s))))
|
||||
|
||||
;;; Only here is an `if' a statement, with statements for arms that can
|
||||
;;; each be anchored. Anywhere else it is `?:', and a #line between its
|
||||
;;; parts does not compile
|
||||
(define (walk-statement s)
|
||||
(match s
|
||||
(('if . clauses)
|
||||
(with-comments (filter comment-form? clauses)
|
||||
(cons 'if (walk-if-clauses (remove comment-form? clauses)))))
|
||||
(_ (walk-expr s))))
|
||||
|
||||
;;; A `;' comment reads as a form, so one written inside a construct
|
||||
;;; with positional slots lands in a slot and shifts everything after
|
||||
@@ -84,6 +94,22 @@ forms, and what remains."
|
||||
form
|
||||
`(%begin ,@(map walk-expr comments) ,form)))
|
||||
|
||||
;;; (for init test step body ...). C's parens around the header, carried
|
||||
;;; over, leave a call of a `var' in init's slot and the body in test's
|
||||
(define (check-for-header form slots)
|
||||
(cond ((and (pair? slots) (pair? (car slots)) (pair? (caar slots))
|
||||
(eq? 'var (car (caar slots))))
|
||||
(sex-error form "a for header is not grouped: write (for init test step body ...)"))
|
||||
((< (length slots) 3)
|
||||
(sex-error form "malformed for: write (for init test step body ...)"))))
|
||||
|
||||
;;; A case body that declares is a block, so two cases can each declare
|
||||
;;; a `bits', and a declaration can follow the label before C23
|
||||
(define (walk-case-body body)
|
||||
(if (any (lambda (form) (and (pair? form) (eq? 'var (car form)))) body)
|
||||
(list (cons '%block-begin (walk-body body)))
|
||||
(walk-body body)))
|
||||
|
||||
(define (walk-if-clauses clauses)
|
||||
"(test stmt test stmt ... [else-stmt]) -- tests stay expressions."
|
||||
(let loop ((cs clauses) (acc (list)))
|
||||
@@ -102,15 +128,22 @@ forms, and what remains."
|
||||
;;; hand-written vec2__length would collide, and an identifier holding
|
||||
;;; `__' is reserved in C++, which a pub header may be included from.
|
||||
;;; Lifted closures carry a ƛ for the same reason.
|
||||
;;;
|
||||
;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised
|
||||
;;; exclamation mark, both letters. Not the retroflex click ǃ, which
|
||||
;;; looks more like `!' -- enough that clang warns at every use.
|
||||
(define +name-spellings+
|
||||
'(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ")))
|
||||
|
||||
(define (unkebabify sym)
|
||||
(case sym
|
||||
((- -- -> -= / /=) sym) ; bare operators, not names
|
||||
((- -- -> -= / /= ! != ?) sym) ; bare operators, not names
|
||||
(else
|
||||
(string->symbol
|
||||
(irregex-replace/all
|
||||
"/"
|
||||
(irregex-replace/all "-(?!>)" (symbol->string sym) "_")
|
||||
"ː")))))
|
||||
(fold (lambda (spelling name)
|
||||
(irregex-replace/all (car spelling) name (cdr spelling)))
|
||||
(symbol->string sym)
|
||||
+name-spellings+)))))
|
||||
|
||||
(define (atom-to-fmt-c atom)
|
||||
(case atom
|
||||
@@ -195,6 +228,12 @@ forms, and what remains."
|
||||
;; name `->' itself being the threading macro
|
||||
(('%-> . rest) (cons '%-> (map walk-expr rest)))
|
||||
(('var . _) (walk-var form))
|
||||
;; semen has told a type from an expression; only it knows the names
|
||||
;; in scope that make `(* p)' one or the other
|
||||
(('sizeof ('%type type)) `(%sizeof-type ,(walk-type type)))
|
||||
;; semen has already put the target first, the way C writes it
|
||||
(('typedef type name)
|
||||
`(typedef ,(walk-type type) ,(atom-to-fmt-c name)))
|
||||
;; An expression has no room for a statement, so a comment in a
|
||||
;; cast is dropped rather than relocated.
|
||||
(('cast . rest)
|
||||
@@ -209,15 +248,14 @@ forms, and what remains."
|
||||
;; and each is spliced or wrapped according to what the
|
||||
;; corresponding fmt-c procedure accepts.
|
||||
(('do . stmts) (cons '%block-begin (walk-body stmts)))
|
||||
(('if . clauses)
|
||||
(with-comments (filter comment-form? clauses)
|
||||
(cons 'if (walk-if-clauses (remove comment-form? clauses)))))
|
||||
(('if . clauses) (cons 'if (map walk-expr (remove comment-form? clauses))))
|
||||
(('while . rest)
|
||||
(let-values (((comments slots body) (take-slots rest 1)))
|
||||
(with-comments comments
|
||||
(cons* 'while (walk-expr (car slots)) (walk-body body)))))
|
||||
(('for . rest)
|
||||
(let-values (((comments slots body) (take-slots rest 3)))
|
||||
(check-for-header form slots)
|
||||
(with-comments comments
|
||||
(cons* 'for (walk-expr (car slots)) (walk-expr (cadr slots))
|
||||
(walk-expr (caddr slots))
|
||||
@@ -236,12 +274,12 @@ forms, and what remains."
|
||||
(('case . rest)
|
||||
(let-values (((comments slots body) (take-slots rest 1)))
|
||||
(with-comments comments
|
||||
(cons* 'case (walk-expr (car slots)) (walk-body body)))))
|
||||
(cons* 'case (walk-expr (car slots)) (walk-case-body body)))))
|
||||
(('case/fallthrough . rest)
|
||||
(let-values (((comments slots body) (take-slots rest 1)))
|
||||
(with-comments comments
|
||||
(cons* 'case/fallthrough (walk-expr (car slots)) (walk-body body)))))
|
||||
(('default . body) (cons 'default (walk-body body)))
|
||||
(cons* 'case/fallthrough (walk-expr (car slots)) (walk-case-body body)))))
|
||||
(('default . body) (cons 'default (walk-case-body body)))
|
||||
|
||||
;; Drop comments so they will not generate additional comma
|
||||
(else (map walk-expr (remove comment-form? form)))))
|
||||
@@ -316,7 +354,7 @@ forms, and what remains."
|
||||
(match form
|
||||
(('¤ . array-type)
|
||||
(if (array-bound? form)
|
||||
`(%array ,(walk-type (array-element-type form)) ,(last array-type))
|
||||
`(%array ,(walk-type (array-element-type form)) ,(walk-expr (last array-type)))
|
||||
;; sugar for pointer... Do we really need it? Guess why not,
|
||||
;; it's a strong semantic cue
|
||||
`(%array ,(walk-type (array-element-type form)))))
|
||||
@@ -447,11 +485,17 @@ forms, and what remains."
|
||||
(('enum (? symbol? name))
|
||||
`(enum ,(atom-to-fmt-c name)))
|
||||
(('enum (values ...))
|
||||
`(enum ,(map atom-to-fmt-c values)))
|
||||
`(enum ,(map walk-enumerator values)))
|
||||
(('enum name (values ...))
|
||||
`(enum ,(atom-to-fmt-c name) ,(map atom-to-fmt-c values)))
|
||||
`(enum ,(atom-to-fmt-c name) ,(map walk-enumerator values)))
|
||||
(else (sex-error form "malformed enum" form))))
|
||||
|
||||
;;; red -> red, (wire-varint 0) -> wire_varint = 0
|
||||
(define (walk-enumerator value)
|
||||
(match value
|
||||
((name expr) (list (atom-to-fmt-c name) (walk-expr expr)))
|
||||
(_ (atom-to-fmt-c value))))
|
||||
|
||||
(define (walk-extern form)
|
||||
(match form
|
||||
(('fn . _)
|
||||
@@ -499,7 +543,7 @@ forms, and what remains."
|
||||
;; A target is a filename and not an identifier: GL/gl.h is a path,
|
||||
;; and unkebabify would spell it GLːgl.h
|
||||
(('include target) (list '%include target))
|
||||
(('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest))
|
||||
(('define name . body) `(%define ,(walk-expr name) ,@(map walk-expr body)))
|
||||
(else (walk-expr form))))
|
||||
|
||||
;;; Two toplevel forms are separated by a blank line only if they were
|
||||
|
||||
42
reader.scm
42
reader.scm
@@ -179,10 +179,37 @@
|
||||
(cond
|
||||
((string=? s ".") dot-token)
|
||||
((string->number s) => identity)
|
||||
((radix-number s) => identity)
|
||||
((negated-name? s) (list '- (string->symbol (substring s 1))))
|
||||
(else (string->symbol s))))
|
||||
|
||||
;;; #-dispatch: booleans, characters, vectors, block/datum comments,
|
||||
;;; feature expressions
|
||||
;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those
|
||||
;;; numbers: the C written from them says 224 and 5
|
||||
(define (radix-number s)
|
||||
(let* ((negative? (and (> (string-length s) 0) (char=? #\- (string-ref s 0))))
|
||||
(digits (if negative? (substring s 1) s)))
|
||||
(and (> (string-length digits) 2)
|
||||
(char=? #\0 (string-ref digits 0))
|
||||
(let ((radix (case (string-ref digits 1)
|
||||
((#\x #\X) 16)
|
||||
((#\b #\B) 2)
|
||||
(else #f)))
|
||||
(body (substring digits 2)))
|
||||
(and radix
|
||||
(not (memv (string-ref body 0) '(#\+ #\-)))
|
||||
(let ((n (string->number body radix)))
|
||||
(and (exact-integer? n) (if negative? (- n) n))))))))
|
||||
|
||||
;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with
|
||||
;;; a dash, and an operator that does goes on with a non-letter: -> --
|
||||
(define (negated-name? s)
|
||||
(and (> (string-length s) 1)
|
||||
(char=? #\- (string-ref s 0))
|
||||
(let ((c (string-ref s 1)))
|
||||
(or (char-alphabetic? c) (char=? c #\_)))))
|
||||
|
||||
;;; #-dispatch: booleans, characters, vectors, numbers in a radix,
|
||||
;;; block/datum comments, feature expressions
|
||||
(define (read-hash port)
|
||||
(let ((c (get-ch port)))
|
||||
(cond
|
||||
@@ -191,6 +218,9 @@
|
||||
((or (char=? c #\f) (char=? c #\F)) (read-bool port #f))
|
||||
((char=? c #\\) (read-char-lit port))
|
||||
((char=? c #\() (list->vector (read-list port close-paren)))
|
||||
((memv c '(#\x #\X)) (read-radix port 16))
|
||||
((memv c '(#\b #\B)) (read-radix port 2))
|
||||
((memv c '(#\o #\O)) (read-radix port 8))
|
||||
((char=? c #\|) (skip-block-comment port 1) (next-token port))
|
||||
((char=? c #\;) (read-datum port) (next-token port)) ; datum comment
|
||||
((char=? c #\+) (read-conditional port #t))
|
||||
@@ -244,6 +274,14 @@
|
||||
((datum-token? guarded) (next-token port))
|
||||
(else guarded))))
|
||||
|
||||
;;; #x80, #b101, #o10
|
||||
(define (read-radix port radix)
|
||||
(let* ((digits (read-atom-string port))
|
||||
(n (string->number digits radix)))
|
||||
(if (exact-integer? n)
|
||||
n
|
||||
(error "Malformed number" digits))))
|
||||
|
||||
;;; #t / #true / #f / #false. `val' is the boolean; consume any
|
||||
;;; trailing name characters and validate
|
||||
(define (read-bool port val)
|
||||
|
||||
473
semen.scm
473
semen.scm
@@ -2,6 +2,7 @@
|
||||
|
||||
(import
|
||||
scheme
|
||||
(only (scheme base) make-parameter)
|
||||
(chicken base)
|
||||
(chicken keyword)
|
||||
(chicken string)
|
||||
@@ -276,7 +277,8 @@
|
||||
(let* ((env (make-fn-env expanded))
|
||||
;; the parameters are the body's outermost scope
|
||||
(header (map resolve-closure-types (take expanded boundary)))
|
||||
(body (walk-body (drop expanded boundary) env))
|
||||
(body (parameterize ((operand-position? #f))
|
||||
(walk-body (drop expanded boundary) env)))
|
||||
;; A function is header and body stitched together, so the
|
||||
;; result is fresh structure: without this the definition
|
||||
;; has no location, and nothing downstream can say where
|
||||
@@ -346,11 +348,21 @@
|
||||
(append (map (lambda (g) (cons g #t)) given)
|
||||
(filter-map
|
||||
(lambda (w)
|
||||
(and (> (length w) 4) ; carries a body, so a default
|
||||
(and (spec-default? w)
|
||||
(not (find (lambda (g) (eq? (second g) (second w))) given))
|
||||
(cons (substitute-parameter parameter type w) #f)))
|
||||
wanted)))
|
||||
|
||||
;;; A docstring or a comment is not a body, so
|
||||
;;;
|
||||
;;; (fn s ((self (* const T))) void "what s is for")
|
||||
;;;
|
||||
;;; is still a method every realization has to write.
|
||||
(define (spec-default? method)
|
||||
(let-values (((doc fn) (extract-fn-docstring (strip-fn-header-comments method))))
|
||||
(any (lambda (form) (not (comment-form? form)))
|
||||
(drop fn (fn-header-length fn)))))
|
||||
|
||||
(define (check-realization form name type parameter wanted given)
|
||||
(for-each
|
||||
(lambda (g)
|
||||
@@ -369,7 +381,7 @@
|
||||
given)
|
||||
(let ((missing (filter-map
|
||||
(lambda (w)
|
||||
(and (= (length w) 4) ; no body, so required
|
||||
(and (not (spec-default? w))
|
||||
(not (find (lambda (g) (eq? (second g) (second w))) given))
|
||||
(second w)))
|
||||
wanted)))
|
||||
@@ -403,17 +415,30 @@
|
||||
;;; is (pub fn vec2/length ...) plus a registry entry, so that
|
||||
;;; (. v length) can find it later. The block itself never reaches the
|
||||
;;; writer; `pub' inside it means what it means outside.
|
||||
;;;
|
||||
;;; Every method is registered before any body is walked, so one may
|
||||
;;; call another written below it; that one is then declared ahead of
|
||||
;;; the first body, since C wants it declared before the call.
|
||||
(define (process-ops form acc)
|
||||
(let ((type (and (pair? (cdr form)) (cadr form))))
|
||||
(unless (symbol? type)
|
||||
(sex-error form "ops needs a type name" form))
|
||||
(fold (lambda (method acc) (process-op type method acc))
|
||||
acc
|
||||
(cddr form))))
|
||||
(let* ((methods (map (lambda (m) (register-op type m)) (cddr form)))
|
||||
(fns (remove comment-form? methods))
|
||||
(bodies (map (lambda (m)
|
||||
(if (comment-form? m) (list m) (process-fn m (list))))
|
||||
methods))
|
||||
(early (filter (lambda (m)
|
||||
(called-before? (sex-fn-name m) m methods bodies))
|
||||
fns)))
|
||||
(append (append-map identity (reverse bodies))
|
||||
(fold (lambda (m acc) (process-fn (fn-prototype m) acc)) acc early)))))
|
||||
|
||||
(define (process-op type form acc)
|
||||
;;; The method's fn form, renamed to vec2/length, once it is registered
|
||||
;;; under `length'; a comment is passed along
|
||||
(define (register-op type form)
|
||||
(if (comment-form? form)
|
||||
(cons form acc)
|
||||
form
|
||||
(let ((core (and (pair? form) (fn-core form))))
|
||||
(unless (and (pair? core) (eq? (car core) 'fn)
|
||||
(pair? (cdr core)) (symbol? (second core)))
|
||||
@@ -423,7 +448,28 @@
|
||||
(sex-error form "method is already defined on" type name))
|
||||
(let ((qualified (qualify-op type name)))
|
||||
(add-method! type name qualified)
|
||||
(process-fn (rename-fn form qualified) acc))))))
|
||||
;; its signature too, which a call's receiver is fitted to
|
||||
(process-fn (fn-prototype (rename-fn form qualified)) (list))
|
||||
(rename-fn form qualified))))))
|
||||
|
||||
;;; Does a body written above METHOD call it?
|
||||
(define (called-before? name method methods bodies)
|
||||
(let loop ((ms methods) (bs bodies))
|
||||
(and (not (eq? (car ms) method))
|
||||
(or (names? (car bs) name)
|
||||
(loop (cdr ms) (cdr bs))))))
|
||||
|
||||
;;; NAME anywhere in FORM, a literal's contents included
|
||||
(define (names? form name)
|
||||
(cond ((eq? form name) #t)
|
||||
((pair? form) (or (names? (car form) name) (names? (cdr form) name)))
|
||||
((vector? form) (names? (vector->list form) name))
|
||||
(else #f)))
|
||||
|
||||
;;; (pub fn name args ret ...) -> (pub fn name args ret)
|
||||
(define (fn-prototype form)
|
||||
(let ((header (strip-fn-header-comments form)))
|
||||
(copy-form-source! form (take header (fn-header-length header)))))
|
||||
|
||||
(define (rename-fn form name)
|
||||
(if (memq (first form) '(pub extern))
|
||||
@@ -433,17 +479,11 @@
|
||||
(define (make-fn-env fn-form)
|
||||
(let ((env (make-hash-table))
|
||||
(parameters (make-hash-table)))
|
||||
;; `(p (* struct point))' writes the type in one piece and
|
||||
;; `(p * struct point)' spreads it over the rest, so the type is
|
||||
;; the whole tail whenever there is more of it than one element
|
||||
(for-each (lambda (param)
|
||||
(when (and (pair? param) (pair? (cdr param))
|
||||
(named-arg? param))
|
||||
(when (named-arg? param)
|
||||
(hash-table-set! parameters
|
||||
(first param)
|
||||
(if (null? (cddr param))
|
||||
(second param)
|
||||
(cdr param)))))
|
||||
(named-arg-type param))))
|
||||
(sex-fn-arglist fn-form))
|
||||
(set! (hash-table-ref env :fn-name) (sex-fn-name fn-form))
|
||||
(set! (hash-table-ref env :lambda-counter) 0)
|
||||
@@ -452,13 +492,22 @@
|
||||
(set! (hash-table-ref env :scopes) (list parameters))
|
||||
env))
|
||||
|
||||
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int).
|
||||
;;; Anything that is not a plain (name type) -- a variadic tail -- goes
|
||||
;;; through untouched.
|
||||
;;; `(p (* struct point))' writes the type in one piece and
|
||||
;;; `(p * struct point)' spreads it over the rest; both are
|
||||
;;; `(* struct point)'
|
||||
(define (named-arg-type param)
|
||||
(if (null? (cddr param))
|
||||
(second param)
|
||||
(cdr param)))
|
||||
|
||||
;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and
|
||||
;;; (self * const v) is ((* const v)) just as (self (* const v)) is.
|
||||
;;; Anything that names nothing -- a variadic tail -- goes through
|
||||
;;; untouched.
|
||||
(define (arglist-types arglist)
|
||||
(map (lambda (param)
|
||||
(if (and (pair? param) (= 2 (length param)) (named-arg? param))
|
||||
(list (second param))
|
||||
(if (named-arg? param)
|
||||
(list (named-arg-type param))
|
||||
param))
|
||||
arglist))
|
||||
|
||||
@@ -486,9 +535,8 @@
|
||||
;;; (while (< v 0) (var v char 1) ...)
|
||||
;;; (var m _ (+ v 1)) ; double, not char
|
||||
;;;
|
||||
;;; One frame per form, not one per arm: a `case' label opens no scope
|
||||
;;; in C, and an `if' arm can only declare inside a `do', which brings
|
||||
;;; its own.
|
||||
;;; A `case' body gets one too, being written as a block. An `if' arm
|
||||
;;; gets none: it can only declare inside a `do', which brings its own.
|
||||
|
||||
(define (declare-name! env name type)
|
||||
(hash-table-set! (car (hash-table-ref env :scopes)) name type))
|
||||
@@ -525,26 +573,52 @@
|
||||
(list walked))))
|
||||
forms))
|
||||
|
||||
;;; #t while the walk is inside a value -- an initializer, an argument,
|
||||
;;; a returned expression -- where a statement-only form has no C
|
||||
;;; spelling:
|
||||
;;;
|
||||
;;; (var n int (match s ...)) -> int n = switch (s.tag) { ...
|
||||
;;;
|
||||
;;; A condition is not tracked: `walk-parts' takes every slot of an `if'
|
||||
;;; alike.
|
||||
(define operand-position? (make-parameter #f))
|
||||
|
||||
(define (walk-operand form env)
|
||||
(parameterize ((operand-position? #t))
|
||||
(walk-statement form env)))
|
||||
|
||||
;;; FORMS are values written inside PARENT, which is what a diagnostic
|
||||
;;; about one of them points at -- a bare name has no location of its
|
||||
;;; own:
|
||||
;;;
|
||||
;;; (var f (fn ((r float)) shape) shape/circle)
|
||||
(define (walk-operands parent forms env)
|
||||
(for-each (lambda (form)
|
||||
(when (and (symbol? form) (get-constructor form))
|
||||
(sex-error parent
|
||||
"a constructor is not a function; call it from a lambda"
|
||||
form)))
|
||||
forms)
|
||||
(parameterize ((operand-position? #t))
|
||||
(walk-body forms env)))
|
||||
|
||||
(define (walk-statement form env)
|
||||
(cond
|
||||
((vector? form) (walk-initializer form env))
|
||||
((not (list? form)) form)
|
||||
((null? form) form)
|
||||
;; expanded here rather than before the walk, so the macro body can
|
||||
;; ask `(type-of x)' about a local the walk has already passed
|
||||
((macro? form)
|
||||
(let ((expansion (parameterize
|
||||
((current-type-of
|
||||
(lambda (queried)
|
||||
(unresolve-closure-types
|
||||
(expression-type queried env)))))
|
||||
(macroexpand form (list)))))
|
||||
(let ((expansion (expand-call form env)))
|
||||
(if (and (pair? expansion) (null? (cdr expansion)))
|
||||
(walk-statement (car expansion) env)
|
||||
(cons walk-embed-result (walk-body expansion env)))))
|
||||
(else
|
||||
(case (car form)
|
||||
((do for while if switch)
|
||||
(with-scope env (lambda () (walk-parts form env))))
|
||||
((do for while if switch case case/fallthrough default)
|
||||
(parameterize ((operand-position? #f))
|
||||
(with-scope env (lambda () (walk-parts form env)))))
|
||||
|
||||
((lambda)
|
||||
(let ((name (aux-name! env make-lambda-name)))
|
||||
@@ -561,8 +635,8 @@
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,construct ,@(map (lambda (capture)
|
||||
(walk-statement (capture-argument capture)
|
||||
env))
|
||||
(walk-operand (capture-argument capture)
|
||||
env))
|
||||
(fourth form))))))))
|
||||
|
||||
((var)
|
||||
@@ -582,7 +656,7 @@
|
||||
form
|
||||
(append prefix
|
||||
(if (> (length form) 3)
|
||||
(walk-body (drop form 3) env)
|
||||
(walk-operands form (drop form 3) env)
|
||||
(list))))
|
||||
env))
|
||||
(bound (if (>= (length walked) 4)
|
||||
@@ -599,7 +673,7 @@
|
||||
bound))
|
||||
|
||||
((return)
|
||||
(let ((walked (walk-parts form env)))
|
||||
(let ((walked (copy-form-source! form (walk-operands form form env))))
|
||||
(if (>= (length walked) 2)
|
||||
(copy-form-source!
|
||||
walked
|
||||
@@ -609,26 +683,150 @@
|
||||
(cddr walked))))
|
||||
walked)))
|
||||
|
||||
((match) (walk-match form env))
|
||||
((match)
|
||||
(when (operand-position?)
|
||||
(sex-error form "match is a statement, and has no value"))
|
||||
(walk-match form env))
|
||||
|
||||
((dot-access) (walk-member-path form env))
|
||||
|
||||
((sizeof)
|
||||
(if (and (= 2 (length form)) (written-type? (second form) env))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(sizeof (%type ,(resolve-closure-types
|
||||
(expand-type (second form) env)))))
|
||||
(walk-parts form env)))
|
||||
|
||||
(else
|
||||
(if (method-head? (car form))
|
||||
(walk-method-call form env)
|
||||
(let ((closure (receiver-closure-type (car form) env)))
|
||||
(if closure
|
||||
;; the receiver is walked first: `((closure ((x int))
|
||||
;; int () ...) 5)' registers `struct ƛint_int' on the
|
||||
;; way, and the call helper's signature names it
|
||||
(let ((receiver (walk-statement (car form) env)))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,(register-closure-call! closure form)
|
||||
,receiver
|
||||
,@(map (lambda (a) (walk-statement a env))
|
||||
(cdr form)))))
|
||||
(convert-arguments (walk-parts form env) env)))))))))
|
||||
(cond
|
||||
((method-head? (car form)) (walk-method-call form env))
|
||||
((get-constructor (car form))
|
||||
=> (lambda (constructor) (walk-construction form constructor env)))
|
||||
((receiver-closure-type (car form) env)
|
||||
=> (lambda (closure)
|
||||
;; the receiver is walked first: `((closure ((x int))
|
||||
;; int () ...) 5)' registers `struct ƛint_int' on the
|
||||
;; way, and the call helper's signature names it
|
||||
(let ((receiver (walk-operand (car form) env)))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,(register-closure-call! closure form)
|
||||
,receiver
|
||||
,@(walk-operands form (cdr form) env))))))
|
||||
(else
|
||||
(convert-arguments (copy-form-source! form (walk-operands form form env))
|
||||
env))))))))
|
||||
|
||||
;;; (shape/circle 1.0) is the value itself, written where it is used:
|
||||
;;;
|
||||
;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}}
|
||||
;;;
|
||||
;;; so it is a constant where one is wanted, an lvalue a method can take
|
||||
;;; the address of, and a pub sum pastes nothing into the importer but
|
||||
;;; its declarations. A lambda argument is converted against its field
|
||||
;;; the way a call converts one against its parameter.
|
||||
(define (walk-construction form constructor env)
|
||||
(let* ((name (car constructor))
|
||||
(tag (cdr constructor))
|
||||
(fields (variant-fields (get-sum name) tag))
|
||||
(args (walk-operands form (cdr form) env)))
|
||||
(unless (= (length fields) (length args))
|
||||
(sex-error form "variant takes this many fields" tag (length fields)))
|
||||
(sum-literal name tag
|
||||
(map (lambda (field arg) (field-argument field arg env form))
|
||||
fields args))))
|
||||
|
||||
;;; An array field cannot be handed an array, C copying neither, so it
|
||||
;;; is handed the array's elements:
|
||||
;;;
|
||||
;;; (shape/row #(1 2 3 4)) -> ...(struct shapeːrow){{1, 2, 3, 4}}
|
||||
;;; (shape/row a) -> ...(struct shapeːrow){{a[0], a[1], a[2], a[3]}}
|
||||
(define (field-argument field arg env form)
|
||||
(let ((type (second field)))
|
||||
(if (not (array-form? type))
|
||||
(convert-to-closure type arg env form)
|
||||
(let ((given (expression-type arg env)))
|
||||
(cond
|
||||
((brace-initializer? arg) arg)
|
||||
((not (array-form? given))
|
||||
(sex-error form "an array field takes an array" (first field)))
|
||||
((not (eqv? (array-length given) (array-length type)))
|
||||
(sex-error form "array is not as long as its field" (first field)))
|
||||
;; `#([int 4] : 1 2 3 4)' is its own elements
|
||||
((vector? arg) (list->vector (cdr (memq ': (vector->list arg)))))
|
||||
((not (simple-path? arg))
|
||||
(sex-error form "an array is read once per element; bind it to a var first"
|
||||
(first field)))
|
||||
(else (spell-out-array type arg)))))))
|
||||
|
||||
(define (array-form? type)
|
||||
(and (pair? type) (eq? '¤ (car type))))
|
||||
|
||||
;;; [int 4] -> 4, and [int N] -> 4 after (define N 4); #f for a length
|
||||
;;; nothing here can count
|
||||
(define (array-length type)
|
||||
(and (array-bound? type)
|
||||
(let ((bound (last type)))
|
||||
(cond ((and (integer? bound) (exact? bound)) bound)
|
||||
((symbol? bound)
|
||||
(let ((info (get-type-info bound)))
|
||||
(and info (eq? 'define (car info))
|
||||
(let ((value (caddr info)))
|
||||
(and (= 1 (length value))
|
||||
(integer? (car value))
|
||||
(exact? (car value))
|
||||
(car value))))))
|
||||
(else #f)))))
|
||||
|
||||
;;; xs : [int 2] -> #((¤ xs 0) (¤ xs 1))
|
||||
(define (spell-out-array type expr)
|
||||
(list->vector (map (lambda (i) `(¤ ,expr ,i)) (iota (array-length type)))))
|
||||
|
||||
;;; The forms a macro call stands for, with `(type-of x)' answered from
|
||||
;;; ENV
|
||||
(define (expand-call form env)
|
||||
(parameterize ((current-type-of
|
||||
(lambda (queried)
|
||||
(unresolve-closure-types (expression-type queried env)))))
|
||||
(macroexpand form (list))))
|
||||
|
||||
;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions
|
||||
;;; like any other, and the type before `:' is not one
|
||||
(define (walk-literal form env)
|
||||
(let* ((parts (vector->list form))
|
||||
(elements (or (and (memq ': parts) (cdr (memq ': parts))) parts)))
|
||||
(list->vector
|
||||
(append (drop-right parts (length elements))
|
||||
(map (lambda (element) (walk-operand element env)) elements)))))
|
||||
|
||||
;;; #(struct point : (. p x) 2) -- the values are expressions, and the
|
||||
;;; words before a `:' a type that is left as written
|
||||
(define (walk-initializer form env)
|
||||
(let-values (((prefix rest) (break (lambda (e) (eq? e ':))
|
||||
(vector->list form))))
|
||||
(let ((walk (lambda (es) (map (lambda (e) (walk-statement e env)) es))))
|
||||
(list->vector
|
||||
(if (null? rest)
|
||||
(walk prefix)
|
||||
(append prefix (list ':) (walk (cdr rest))))))))
|
||||
|
||||
;;; Is the operand of `sizeof' a type? `(* x)' and `(¤ x i)' are
|
||||
;;; expressions when x is: a name in scope, or a list that is not
|
||||
;;; itself a type. A name nothing declared is one only C knows of, and
|
||||
;;; there that is a type:
|
||||
;;;
|
||||
;;; (* char) (* const char) (* size-t) (unsigned int) types
|
||||
;;; (* p) (* (g)) (¤ xs 0) expressions
|
||||
(define (written-type? form env)
|
||||
(and (pair? form)
|
||||
;; the length a dereference and a subscript have
|
||||
(if (= (length form) (case (car form) ((*) 2) ((¤) 3) (else -1)))
|
||||
(let ((operand (second form)))
|
||||
(if (symbol? operand)
|
||||
(not (or (lookup-name env operand) (get-name-type operand)))
|
||||
(written-type? operand env)))
|
||||
(type-head? form))))
|
||||
|
||||
;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'.
|
||||
(define (resolve-wildcard form env)
|
||||
@@ -779,20 +977,31 @@
|
||||
(else (case (car expr)
|
||||
((dot-access %->) (simple-path? (second expr)))
|
||||
((*) (and (= 2 (length expr)) (simple-path? (second expr))))
|
||||
((¤) (and (= 3 (length expr))
|
||||
(simple-path? (second expr))
|
||||
(or (symbol? (third expr)) (number? (third expr)))))
|
||||
(else #f)))))
|
||||
|
||||
(define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm))))
|
||||
|
||||
(define (check-match form name variants arms)
|
||||
(for-each
|
||||
(lambda (arm)
|
||||
(unless (and (pair? arm)
|
||||
(or (eq? (car arm) 'else)
|
||||
(and (list? (car arm)) (= 2 (length (car arm)))
|
||||
(list? (second (car arm))))))
|
||||
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm)))
|
||||
arms)
|
||||
(let* ((else? (lambda (arm) (eq? (car arm) 'else)))
|
||||
(named (remove else? arms))
|
||||
(covered (map match-arm-variant named)))
|
||||
(when (> (count else? arms) 1)
|
||||
(sex-error form "match has more than one else"))
|
||||
(for-each
|
||||
(lambda (arm)
|
||||
(let* ((variant (match-arm-variant arm))
|
||||
(fields (variant-fields variants variant)))
|
||||
(unless (and (list? (car arm)) (= 2 (length (car arm))))
|
||||
(sex-error form "an arm is ((variant (binders ...)) body ...)" arm))
|
||||
(unless fields
|
||||
(sex-error form "not a variant of" name variant))
|
||||
(unless (= (length fields) (length (second (car arm))))
|
||||
@@ -820,13 +1029,18 @@
|
||||
,@(cdr arm))))))
|
||||
arms)))
|
||||
|
||||
;;; A binder is a copy of its field, an array one included:
|
||||
;;;
|
||||
;;; (var xs [int 2] #((¤ s.u.row.xs 0) (¤ s.u.row.xs 1)))
|
||||
(define (match-bindings scrutinee variant binders fields)
|
||||
(filter-map
|
||||
(lambda (binder field)
|
||||
(and (not (eq? binder '_))
|
||||
`(var ,binder ,(second field)
|
||||
(dot-access (dot-access (dot-access ,scrutinee u) ,variant)
|
||||
,(first field)))))
|
||||
(let ((type (second field))
|
||||
(path `(dot-access (dot-access (dot-access ,scrutinee u) ,variant)
|
||||
,(first field))))
|
||||
`(var ,binder ,type
|
||||
,(if (array-form? type) (spell-out-array type path) path)))))
|
||||
binders fields))
|
||||
|
||||
;;; (.length v) is a call to vec2ːlength; (. v length) is the field
|
||||
@@ -866,17 +1080,24 @@
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,method
|
||||
,(method-receiver method (and target #t)
|
||||
(walk-statement receiver env) form)
|
||||
,@(map (lambda (argument) (walk-statement argument env))
|
||||
(cddr form))))))))
|
||||
,(method-receiver method (or target written) (and target #t)
|
||||
(walk-operand receiver env) form)
|
||||
,@(walk-operands form (cddr form) env)))))))
|
||||
|
||||
;;; A method taking (* Self) wants an address and one taking Self wants
|
||||
;;; a value; the receiver is one or the other, so one of the two gets
|
||||
;;; `&' or `*' put in front of it
|
||||
(define (method-receiver method pointer? receiver form)
|
||||
(let ((wants-pointer? (let ((self (method-self-type method)))
|
||||
(and (pair? self) (eq? '* (car self))))))
|
||||
;;; `&' or `*' put in front of it.
|
||||
;;;
|
||||
;;; OBJECT is what the receiver holds or points at: a `(const v)' handed
|
||||
;;; to a method taking (* v) would be quietly stripped of its const.
|
||||
(define (method-receiver method object pointer? receiver form)
|
||||
(let* ((self (method-self-type method))
|
||||
(wants-pointer? (and (pair? self) (eq? '* (car self)))))
|
||||
(when (and wants-pointer?
|
||||
(const-type? object)
|
||||
(not (const-type? (pointer-target self))))
|
||||
(sex-error form "method may change its receiver, and this one is const"
|
||||
method))
|
||||
(cond ((eq? wants-pointer? pointer?) receiver)
|
||||
((not wants-pointer?) `(* ,receiver))
|
||||
;; `&(f())' is not C, and the method cannot be given a
|
||||
@@ -894,11 +1115,14 @@
|
||||
;;; (. l a x) l : (struct line), l.a : (* struct point) -> l.a->x
|
||||
;;;
|
||||
;;; A type we cannot work out is read as a value, which is what the
|
||||
;;; path would have meant before any of this.
|
||||
;;; path would have meant before any of this. The warning names what
|
||||
;;; could not be typed: the base, or the path up to a field of a struct
|
||||
;;; only C knows -- (. font handle), not font.
|
||||
(define (walk-member-path form env)
|
||||
(let ((base (second form)))
|
||||
(let step ((expr (walk-statement base env))
|
||||
(let step ((expr (walk-operand base env))
|
||||
(type (expression-type base env))
|
||||
(read (list)) ; the fields walked, reversed
|
||||
(fields (cddr form))
|
||||
(told? #f))
|
||||
(if (null? fields)
|
||||
@@ -906,9 +1130,12 @@
|
||||
(let ((target (pointer-target type)))
|
||||
(unless (or type told?)
|
||||
(sex-warning form "cannot type this; `.' reads it as a value"
|
||||
base))
|
||||
(if (null? read)
|
||||
base
|
||||
`(|.| ,base ,@(reverse read)))))
|
||||
(step (list (if target '%-> 'dot-access) expr (car fields))
|
||||
(field-type (or target type) (car fields))
|
||||
(cons (car fields) read)
|
||||
(cdr fields)
|
||||
(or told? (not type))))))))
|
||||
|
||||
@@ -927,8 +1154,10 @@
|
||||
(eq? 'fn (car signature))
|
||||
(pair? (cdr signature))
|
||||
(pair? (second signature))
|
||||
(let ((self (car (second signature))))
|
||||
(if (pair? self) (car self) self)))))
|
||||
(unwrap-type (car (second signature))))))
|
||||
|
||||
(define (const-type? type)
|
||||
(and (pair? type) (eq? 'const (car type))))
|
||||
|
||||
|
||||
(define (as-closure-type type)
|
||||
@@ -970,7 +1199,17 @@
|
||||
(let ((written (car parts)))
|
||||
(if (= 1 (length written)) (car written) written)))))
|
||||
((symbol? expr) (or (lookup-name env expr) (get-name-type expr)))
|
||||
;; the walk expands `(the a)' before it gets there, so its type is
|
||||
;; that of what it expands to:
|
||||
;;
|
||||
;; (.len (the a)) (match (the s) ...) (. (the a) x)
|
||||
((macro? expr)
|
||||
(let ((expansion (expand-call expr env)))
|
||||
(and (pair? expansion) (null? (cdr expansion))
|
||||
(expression-type (car expansion) env))))
|
||||
((not (and (list? expr) (pair? expr))) #f)
|
||||
;; (shape/circle 1.0) -> shape
|
||||
((and (symbol? (car expr)) (get-constructor (car expr))) => car)
|
||||
;; a call of no arguments is still a call
|
||||
((< (length expr) 2)
|
||||
(and (symbol? (car expr)) (get-return-type (car expr))))
|
||||
@@ -1533,9 +1772,19 @@
|
||||
(unless (and (symbol? name) (list? declared) (pair? declared))
|
||||
(sex-error form "sum needs a name and a list of variants" form))
|
||||
(let ((variants (map (lambda (v) (parse-variant form v)) declared)))
|
||||
(for-each (lambda (v)
|
||||
(for-each (lambda (field) (check-variant-field form name field))
|
||||
(cdr v)))
|
||||
variants)
|
||||
(let* ((names (map car variants))
|
||||
(twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names)))
|
||||
(when twice
|
||||
(sex-error form "variant is declared twice" twice)))
|
||||
(when (get-sum name)
|
||||
(sex-error form "sum is already defined" name))
|
||||
(add-sum! name variants)
|
||||
(for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v)))
|
||||
variants)
|
||||
(fold match-sex-form acc
|
||||
(map (lambda (f) (copy-form-source! form f))
|
||||
(sum-forms name variants))))))
|
||||
@@ -1545,6 +1794,25 @@
|
||||
(sex-error form "a variant is (name (fields ...))" v))
|
||||
(cons (car v) (normalize-fields (cadr v))))
|
||||
|
||||
;;; (sum expr ((neg ((e expr))))) has no size; (neg ((e (* expr)))) does.
|
||||
;;; An array field is spelled out element by element wherever it is
|
||||
;;; copied, so its length has to be one sexc can count.
|
||||
(define (check-variant-field form name field)
|
||||
(let ((type (second field)))
|
||||
(when (holds-by-value? type name)
|
||||
(sex-error form "a sum holds itself through a pointer" (first field)))
|
||||
(when (and (array-form? type) (not (array-length type)))
|
||||
(sex-error form "array field needs a length written as a number"
|
||||
(first field)))))
|
||||
|
||||
(define (holds-by-value? type name)
|
||||
(cond ((eq? type name) #t)
|
||||
((not (pair? type)) #f)
|
||||
((memq (car type) '(struct const volatile))
|
||||
(and (pair? (cdr type)) (holds-by-value? (cadr type) name)))
|
||||
((array-form? type) (holds-by-value? (array-element-type type) name))
|
||||
(else #f)))
|
||||
|
||||
(define (sum-forms name variants)
|
||||
(let ((carried (filter (lambda (v) (pair? (cdr v))) variants)))
|
||||
`(;; forward, so a variant may hold a pointer back to the sum
|
||||
@@ -1560,39 +1828,32 @@
|
||||
`((u (union ,(map (lambda (v)
|
||||
`(,(car v)
|
||||
(struct ,(qualify-op name (car v)))))
|
||||
carried)))))))
|
||||
,@(map (lambda (v) (sum-constructor name v)) variants))))
|
||||
carried))))))))))
|
||||
|
||||
;;; (shape/circle 1.0) builds the value in one compound literal, so a
|
||||
;;; constructor is an expression and not three statements
|
||||
;;; Static even when the sum is pub: a pub sum is pasted whole into
|
||||
;;; the importer, and two units defining shapeːcircle would not link.
|
||||
(define (sum-constructor name variant)
|
||||
(let* ((tag (car variant))
|
||||
(fields (cdr variant))
|
||||
(payload (qualify-op name tag)))
|
||||
`(fn ,payload ,fields ,name
|
||||
(return ,(sum-literal name tag payload fields)))))
|
||||
|
||||
;;; #(shape : .tag shapeːtagːcircle .u #(.circle #((struct shapeːcircle) : r)))
|
||||
(define (sum-literal name tag payload fields)
|
||||
;;; #(shape : .tag shapeǂcircle .u #(.circle #((struct shapeːcircle) : 1.0)))
|
||||
(define (sum-literal name tag values)
|
||||
(list->vector
|
||||
(append (list name ': (dotted 'tag) (sum-tag-constant name tag))
|
||||
(if (null? fields)
|
||||
(if (null? values)
|
||||
(list)
|
||||
(list (dotted 'u)
|
||||
(vector (dotted tag)
|
||||
(list->vector
|
||||
(append (list (list 'struct payload) ':)
|
||||
(map car fields)))))))))
|
||||
(append (list (list 'struct (qualify-op name tag)) ':)
|
||||
values))))))))
|
||||
|
||||
(define (dotted name)
|
||||
(string->symbol (string-append "." (symbol->string name))))
|
||||
|
||||
(define (sum-tag name) (qualify-op name 'tag))
|
||||
;;; shape -> enum shapeǂ, circle -> shapeǂcircle. Not shapeːtag: that
|
||||
;;; is where a variant named `tag' keeps its payload struct, and an enum
|
||||
;;; and a struct share C's tag namespace.
|
||||
(define (sum-tag name)
|
||||
(string->symbol (string-append (symbol->string name) "ǂ")))
|
||||
|
||||
(define (sum-tag-constant name variant)
|
||||
(qualify-op (sum-tag name) variant))
|
||||
(string->symbol (string-append (symbol->string (sum-tag name))
|
||||
(symbol->string variant))))
|
||||
|
||||
;;; (record point ((x int) (y int))) is a struct that also names
|
||||
;;; itself, so `point' alone stands where `(struct point)' had to:
|
||||
@@ -1619,7 +1880,9 @@
|
||||
(name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f))))
|
||||
;; An anonymous aggregate has a field list where the name would be,
|
||||
;; and nothing can refer to it by name anyway
|
||||
(when name
|
||||
;; ...and a bodyless one adds nothing to what is known: an importer
|
||||
;; may be handed a declaration after the definition it declares
|
||||
(when (and name (not (and (null? (cddr f)) (get-tag-info name))))
|
||||
(case (car f)
|
||||
((struct) (add-struct name form))
|
||||
((union) (add-union name form))
|
||||
@@ -1627,28 +1890,44 @@
|
||||
|
||||
;;; No function around a toplevel form, so no scope chain: what a
|
||||
;;; global's initializer names comes from `get-name-type' alone.
|
||||
(define (make-toplevel-env)
|
||||
;;; What a global's initializer is walked in: no names but its own,
|
||||
;;; and anything it lifts is named after the global
|
||||
(define (make-toplevel-env name)
|
||||
(let ((env (make-hash-table)))
|
||||
(set! (hash-table-ref env :fn-name) name)
|
||||
(set! (hash-table-ref env :lambda-counter) 0)
|
||||
(set! (hash-table-ref env :lambda-aux-code) (list))
|
||||
(set! (hash-table-ref env :scopes) (list))
|
||||
env))
|
||||
|
||||
;;; The writer spells neither `closure' nor `_', and an initializer is
|
||||
;;; an expression like any other:
|
||||
;;;
|
||||
;;; (var n _ 1) -> int n = 1
|
||||
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
|
||||
(define (process-global-var sex-var acc)
|
||||
;; A global is not walked for lambdas, but the writer spells neither
|
||||
;; `closure' nor `_': `(var n _ 1)' has to reach it as `int n = 1'
|
||||
(let* ((resolved (resolve-closure-types sex-var))
|
||||
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved)))
|
||||
(core (if qualifier (cdr resolved) resolved))
|
||||
(env (make-toplevel-env (and (pair? (cdr core)) (second core))))
|
||||
;; `(extern var n int)' has no initializer to work a `_' out
|
||||
;; from
|
||||
(core (if (eq? 'extern qualifier)
|
||||
core
|
||||
(resolve-wildcard core (make-toplevel-env))))
|
||||
(resolve-wildcard
|
||||
(copy-form-source!
|
||||
core
|
||||
(if (> (length core) 3)
|
||||
(append (take core 3)
|
||||
(walk-operands core (drop core 3) env))
|
||||
core))
|
||||
env)))
|
||||
(form (if qualifier
|
||||
(copy-form-source! resolved (cons qualifier core))
|
||||
core)))
|
||||
(when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core)))
|
||||
(add-name-type! (second core) (third core)))
|
||||
(cons form acc)))
|
||||
(cons form (append (hash-table-ref env :lambda-aux-code) acc))))
|
||||
|
||||
;;; Utils
|
||||
(define (non-empty-list? form)
|
||||
|
||||
106
sex-fmt-c.scm
106
sex-fmt-c.scm
@@ -36,6 +36,7 @@
|
||||
scheme
|
||||
(scheme base) ; string->utf8, bytevector accessors
|
||||
(chicken base)
|
||||
(chicken flonum) ; flonum-print-precision
|
||||
fmt
|
||||
srfi-1
|
||||
srfi-13)
|
||||
@@ -80,6 +81,7 @@
|
||||
((dot arrow post-decrement post-increment) 10)
|
||||
((**) 15) ; Perl
|
||||
((unary+ unary- ! ~ cast unary-* unary-& sizeof) 20) ; ++ --
|
||||
((cast-operand) 25) ; see c-cast
|
||||
((=~ !~) 25) ; Perl
|
||||
((* / %) 30)
|
||||
((+ -) 35)
|
||||
@@ -96,6 +98,7 @@
|
||||
;;((|\|\||) 75)
|
||||
;;((.. ...) 77) ; Perl
|
||||
((?) 80)
|
||||
((conditional-else) 81) ; see c-if/expr
|
||||
((= *= /= %= &= ^= <<= >>=) 85) ; |\|=| ; += -=
|
||||
((comma) 90)
|
||||
((=>) 90) ; Perl
|
||||
@@ -110,6 +113,13 @@
|
||||
|
||||
(define (c-paren x) (cat "(" (c-expr x) ")"))
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: a subscript is postfix, tighter than
|
||||
;; any operator, so what it subscripts is written at the level of
|
||||
;; `.' -- (* q) comes out `(*q)[i]', not `*q[i]', which is *(q[i]).
|
||||
;; The index has brackets of its own and starts afresh.
|
||||
(define (c-subscript array index)
|
||||
(cat (c-with-op "." (c-expr array)) "[" (c-with-op 'paren (c-expr index)) "]"))
|
||||
|
||||
;; `.' and `->' associate left, and their right operand is always a
|
||||
;; name, so a member access written inside another is the left one
|
||||
;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r'
|
||||
@@ -183,7 +193,21 @@
|
||||
((8) (cat "0" (number->string x 8)))
|
||||
(else (dsp (number->string x))))
|
||||
st))
|
||||
(dsp (number->string x))))
|
||||
(dsp (c-format-flonum x))))
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: a double in as few digits as read
|
||||
;; back as the same double. number->string stops at
|
||||
;; flonum-print-precision, 15 unless set, and 0.16666666666666666 came
|
||||
;; out 0.166666666666667: a different double in the C. Seventeen
|
||||
;; always do.
|
||||
(define (c-format-flonum x)
|
||||
(let ((precision (flonum-print-precision)))
|
||||
(let try ((digits 15))
|
||||
(flonum-print-precision digits)
|
||||
(let ((written (number->string x)))
|
||||
(if (or (= digits 17) (= (string->number written) x))
|
||||
(begin (flonum-print-precision precision) written)
|
||||
(try (+ digits 1)))))))
|
||||
|
||||
(define (c-format-string x)
|
||||
(lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st)))
|
||||
@@ -248,12 +272,9 @@
|
||||
;; non C-keywords must have some character invalid in a C
|
||||
;; identifier to avoid conflicts - by default we prefix %
|
||||
((vector-ref)
|
||||
((c-wrap-stmt
|
||||
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
|
||||
st))
|
||||
((c-wrap-stmt (c-subscript (cadr x) (caddr x))) st))
|
||||
((vector-set!)
|
||||
((c= (c-in-expr
|
||||
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
|
||||
((c= (c-in-expr (c-subscript (cadr x) (caddr x)))
|
||||
(c-expr (cadddr x)))
|
||||
st))
|
||||
((extern/C) ((apply c-extern/C (cdr x)) st))
|
||||
@@ -287,6 +308,7 @@
|
||||
((%comment) ((apply c-comment (cdr x)) st))
|
||||
((:) ((apply c-label (cdr x)) st))
|
||||
((%cast) ((apply c-cast (cdr x)) st))
|
||||
((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st))
|
||||
((%compound) ((apply c-compound (cdr x)) st))
|
||||
((%designate) ((apply c-designate (cdr x)) st))
|
||||
((+ - & * / % ! ~ ^ && < > <= >= == != << >>
|
||||
@@ -432,6 +454,15 @@
|
||||
((pair? x) (cons (replace (car x)) (replace (cdr x))))
|
||||
(else x))))
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: an object-like body is parenthesised
|
||||
;; as a function-like one is. Upstream left it bare, so with
|
||||
;; `#define D -1.0 / 6.0', `x * D' was `(x * -1.0) / 6.0'. Only a
|
||||
;; name or a literal that cannot lose its sign to a neighbour is
|
||||
;; left as written.
|
||||
(define (c-atomic-body? x)
|
||||
(or (symbol? x)
|
||||
(and (c-literal? x) (not (and (number? x) (negative? x))))))
|
||||
|
||||
(define (cpp-define x . body)
|
||||
(define (name-of x) (c-expr (if (pair? x) (cadr x) x)))
|
||||
(lambda (st)
|
||||
@@ -449,9 +480,8 @@
|
||||
(cat " "
|
||||
(fmt-let 'writer (make-cpp-writer st)
|
||||
(fmt-let 'macro-params params
|
||||
((if (or (not (pair? x))
|
||||
(and (null? (cdr body))
|
||||
(c-literal? (car body))))
|
||||
((if (and (null? (cdr body))
|
||||
(c-atomic-body? (car body)))
|
||||
(lambda (x) x)
|
||||
c-paren)
|
||||
(c-in-expr (apply c-begin body))))))
|
||||
@@ -805,32 +835,22 @@
|
||||
(fmt-join c-expr name ", ")
|
||||
(c-expr name))))))
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: parenthesise a binary operand.
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: take part in precedence, both ways.
|
||||
;;
|
||||
;; A cast binds tighter than every binary operator, so upstream's
|
||||
;; unparenthesised (cat "(" type ")" expr) silently casts only the
|
||||
;; first operand: (cast (* 2 (sizeof GLfloat)) (* void)) came out as
|
||||
;; `(void *)2 * sizeof(GLfloat)'. Unary operands -- &x, *p, -n,
|
||||
;; sizeof, calls, identifiers, literals -- are already
|
||||
;; unary-expressions and are left alone, so this changes nothing that
|
||||
;; was previously correct.
|
||||
(define c-binary-operators
|
||||
'(+ - * / % << >> < > <= >= == != & ^ && %and %or
|
||||
= *= /= %= &= ^= <<= >>=))
|
||||
|
||||
(define (c-binary-expression? expr)
|
||||
(and (pair? expr)
|
||||
(memq (car expr) c-binary-operators)
|
||||
(pair? (cdr expr))
|
||||
(pair? (cddr expr)))) ; two or more operands
|
||||
|
||||
;; Upstream's bare (cat "(" type ")" expr) cast only the first operand
|
||||
;; of a looser one -- (cast (* 2 (sizeof GLfloat)) (* void)) came out
|
||||
;; `(void *)2 * sizeof(GLfloat)' -- and was itself taken apart by a
|
||||
;; tighter operator around it: `(const wanted *)pa->distance'.
|
||||
;;
|
||||
;; The operand is written at `cast-operand', just looser than a unary
|
||||
;; operator, so a unary operand stays bare -- `(int *)&a' -- while
|
||||
;; anything looser parenthesises itself. The cast is parenthesised
|
||||
;; only under something strictly tighter: `-(int)a', `*(int *)v'.
|
||||
(define (c-cast type expr)
|
||||
(cat "(" (c-type type) ")"
|
||||
(if (c-binary-expression? expr)
|
||||
;; c-with-op stops the operand from parenthesising itself
|
||||
;; a second time inside the parens we just added.
|
||||
(cat "(" (c-with-op 'paren (c-expr expr)) ")")
|
||||
(c-expr expr))))
|
||||
(lambda (st)
|
||||
(let ((cast (cat "(" (c-type type) ")"
|
||||
(c-with-op 'cast-operand (c-expr expr)))))
|
||||
((if (c-op< (fmt-op st) 'cast) (c-paren cast) cast) st))))
|
||||
|
||||
;; { a, b, c } -- on one line if it fits, one element per line if not.
|
||||
(define (c-braced-list ls)
|
||||
@@ -881,7 +901,18 @@
|
||||
tail))))
|
||||
st))))
|
||||
|
||||
(define (c-if/expr c p . rest)
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: parenthesised as the operator it is.
|
||||
;; Upstream wrote it bare whatever surrounded it, and `?:' binds
|
||||
;; looser than every binary operator: (/ 300 (if c c 1)) came out
|
||||
;; `300 / c ? c : 1', a conditional on the quotient.
|
||||
;;
|
||||
;; It groups to the right, so its else arm is written at
|
||||
;; `conditional-else', just looser: a chain there stays bare,
|
||||
;; `a ? x : b ? y : z', and an assignment does not.
|
||||
(define (c-if/expr . args)
|
||||
(c-maybe-paren '? (apply c-if/expr/aux args)))
|
||||
|
||||
(define (c-if/expr/aux c p . rest)
|
||||
(let lp ((c c) (p p) (ls rest))
|
||||
(cond
|
||||
((or (eq? c 'else) (eq? c #t))
|
||||
@@ -890,9 +921,10 @@
|
||||
(c-expr p)))
|
||||
((pair? ls)
|
||||
(cat (c-in-test (c-expr c)) " ? " (c-expr p) " : "
|
||||
(if (pair? (cdr ls))
|
||||
(lp (car ls) (cadr ls) (cddr ls))
|
||||
(lp 'else (car ls) '()))))
|
||||
(c-with-op 'conditional-else
|
||||
(if (pair? (cdr ls))
|
||||
(lp (car ls) (cadr ls) (cddr ls))
|
||||
(lp 'else (car ls) '())))))
|
||||
(else
|
||||
(c-or (c-in-test (c-expr c)) (c-expr p))))))
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
|
||||
"import"
|
||||
"include"
|
||||
"fn"
|
||||
"ops"
|
||||
"pub"
|
||||
"record"
|
||||
"realize"
|
||||
@@ -62,6 +63,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
|
||||
"if"
|
||||
"for"
|
||||
"goto"
|
||||
"match"
|
||||
"return"
|
||||
"switch"
|
||||
"var"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
(module sex-modules
|
||||
(get-modules-public-forms
|
||||
load-persistent-module-paths
|
||||
check-public-interface
|
||||
module-dependencies
|
||||
read-public-interface)
|
||||
"sex-modules.scm")
|
||||
|
||||
224
sex-modules.scm
224
sex-modules.scm
@@ -78,17 +78,230 @@
|
||||
(file-readable? module-path)
|
||||
module-path))))
|
||||
|
||||
;;; Every module file read for this unit, first read first: what its
|
||||
;;; output depends on, besides the unit itself
|
||||
(define +module-dependencies+ (list))
|
||||
|
||||
(define (module-dependencies) (reverse +module-dependencies+))
|
||||
|
||||
(define (read-module path)
|
||||
(unless (member path +module-dependencies+)
|
||||
(set! +module-dependencies+ (cons path +module-dependencies+)))
|
||||
(read-from-file path))
|
||||
|
||||
(define (read-public-interface module-path)
|
||||
;; pub fns are reduced to prototypes, other pub forms are just pasted.
|
||||
;; Declaration order is kept: a module that declares a type and then a
|
||||
;; pub fn taking it has to paste them that way round, or the prototype
|
||||
;; names a type C has not seen.
|
||||
(let ((raw-forms (read-from-file module-path)))
|
||||
;; names a type C has not seen. The declarations of the types its
|
||||
;; importers see only behind a pointer go first.
|
||||
(let ((raw-forms (read-module module-path)))
|
||||
(append (check-public-interface raw-forms)
|
||||
(interface-forms raw-forms))))
|
||||
|
||||
(define (interface-forms raw-forms)
|
||||
(reverse (fold process-public-interface-form (list) raw-forms)))
|
||||
|
||||
;;; What importers can see of a module's types
|
||||
;;;
|
||||
;;; They are given the pub forms and nothing else, so a pub form that
|
||||
;;; names a type not among them compiled here and failed there:
|
||||
;;; (pub record shape ((cells (* cell)))) with `cell' private told the
|
||||
;;; importer `unknown type name cell'. A record behind a pointer needs
|
||||
;;; only declaring, and its declaration goes out with the pub forms.
|
||||
;;; Held by value it needs its body; and a typedef or an enum has no
|
||||
;;; declaration short of its definition. Those are errors here, where
|
||||
;;; they were written. A name Sex has no declaration for is one only C
|
||||
;;; knows, and is left to C.
|
||||
|
||||
;;; The bodyless declarations FORMS' importers need, in the order the
|
||||
;;; pub forms ask for them. An error when a pub form needs more than a
|
||||
;;; declaration of a type they cannot see.
|
||||
(define (check-public-interface forms)
|
||||
(let ((visible (visible-types forms))
|
||||
(hidden (hidden-types forms)))
|
||||
(reverse
|
||||
(fold
|
||||
process-public-interface-form
|
||||
(lambda (form acc)
|
||||
(fold (lambda (use acc) (check-type-use form use visible hidden acc))
|
||||
acc
|
||||
(append-map (lambda (type) (type-uses type #f))
|
||||
(interface-types form))))
|
||||
(list)
|
||||
raw-forms))))
|
||||
forms))))
|
||||
|
||||
;;; USE is (name . behind-a-pointer?)
|
||||
(define (check-type-use form use visible hidden acc)
|
||||
(let* ((name (car use))
|
||||
(seen (assq name visible))
|
||||
(kept (assq name hidden)))
|
||||
(cond
|
||||
((and seen (third seen)) acc) ; pub with its body
|
||||
((and seen (cdr use)) acc) ; a pub handle, held by one
|
||||
(seen
|
||||
(sex-error form "only a handle of this type is pub, so hold it through a pointer"
|
||||
name))
|
||||
((not kept) acc)
|
||||
((not (memq (second kept) '(record struct union sum)))
|
||||
(sex-error form (string-append "importers cannot see this "
|
||||
(symbol->string (second kept))
|
||||
", and C declares one only by defining it; "
|
||||
(if (fourth kept)
|
||||
"import its module with pub"
|
||||
"make it pub"))
|
||||
name))
|
||||
((not (cdr use))
|
||||
(sex-error form (string-append "importers cannot see this type, held by value; "
|
||||
(if (fourth kept)
|
||||
"import its module with pub"
|
||||
"make it pub")
|
||||
", or hold it through a pointer")
|
||||
name))
|
||||
((any (lambda (f) (eq? name (cadr f))) acc) acc)
|
||||
(else
|
||||
(cons (copy-form-source!
|
||||
form
|
||||
(list (if (memq (second kept) '(record sum)) 'record (second kept))
|
||||
name))
|
||||
acc)))))
|
||||
|
||||
;;; The type forms a pub form shows its importers
|
||||
;;;
|
||||
;;; (pub fn f ((c (* cell)) (n int)) shape) -> ((* cell) int shape)
|
||||
(define (interface-types form)
|
||||
(match form
|
||||
(('pub 'fn . _)
|
||||
(match (strip-header-comments form 5)
|
||||
(('pub 'fn name (args ...) ret . _) (signature-types args ret))
|
||||
(_ (list))))
|
||||
(('pub 'var . _)
|
||||
(match (strip-header-comments form 4)
|
||||
(('pub 'var name type . _) (list type))
|
||||
(_ (list))))
|
||||
(('pub 'typedef name target) (list target))
|
||||
(('pub 'define name . body) body)
|
||||
(('pub (or 'record 'struct 'union) name . rest)
|
||||
(field-types (find list? (remove comment-form? rest))))
|
||||
(('pub 'sum name (variants ...))
|
||||
(append-map (lambda (v)
|
||||
(if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list)))
|
||||
(remove comment-form? variants)))
|
||||
(('ops type . methods)
|
||||
(append-map interface-types
|
||||
(filter (lambda (m) (and (pair? m) (eq? (car m) 'pub))) methods)))
|
||||
(('pub 'realize spec . methods)
|
||||
(append-map (lambda (m) (interface-types (cons 'pub m)))
|
||||
(remove comment-form? methods)))
|
||||
(_ (list))))
|
||||
|
||||
(define (field-types fields)
|
||||
(if (list? fields) (map second (normalize-fields fields)) (list)))
|
||||
|
||||
(define (signature-types args ret)
|
||||
(cons ret (map arg-type (remove comment-form? args))))
|
||||
|
||||
;;; (f1 float) -> float, (n unsigned int) -> (unsigned int), (int) -> (int)
|
||||
(define (arg-type arg)
|
||||
(cond ((not (named-arg? arg)) arg)
|
||||
((null? (cddr arg)) (second arg))
|
||||
(else (cdr arg))))
|
||||
|
||||
;;; Each name TYPE mentions, and whether it is behind a pointer:
|
||||
;;;
|
||||
;;; (* const cell) -> ((const . #t) (cell . #t))
|
||||
;;; [cell 4] -> ((cell . #f))
|
||||
;;; (fn ((cell)) int) -> ((cell . #t) (int . #t)) ; declaring is enough
|
||||
(define (type-uses type behind?)
|
||||
(cond
|
||||
((symbol? type) (list (cons type behind?)))
|
||||
((not (pair? type)) (list))
|
||||
(else
|
||||
(case (car type)
|
||||
((*) (append-map (lambda (t) (type-uses t #t)) (cdr type)))
|
||||
((¤) (let ((element (array-element-type type)))
|
||||
(append (if element (type-uses element behind?) (list))
|
||||
(if (array-bound? type) (bound-uses (last type)) (list)))))
|
||||
((fn closure)
|
||||
(if (and (pair? (cdr type)) (list? (second type)))
|
||||
(append-map (lambda (t) (type-uses t #t))
|
||||
(signature-types (second type) (last type)))
|
||||
(list)))
|
||||
((struct union enum)
|
||||
(if (and (pair? (cdr type)) (symbol? (second type)))
|
||||
(list (cons (second type) behind?))
|
||||
(list)))
|
||||
(else (append-map (lambda (t) (type-uses t behind?)) type))))))
|
||||
|
||||
;;; [int (* 2 N)] needs N, as a value: there is no declaring it
|
||||
(define (bound-uses bound)
|
||||
(cond ((symbol? bound) (list (cons bound #f)))
|
||||
((pair? bound) (append-map bound-uses (cdr bound)))
|
||||
(else (list))))
|
||||
|
||||
;;; The types and constants FORMS declare, as (name kind body?):
|
||||
;;;
|
||||
;;; (pub record tally) -> (tally record #f)
|
||||
;;; (sum colour ((none ()))) -> (colour sum #t)
|
||||
;;; (define (sq x) (* x x)) -> (sq define #t)
|
||||
(define (declared-types forms)
|
||||
(filter-map
|
||||
(lambda (form)
|
||||
(and (pair? form)
|
||||
(let* ((core (if (pub-form? form) (cdr form) form))
|
||||
(name (and (pair? core) (pair? (cdr core))
|
||||
(if (and (eq? (car core) 'define) (pair? (second core)))
|
||||
(car (second core))
|
||||
(second core)))))
|
||||
(and (memq (car core) '(record struct union enum sum typedef define))
|
||||
(symbol? name)
|
||||
(list name
|
||||
(car core)
|
||||
(or (memq (car core) '(typedef define))
|
||||
(any list? (remove comment-form? (cddr core)))))))))
|
||||
forms))
|
||||
|
||||
(define (pub-form? form) (and (pair? form) (eq? (car form) 'pub)))
|
||||
|
||||
;;; Pub here or through a pub import. A type declared pub both bodyless
|
||||
;;; and whole is whole
|
||||
(define (visible-types forms)
|
||||
(let ((all (append (declared-types (filter pub-form? forms))
|
||||
(append-map exported-types (imported-modules forms #t)))))
|
||||
(map (lambda (entry)
|
||||
(list (first entry) (second entry)
|
||||
(any third (filter (lambda (e) (eq? (first e) (first entry))) all))))
|
||||
all)))
|
||||
|
||||
;;; Declared here without pub, or brought by an import without it, as
|
||||
;;; (name kind body? imported?)
|
||||
(define (hidden-types forms)
|
||||
(append (map (lambda (entry) (append entry (list #f)))
|
||||
(declared-types (remove pub-form? forms)))
|
||||
(map (lambda (entry) (append entry (list #t)))
|
||||
(append-map exported-types (imported-modules forms #f)))))
|
||||
|
||||
;;; The names of the modules FORMS import, with pub or without
|
||||
(define (imported-modules forms pub?)
|
||||
(append-map (lambda (form)
|
||||
(match form
|
||||
(('pub 'import . modules) (if pub? modules (list)))
|
||||
(('import . modules) (if pub? (list) modules))
|
||||
(_ (list))))
|
||||
forms))
|
||||
|
||||
;;; The types a module gives its importers, its pub imports' included.
|
||||
;;; Two modules may import each other, so each is read once
|
||||
(define (exported-types module)
|
||||
(let read ((modules (list module)) (seen (list)) (acc (list)))
|
||||
(if (null? modules)
|
||||
acc
|
||||
(let ((path (locate-module (symbol->string (car modules)))))
|
||||
(if (or (not path) (member path seen))
|
||||
(read (cdr modules) seen acc)
|
||||
(let ((forms (interface-forms (read-module path))))
|
||||
(read (append (cdr modules) (imported-modules forms #f))
|
||||
(cons path seen)
|
||||
(append acc (declared-types forms)))))))))
|
||||
|
||||
(define (public-fn-interface raw-form)
|
||||
;; (pub fn name args ret . body) -> prototype, keeping a docstring so
|
||||
@@ -159,6 +372,5 @@
|
||||
(get-env-var "SEX_MODULE_PATH")))
|
||||
(when sex-module-path-env-var
|
||||
(set! +persistent-module-paths+
|
||||
(map (lambda (p)
|
||||
(make-absolute-pathname p #f #f))
|
||||
(map to-absolute-pathname
|
||||
(string-split sex-module-path-env-var ":"))))))
|
||||
|
||||
73
sexc.scm
73
sexc.scm
@@ -59,10 +59,16 @@
|
||||
(value #f)
|
||||
(single-char #\m))
|
||||
(output ,(fmt #f "Write output to file. Default file name is a.out." nl
|
||||
(pad padding) "If -E or -m options are provided, defaults to stdout")
|
||||
(pad padding) "If -C or -m options are provided, defaults to stdout;" nl
|
||||
(pad padding) "`-' is stdout too")
|
||||
(required #f)
|
||||
(value #t)
|
||||
(single-char #\o))
|
||||
(depfile
|
||||
,(fmt #f "Write a make rule for the output to FILE: it depends on" nl
|
||||
(pad padding) "the source and on every module read for it. Needs -o")
|
||||
(required #f)
|
||||
(value #t))
|
||||
(line-directives
|
||||
,(fmt #f "How much #line information to emit: statement (default)," nl
|
||||
(pad padding) "toplevel, or none. `statement' is what makes a debugger" nl
|
||||
@@ -100,6 +106,17 @@
|
||||
(list)
|
||||
(cdr tail))))
|
||||
|
||||
;;; getopt-long reads a lone `-' as an option, so `-o -' died there as
|
||||
;;; one missing its value. `--output=-' is the spelling it takes
|
||||
(define (spell-stdout-output argv)
|
||||
(let loop ((as argv) (acc (list)))
|
||||
(cond ((null? as) (reverse acc))
|
||||
((and (member (car as) '("-o" "--output"))
|
||||
(pair? (cdr as))
|
||||
(string=? (cadr as) "-"))
|
||||
(loop (cddr as) (cons "--output=-" acc)))
|
||||
(else (loop (cdr as) (cons (car as) acc))))))
|
||||
|
||||
(define (get-rest-args args)
|
||||
(cdr (assoc '@ args)))
|
||||
|
||||
@@ -126,7 +143,7 @@
|
||||
(car rest-args))))
|
||||
|
||||
(define (write-to-file-or-stdout output what)
|
||||
(if (eq? output 'default)
|
||||
(if (or (eq? output 'default) (equal? output "-"))
|
||||
(what)
|
||||
(with-output-to-file output
|
||||
(fn (what)))))
|
||||
@@ -138,6 +155,28 @@
|
||||
(map pp sex-forms)
|
||||
(emit-c sex-forms)))))
|
||||
|
||||
;;; app.o: app.sex /m/greet.sex, and an empty rule per module, so that
|
||||
;;; make takes a module deleted since as out of date rather than as a
|
||||
;;; file it has no rule to make
|
||||
(define (dependency-rule target source modules)
|
||||
(let ((spell (lambda (path) (string-translate* path '((" " . "\\ "))))))
|
||||
(apply string-append
|
||||
(spell target) ":"
|
||||
(append (map (lambda (path) (string-append " " (spell path)))
|
||||
(if source (cons source modules) modules))
|
||||
(list "\n")
|
||||
(map (lambda (path) (string-append "\n" (spell path) ":\n"))
|
||||
modules)))))
|
||||
|
||||
(define (write-dependencies depfile output input)
|
||||
(when (or (eq? output 'default) (equal? output "-"))
|
||||
(error "--depfile needs -o, to name what depends on the modules"))
|
||||
(with-output-to-file depfile
|
||||
(lambda ()
|
||||
(display (dependency-rule output
|
||||
(and (not (eq? input 'stdin)) input)
|
||||
(module-dependencies))))))
|
||||
|
||||
(define (compile-to-file sex-forms output args cc-args)
|
||||
"Hand the generated C to the C compiler. Returns the compiler's exit
|
||||
status, which is ours to pass on."
|
||||
@@ -168,11 +207,15 @@ status, which is ours to pass on."
|
||||
(delete-file* c-file)
|
||||
(if normal-exit? status 1)))))))
|
||||
|
||||
(define (semantic-process-forms raw-forms input-source)
|
||||
(if (eq? input-source 'stdin)
|
||||
(semen-process raw-forms)
|
||||
(with-directory input-source
|
||||
(semen-process raw-forms))))
|
||||
;;; The unit's own forms are checked for what its importers will need,
|
||||
;;; the prelude's not: every unit has those
|
||||
(define (semantic-process-forms unit-forms input-source)
|
||||
(let ((process (lambda ()
|
||||
(check-public-interface unit-forms)
|
||||
(semen-process (append prelude unit-forms)))))
|
||||
(if (eq? input-source 'stdin)
|
||||
(process)
|
||||
(with-directory input-source (process)))))
|
||||
|
||||
(define prelude
|
||||
(append
|
||||
@@ -196,7 +239,7 @@ status, which is ours to pass on."
|
||||
(let* ((argv (command-line-arguments))
|
||||
(raw-args (args-before-separator argv))
|
||||
(cc-args (args-after-separator argv))
|
||||
(args (getopt-long raw-args
|
||||
(args (getopt-long (spell-stdout-output raw-args)
|
||||
opts-grammar))
|
||||
(output (get-arg args 'output 'default))
|
||||
(help (help-arg? args))
|
||||
@@ -216,16 +259,18 @@ status, which is ours to pass on."
|
||||
(platform-features))
|
||||
(cli-features args)))
|
||||
|
||||
;; before the interface too, which asks the modules it imports
|
||||
;; what types they export
|
||||
(load-persistent-module-paths)
|
||||
|
||||
(when (get-arg args 'public-interface #f)
|
||||
(assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument")
|
||||
|
||||
(write-to-file-or-stdout
|
||||
output
|
||||
(fn
|
||||
(map pp (reverse
|
||||
(read-public-interface input)))))
|
||||
(map pp (read-public-interface input))))
|
||||
(return #f))
|
||||
(load-persistent-module-paths)
|
||||
|
||||
;; The file name in a #line directive now comes from the form's
|
||||
;; own recorded location, so imported modules report themselves
|
||||
@@ -235,8 +280,10 @@ status, which is ours to pass on."
|
||||
(not (get-arg args 'line-directives #f)))
|
||||
(sex-line-directives 'none))
|
||||
|
||||
(let* ((raw-forms (append prelude (read-raw-forms input)))
|
||||
(sex-forms (semantic-process-forms raw-forms input)))
|
||||
(let ((sex-forms (semantic-process-forms (read-raw-forms input) input)))
|
||||
(let ((depfile (get-arg args 'depfile #f)))
|
||||
(when depfile
|
||||
(write-dependencies depfile output input)))
|
||||
(if (or (get-arg args 'macro-expand #f)
|
||||
(get-arg args 'emit-c #f))
|
||||
;; Emit processed and macro-expanded sex code, or emit C code
|
||||
|
||||
@@ -6,7 +6,7 @@ MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
|
||||
MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc
|
||||
SEX_OBJ = $(MODULES:%=%.o)
|
||||
|
||||
TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args types infer
|
||||
TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args module-path types infer
|
||||
TEST_SRCS = $(TESTS:%=%.scm)
|
||||
|
||||
sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ)
|
||||
|
||||
@@ -52,4 +52,32 @@
|
||||
|
||||
(test "an empty command line is handled"
|
||||
'()
|
||||
(args-before-separator '())))
|
||||
(args-before-separator '()))
|
||||
|
||||
;; getopt-long reads a lone `-' as an option and refused `-o -', so
|
||||
;; it is handed the one spelling it takes a dash in
|
||||
(test "-o - reaches getopt-long as a value"
|
||||
'("x.sex" "--output=-" "-C")
|
||||
(spell-stdout-output '("x.sex" "-o" "-" "-C")))
|
||||
(test "and so does --output -"
|
||||
'("--output=-")
|
||||
(spell-stdout-output '("--output" "-")))
|
||||
(test "any other output is left alone"
|
||||
'("-o" "out" "-")
|
||||
(spell-stdout-output '("-o" "out" "-"))))
|
||||
|
||||
;;; --depfile: an import pastes another file's forms into the output, so
|
||||
;;; the output depends on that file as a C object does on a header
|
||||
(test-group "dependency rule"
|
||||
(test "the target, the source and the modules, then a rule per module"
|
||||
"app.o: app.sex /m/greet.sex /m/ledger.sex\n\n/m/greet.sex:\n\n/m/ledger.sex:\n"
|
||||
(dependency-rule "app.o" "app.sex" '("/m/greet.sex" "/m/ledger.sex")))
|
||||
(test "no modules, no rules of their own"
|
||||
"app.o: app.sex\n"
|
||||
(dependency-rule "app.o" "app.sex" '()))
|
||||
(test "a space is escaped, the way make reads it"
|
||||
"a\\ b.o: a\\ b.sex\n"
|
||||
(dependency-rule "a b.o" "a b.sex" '()))
|
||||
(test "stdin is no file to depend on"
|
||||
"app.o: /m/greet.sex\n\n/m/greet.sex:\n"
|
||||
(dependency-rule "app.o" #f '("/m/greet.sex"))))
|
||||
|
||||
@@ -13,6 +13,13 @@
|
||||
(test '_this_->_member_ (unkebabify '-this-->-member-))
|
||||
(test '__->>> (unkebabify '--->>>))
|
||||
|
||||
;; A Lisp predicate and mutator, in letters C takes. The operators
|
||||
;; spelled with the same characters are not names
|
||||
(test 'ident_startʔ (unkebabify 'ident-start?))
|
||||
(test 'resetꜝ (unkebabify 'reset!))
|
||||
(test '! (unkebabify '!))
|
||||
(test '!= (unkebabify '!=))
|
||||
|
||||
;; Non-ASCII identifiers must survive intact. The `regex' egg's
|
||||
;; string-substitute drops one trailing character per multi-byte
|
||||
;; character, which renames things silently -- the C still compiles,
|
||||
|
||||
@@ -53,6 +53,15 @@ compiles."
|
||||
(let ((m (error-message source)))
|
||||
(and m (string-contains m fragment) #t)))
|
||||
|
||||
(define (followed-by? source first then)
|
||||
"Is FIRST in the C compiled from SOURCE, and the next thing past it,
|
||||
whitespace aside, THEN?"
|
||||
(let* ((c (silently (lambda () (sex->c source))))
|
||||
(at (string-contains c first)))
|
||||
(and at
|
||||
(let ((next (string-skip c char-whitespace? (+ at (string-length first)))))
|
||||
(and next (string-prefix? then (substring c next)))))))
|
||||
|
||||
(define (in-fn body)
|
||||
(string-append "(fn f ((a int) (b int)) void " body ")"))
|
||||
|
||||
@@ -78,6 +87,22 @@ compiles."
|
||||
;; c-switch handed its scrutinee straight to `cat', which only works
|
||||
;; when it is an atom. Anything else was displayed as a raw
|
||||
;; s-expression: `switch ((%. e type))'.
|
||||
;; A case body shared the switch's scope, so two cases could not
|
||||
;; declare one name, and a label could not be followed by a
|
||||
;; declaration before C23. Only a body that declares needs a block
|
||||
(test-group "case bodies"
|
||||
(test-assert "are blocks"
|
||||
(followed-by? (in-fn "(switch a (case 1 (var x int 1) (g x)))")
|
||||
"case 1:" "{"))
|
||||
(test-assert "so is a default"
|
||||
(followed-by? (in-fn "(switch a (default (var x int 1) (g x)))")
|
||||
"default:" "{"))
|
||||
(test-assert "where they declare"
|
||||
(followed-by? (in-fn "(switch a (case 1 (g a)))") "case 1:" "g(a)"))
|
||||
(test-assert "and one already a block is not wrapped again"
|
||||
(not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))")
|
||||
"{" "{"))))
|
||||
|
||||
(test-group "switch scrutinee"
|
||||
(test-assert "member access"
|
||||
(emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))"
|
||||
@@ -114,7 +139,58 @@ compiles."
|
||||
"(int *)&a"))
|
||||
(test-assert "sizeof is left bare"
|
||||
(emits? (in-fn "(var n int (cast (sizeof int) int))")
|
||||
"(int)sizeof(int)")))
|
||||
"(int)sizeof(int)"))
|
||||
;; `|' reaches fmt-c as a string, which a list of binary heads to
|
||||
;; parenthesise did not have
|
||||
(test-assert "bitwise operand is parenthesised"
|
||||
(emits? (in-fn "(var f float (cast (| a b) float))")
|
||||
"(float)(a | b)"))
|
||||
(test-assert "conditional operand is parenthesised"
|
||||
(emits? (in-fn "(var f float (cast (if a a b) float))")
|
||||
"(float)(a ? a : b)"))
|
||||
;; A cast is the operand here, and binds looser than `->'
|
||||
(test-assert "cast under a member access is parenthesised"
|
||||
(emits? (in-line "(var v (* void) pp) (var x int (. (cast v (* struct point)) x))")
|
||||
"((struct point*)v)->x"))
|
||||
(test-assert "cast under a unary operator is left bare"
|
||||
(emits? (in-line "(var v (* void) pp) (var x int (* (cast v (* int))))")
|
||||
"*(int *)v")))
|
||||
|
||||
;; `?:' binds looser than every binary operator, so as an operand it
|
||||
;; has to be parenthesised, or C takes the operator into its test
|
||||
(test-group "conditional expression precedence"
|
||||
(test-assert "operand of a binary operator"
|
||||
(emits? (in-fn "(var x int (/ a (if a a b)))")
|
||||
"a / (a ? a : b)"))
|
||||
(test-assert "left bare where it is the whole value"
|
||||
(emits? (in-fn "(var x int (if a a b))")
|
||||
"int x = a ? a : b"))
|
||||
(test-assert "left bare as an argument"
|
||||
(emits? (in-fn "(g (if a a b) b)")
|
||||
"g(a ? a : b, b)"))
|
||||
;; ?: groups to the right, so a chain needs none in its else arm
|
||||
(test-assert "a chain in the else arm is left bare"
|
||||
(emits? (in-fn "(var x int (if a a (if b b 0)))")
|
||||
"a ? a : b ? b : 0"))
|
||||
(test-assert "but an assignment there is not"
|
||||
(emits? (in-fn "(var x int (if a a (= b 1)))")
|
||||
"a ? a : (b = 1)")))
|
||||
|
||||
;; A subscript binds tighter than anything, so what it subscripts is
|
||||
;; parenthesised whenever it is an operator: `*q[i]' is *(q[i])
|
||||
(test-group "subscript precedence"
|
||||
(test-assert "a dereference"
|
||||
(emits? "(fn f ((q (* * int)) (i int)) int (return [(* q) i]))" "(*q)[i]"))
|
||||
(test-assert "a sum"
|
||||
(emits? "(fn f ((p (* int))) int (return [(+ p 1) 0]))" "(p + 1)[0]"))
|
||||
(test-assert "a cast"
|
||||
(emits? "(fn f ((v (* void))) int (return [(cast v (* int)) 0]))" "((int *)v)[0]"))
|
||||
(test-assert "a path is left bare"
|
||||
(emits? (in-line "(var x int [(. p x) 0])") "p.x[0]"))
|
||||
;; ...while the index is in brackets of its own
|
||||
(test-assert "an index is never parenthesised"
|
||||
(emits? "(fn f ((p (* int)) (i int)) int (return (cast [p (+ i 1)] int)))"
|
||||
"(int)p[i + 1]")))
|
||||
|
||||
;; A comment among a call's arguments used to become an argument,
|
||||
;; and c-apply put a comma on each side of it -- which does not
|
||||
@@ -172,6 +248,16 @@ compiles."
|
||||
(emits? "(pub enum color (red green blue))" "enum color"))
|
||||
(test-assert "with its values"
|
||||
(emits? "(pub enum color (red green blue))" "red"))
|
||||
;; A value made the enumerator a pair, which went out unconverted
|
||||
(test-assert "explicit values"
|
||||
(emits? "(pub enum wire ((wire-varint 0) (wire-fixed64 1)))"
|
||||
"wire_varint = 0, wire_fixed64 = 1"))
|
||||
(test-assert "a value is an expression"
|
||||
(emits? "(enum wire ((wire-last (+ WIRE-BASE 1))))"
|
||||
"wire_last = WIRE_BASE + 1"))
|
||||
(test-assert "and an anonymous enum takes them too"
|
||||
(emits? "(fn f () void (var e (enum ((up-one 1) down)) up-one))"
|
||||
"up_one = 1, down"))
|
||||
(test-assert "and a non-pub enum still is too"
|
||||
(emits? "(enum color (red green blue))" "enum color"))
|
||||
;; Naming an enum as a type, rather than defining it, had no
|
||||
@@ -246,6 +332,22 @@ compiles."
|
||||
|
||||
;; A nested pointer chain used to silently lose a level:
|
||||
;; (var p (* (* char))) emitted `char *p'
|
||||
;; A grouped header, C's parens carried over, died in the writer with
|
||||
;; `(caddr) bad argument type' and no location
|
||||
(test-group "malformed for"
|
||||
(test-assert "a grouped header is named"
|
||||
(reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i))")
|
||||
"header is not grouped"))
|
||||
(test-assert "even when the body fills the slots it left"
|
||||
(reports? (in-fn "(for ((var i int 0) (< i 4) (++ i)) (g i) (g i) (g i))")
|
||||
"header is not grouped"))
|
||||
(test-assert "a short one gets the shape"
|
||||
(reports? (in-fn "(for (var i int 0) (< i 4))")
|
||||
"(for init test step body ...)"))
|
||||
(test-assert "and both name the line"
|
||||
(reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))"
|
||||
"codegen.sex:2:")))
|
||||
|
||||
(test-group "malformed types are rejected"
|
||||
(test-assert "nested pointer chain"
|
||||
(reports? (in-fn "(var p (* (* char)))") "pointer chains are written flat"))
|
||||
@@ -328,7 +430,7 @@ compiles."
|
||||
(emits? "(fn f ((c (closure ((long)) int))) int (return (c 1)))"
|
||||
"ƛc.code(&ƛc.env, ƛa0)"))
|
||||
(test-assert "a subscript receiver is evaluated once"
|
||||
(emits? "(fn f ((t (¤ (closure ((int)) int) 4)) (i int)) int (return ((¤ t (++ i)) 1)))"
|
||||
(emits? "(fn f ((t [(closure ((int)) int) 4]) (i int)) int (return ([t (++ i)] 1)))"
|
||||
"ƛint_int_call(t[++i], 1)"))
|
||||
(test-assert "so is a member receiver"
|
||||
(emits? "(struct h ((cb (closure ((int)) int))))
|
||||
@@ -449,7 +551,7 @@ compiles."
|
||||
(test-group "macro list accessors"
|
||||
(test-assert "third reads an array's length"
|
||||
(emits? "(defmacro (len t) (third t))
|
||||
(fn f () int (return (len (¤ int 7))))"
|
||||
(fn f () int (return (len [int 7])))"
|
||||
"return 7;"))
|
||||
(test-assert "second reads a tag"
|
||||
(emits? "(defmacro (tag t) (symbol->string (second t)))
|
||||
@@ -523,7 +625,7 @@ compiles."
|
||||
(fn f ((s (struct p))) void (var x (* _) (& s)))"
|
||||
"struct p* x = &s"))
|
||||
(test-assert "a wildcard inside an array"
|
||||
(emits? (in-fn "(var t (¤ _ 3) #((¤ int 3) : 1 2 3))") "int t[3]"))
|
||||
(emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]"))
|
||||
;; a compound literal carries its own type, where a brace
|
||||
;; initializer has none and takes one from its context
|
||||
(test-assert "a compound literal answers a bare wildcard"
|
||||
@@ -534,11 +636,11 @@ compiles."
|
||||
(reports? (in-fn "(var x _ #(1 2))") "cannot infer the type"))
|
||||
;; ...but its elements still solve the hole in an array type
|
||||
(test-assert "elements solve an array's element type"
|
||||
(emits? (in-fn "(var t (¤ _ 4) #(0 1 4 9))") "int t[4] = {0, 1, 4, 9}"))
|
||||
(emits? (in-fn "(var t [_ 4] #(0 1 4 9))") "int t[4] = {0, 1, 4, 9}"))
|
||||
(test-assert "including when there are fewer than the length"
|
||||
(emits? (in-fn "(var t (¤ _ 10) #(1 2))") "int t[10] = {1, 2}"))
|
||||
(emits? (in-fn "(var t [_ 10] #(1 2))") "int t[10] = {1, 2}"))
|
||||
(test-assert "and they have to agree with each other"
|
||||
(reports? (in-fn "(var t (¤ _ 2) #(1 \"s\"))") "type mismatch"))
|
||||
(reports? (in-fn "(var t [_ 2] #(1 \"s\"))") "type mismatch"))
|
||||
;; a closure type reaches the solver as the struct that stands for
|
||||
;; it, which is the spelling `parse-type' knows
|
||||
(test-assert "a closure, from the signature that produced it"
|
||||
@@ -642,26 +744,106 @@ compiles."
|
||||
(emits? (in-fn "(var n int (+ (- a) b))") "-a + b")))
|
||||
|
||||
;; An array bound was taken only when it was an integer literal, so a
|
||||
;; symbolic one fell into the type: `(¤ int N)' came out `int N a[]'.
|
||||
;; symbolic one fell into the type: `[int N]' came out `int N a[]'.
|
||||
(test-group "array bounds"
|
||||
(test-assert "a symbolic bound"
|
||||
(emits? "(define N 4) (struct s ((a (¤ int N))))" "int a[N]"))
|
||||
(emits? "(define N 4) (struct s ((a [int N])))" "int a[N]"))
|
||||
(test-assert "an expression bound"
|
||||
(emits? "(define N 4) (struct s ((a (¤ char (* 2 N)))))" "char a[2 * N]"))
|
||||
(emits? "(define N 4) (struct s ((a [char (* 2 N)])))" "char a[2 * N]"))
|
||||
(test-assert "an integer bound still works"
|
||||
(emits? "(struct s ((a (¤ int 4))))" "int a[4]"))
|
||||
(emits? "(struct s ((a [int 4])))" "int a[4]"))
|
||||
;; ...and it is spelled the way the same name is in an expression
|
||||
(test-assert "a bound's name is converted"
|
||||
(emits? (in-fn "(var xs [u16 CHUNK-AREA])") "u16 xs[CHUNK_AREA]"))
|
||||
(test-assert "so is one inside an expression bound"
|
||||
(emits? (in-fn "(var xs [u16 (* 2 CHUNK-AREA)])") "u16 xs[2 * CHUNK_AREA]"))
|
||||
;; a multi-word type is keywords all the way down, so a trailing
|
||||
;; keyword belongs to the type and leaves the array unsized
|
||||
(test-assert "a multi-word type is not a bound"
|
||||
(emits? "(struct s ((a (¤ unsigned int))))" "unsigned int a[]"))
|
||||
(emits? "(struct s ((a [unsigned int])))" "unsigned int a[]"))
|
||||
;; ...and a tag always follows its keyword
|
||||
(test-assert "nor is an aggregate tag"
|
||||
(emits? "(struct t ((z int))) (struct s ((a (¤ struct t))))" "struct t a[]"))
|
||||
(emits? "(struct t ((z int))) (struct s ((a [struct t])))" "struct t a[]"))
|
||||
(test-assert "nor one behind a pointer"
|
||||
(emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]")))
|
||||
(emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]")))
|
||||
|
||||
;; `sizeof' takes a type or an expression, and `(* x)' is either.
|
||||
;; What is in scope says which: a name C alone knows is a type
|
||||
(test-group "sizeof"
|
||||
(test-assert "a pointer type"
|
||||
(emits? (in-fn "(var n size-t (sizeof (* char)))") "sizeof(char *)"))
|
||||
(test-assert "a qualified one"
|
||||
(emits? (in-fn "(var n size-t (sizeof (* const char)))") "sizeof(const char *)"))
|
||||
(test-assert "to a type only C knows of"
|
||||
(emits? (in-fn "(var n size-t (sizeof (* size-t)))") "sizeof(size_t *)"))
|
||||
(test-assert "a multi-word type"
|
||||
(emits? (in-fn "(var n size-t (sizeof (unsigned int)))") "sizeof(unsigned int)"))
|
||||
(test-assert "an array type"
|
||||
(emits? (in-fn "(var n size-t (sizeof [int 4]))") "sizeof(int [4])"))
|
||||
(test-assert "a dereference of a local"
|
||||
(emits? (in-fn "(var p (* int) 0) (var n size-t (sizeof (* p)))") "sizeof(*p)"))
|
||||
(test-assert "of a parameter"
|
||||
(emits? "(fn f ((p (* int))) void (var n size-t (sizeof (* p))))" "sizeof(*p)"))
|
||||
(test-assert "of a call"
|
||||
(emits? (in-fn "(var n size-t (sizeof (* (g))))") "sizeof(*g())"))
|
||||
(test-assert "a subscript"
|
||||
(emits? (in-fn "(var xs [int 4]) (var n size-t (sizeof [xs 0]))") "sizeof(xs[0])")))
|
||||
|
||||
;; A double is written in as few digits as read back as the same
|
||||
;; double: CHICKEN prints 15 by default, and 0.16666666666666666 came
|
||||
;; out 0.166666666666667, another number
|
||||
(test-group "double literals"
|
||||
(test-assert "keep every digit they need"
|
||||
(emits? (in-fn "(var d double 0.16666666666666666)") "d = 0.16666666666666666;"))
|
||||
(test-assert "and gain none they do not"
|
||||
(emits? (in-fn "(var d double 0.1)") "d = 0.1;"))
|
||||
(test-assert "sixteen when that is enough"
|
||||
(emits? (in-fn "(var d double 0.9871465422297019)") "d = 0.9871465422297019;")))
|
||||
|
||||
;; A define's body was pasted unwalked, and unparenthesised: `cast'
|
||||
;; stayed a call, and (* x D) regrouped with D's own operator
|
||||
(test-group "defines"
|
||||
(test-assert "an atom is left bare"
|
||||
(emits? "(define N 4)" "#define N 4"))
|
||||
(test-assert "and its name converted"
|
||||
(emits? "(define MAX-N MIN-N)" "#define MAX_N MIN_N"))
|
||||
(test-assert "an expression is walked and parenthesised"
|
||||
(emits? "(define K (/ (cast 255 float) (cast 60 float)))"
|
||||
"#define K ((float)255 / (float)60)"))
|
||||
(test-assert "and a negated name"
|
||||
(emits? "(define LOWEST -INFINITY)" "#define LOWEST (-INFINITY)"))
|
||||
(test-assert "so is a negative literal"
|
||||
(emits? "(define NEG -1)" "#define NEG (-1)"))
|
||||
(test-assert "a function-like one is converted too"
|
||||
(emits? "(define (sq-of x) (* x x))" "#define sq_of(x) ((x) * (x))")))
|
||||
|
||||
;; A typedef's target is a type, and was walked as an expression: a
|
||||
;; pointer read as a dereference, an array as a subscript
|
||||
(test-group "typedefs"
|
||||
(test-assert "of a name"
|
||||
(emits? "(typedef small int)" "typedef int small;"))
|
||||
(test-assert "of a pointer"
|
||||
(emits? "(typedef cstr (* const char))" "typedef const char * cstr;"))
|
||||
(test-assert "of an array"
|
||||
(emits? "(typedef vec4 [float 4])" "typedef float vec4[4];"))
|
||||
(test-assert "of a function pointer"
|
||||
(emits? "(typedef colour-fn (fn ((i32)) u32))"
|
||||
"typedef u32 (*colour_fn)(i32);")))
|
||||
|
||||
;; `.' is C's `.' or its `->' depending on what is being read from,
|
||||
;; so a path reads the same however the thing it starts from is held
|
||||
;; ...and inside a literal, which the walk used to pass by
|
||||
(test-group "member access in a literal"
|
||||
(test-assert "compound"
|
||||
(emits? (in-line "(var q (struct point) #(struct point : (. pp x) (. pp y)))")
|
||||
"(struct point){pp->x, pp->y}"))
|
||||
(test-assert "brace initializer"
|
||||
(emits? (in-line "(var q (struct point) #((. pp x) (. pp y)))")
|
||||
"{pp->x, pp->y}"))
|
||||
(test-assert "designated"
|
||||
(emits? (in-line "(var q (struct point) #(.y (. pp x)))")
|
||||
"{.y = pp->x}")))
|
||||
|
||||
(test-group "member access"
|
||||
(test-assert "a value reads with a dot"
|
||||
(emits? (in-line "(= (. p x) 1)") "p.x = 1"))
|
||||
@@ -685,12 +867,36 @@ compiles."
|
||||
(emits? (in-line "(= (. (guess) x) 1)") "guess().x = 1"))
|
||||
(test-assert "and said so"
|
||||
(warns? (in-line "(= (. (guess) x) 1)") "cannot type this"))
|
||||
;; Past a typed base it is a field that cannot be typed -- one of a
|
||||
;; struct only C knows -- and the warning named the base regardless
|
||||
(test-assert "naming the path read so far"
|
||||
(warns? (in-fn "(var t (* struct tm) 0) (= (. t a b) 1)")
|
||||
"as a value (. t a)\n"))
|
||||
(test-assert "which one step through it does not need"
|
||||
(not (warns? (in-fn "(var t (* struct tm) 0) (= (. t a) 1)")
|
||||
"cannot type")))
|
||||
;; the arrow is `%->' and nothing else writes one, so a bare `->'
|
||||
;; is an ordinary head -- a threading macro that nobody imported,
|
||||
;; and a call like any other unknown
|
||||
(test-assert "a bare -> is not the arrow"
|
||||
(emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1")))
|
||||
|
||||
;; A global's initializer is an expression like a local's, and walked
|
||||
;; the same way
|
||||
(test-group "global initializers"
|
||||
(test-assert "a path is dispatched on its type"
|
||||
(emits? (string-append "(struct pt ((x int)))"
|
||||
"(var a (struct pt) #((struct pt) : 1))"
|
||||
"(var q (* int) (& (. a x)))")
|
||||
"int * q = &a.x"))
|
||||
(test-assert "a lambda is lifted, and named after the global"
|
||||
(emits? "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))"
|
||||
"int (*f)(int) = λ0_f"))
|
||||
(test-assert "ahead of it"
|
||||
(let ((c (sex->c "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))")))
|
||||
(< (string-contains c "static int λ0_f (int x)")
|
||||
(string-contains c "(*f)(int) = λ0_f")))))
|
||||
|
||||
;; Toplevel forms used to be separated by a blank line unconditionally,
|
||||
;; which spread a block of adjacent typedefs over twice the lines its
|
||||
;; author wrote
|
||||
|
||||
@@ -8,16 +8,40 @@
|
||||
;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm,
|
||||
;;; which run.scm includes first.
|
||||
|
||||
(import sex-modules)
|
||||
|
||||
(define (interface-of source)
|
||||
"The declarations SOURCE, compiled as a module, hands its importers
|
||||
ahead of its pub forms."
|
||||
(check-public-interface
|
||||
(with-input-from-string source
|
||||
(lambda ()
|
||||
(parameterize ((current-source-file "codegen.sex"))
|
||||
(parse-all (current-input-port)))))))
|
||||
|
||||
(define (interface-reports? source fragment)
|
||||
(let ((m (handle-exceptions e ((condition-property-accessor 'exn 'message) e)
|
||||
(begin (interface-of source) #f))))
|
||||
(and m (string-contains m fragment) #t)))
|
||||
|
||||
(define (ops-src . body)
|
||||
(string-append
|
||||
"(record vec2 ((x float) (y float)))"
|
||||
"(ops vec2"
|
||||
" (pub fn length ((self (* const vec2))) float (return 1.0))"
|
||||
" (fn sum-of ((self vec2)) float (return (. self x))))"
|
||||
" (fn sum-of ((self vec2)) float (return (. self x)))"
|
||||
" (fn scale ((self (* vec2))) void (= (. self x) 2.0)))"
|
||||
"(fn mk () vec2 (return #(vec2 : 1.0 2.0)))"
|
||||
"(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) "
|
||||
(apply string-append body) ")"))
|
||||
|
||||
(define forward-src
|
||||
(string-append
|
||||
"(record pb ((n int)))"
|
||||
"(ops pb"
|
||||
" (fn twice ((self (* pb))) int (return (* 2 (.len self))))"
|
||||
" (pub fn len ((self (* pb))) int (return (. self n))))"))
|
||||
|
||||
(define (sum-src . body)
|
||||
(string-append
|
||||
"(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))"
|
||||
@@ -78,7 +102,15 @@
|
||||
" (fn g ((s v)) int (return 2)))")
|
||||
"method is already defined on"))
|
||||
(test-assert "pub goes on the methods, not the block"
|
||||
(reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods")))
|
||||
(reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))
|
||||
;; Every method is known before any body is walked, and C is told of
|
||||
;; one before a body above it calls it -- and only then
|
||||
(test-assert "a method can call one written below it"
|
||||
(emits? forward-src "return 2 * pbːlen(self)"))
|
||||
(test-assert "which is declared ahead of the call"
|
||||
(emits? forward-src "int pbːlen (pb * self);"))
|
||||
(test-assert "and nothing else is"
|
||||
(not (emits? (ops-src "") "vec2ːsum_of (vec2 self);"))))
|
||||
|
||||
;; The method sits in the head, so the shape of a form can be read
|
||||
;; without knowing the receiver's type.
|
||||
@@ -111,6 +143,60 @@
|
||||
(reports? (ops-src "(.nope v)") "no such method on"))
|
||||
(test-assert "and so is a receiver with no type to dispatch on"
|
||||
(reports? "(fn f () void (var n int 1) (.get n))" "no such method on"))
|
||||
(test-assert "a self spread over the parameter is a pointer self too"
|
||||
(emits? (string-append
|
||||
"(record w ((x int)))"
|
||||
"(ops w (fn get ((self * const w)) int (return (. self x))))"
|
||||
"(fn f () int (var a w #(w : 1)) (var p (* const w) (& a))"
|
||||
" (return (+ (.get a) (.get p))))")
|
||||
"wːget(&a) + wːget(p)"))
|
||||
(test-assert "a const receiver is not handed to a method that may change it"
|
||||
(reports? (ops-src "(var c (* const vec2) p) (.scale c)")
|
||||
"this one is const"))
|
||||
(test-assert "one that cannot change it takes it"
|
||||
(emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))")
|
||||
"vec2ːlength(c)"))
|
||||
(test-assert "a macro receiver is typed by what it expands to"
|
||||
(emits? (string-append "(defmacro (the a) a)"
|
||||
(ops-src "(var n float (.length (the v)))"))
|
||||
"vec2ːlength(&v)"))
|
||||
(test-assert "and so is the start of a path"
|
||||
(emits? (string-append "(defmacro (the a) a)"
|
||||
(ops-src "(var q float (. (the p) x))"))
|
||||
"p->x"))
|
||||
(test-assert "a typedef of the type has its methods"
|
||||
(emits? (string-append
|
||||
"(record w ((x int)))"
|
||||
"(typedef alias w)"
|
||||
"(ops w (fn get ((self (* const w))) int (return (. self x))))"
|
||||
"(fn f () int (var a alias #(alias : 1)) (return (.get a)))")
|
||||
"wːget(&a)"))
|
||||
(test-assert "and a method written on the typedef is the type's"
|
||||
(emits? (string-append
|
||||
"(record w ((x int)))"
|
||||
"(typedef alias w)"
|
||||
"(ops alias (fn get ((self (* const alias))) int (return 1)))"
|
||||
"(fn f () int (var a w #(w : 1)) (return (.get a)))")
|
||||
"aliasːget(&a)"))
|
||||
(test-assert "a typedef of a scalar keeps its own"
|
||||
(reports? (string-append
|
||||
"(typedef meters float)"
|
||||
"(ops meters (fn half ((self meters)) meters (return self)))"
|
||||
"(fn f () void (var x float 1.0) (.half x))")
|
||||
"no such method on"))
|
||||
(test-assert "which a typedef of it shares"
|
||||
(emits? (string-append
|
||||
"(typedef meters float)"
|
||||
"(typedef km meters)"
|
||||
"(ops meters (fn half ((self meters)) meters (return self)))"
|
||||
"(fn f () void (var x km 1.0) (var y km (.half x)))")
|
||||
"metersːhalf(x)"))
|
||||
(test-assert "a method call inside a literal is still a call"
|
||||
(emits? (ops-src "(var w vec2 #(vec2 : (.length v) 1.0))")
|
||||
"(vec2){vec2ːlength(&v), 1.0}"))
|
||||
(test-assert "however deep"
|
||||
(emits? (ops-src "(var ws [vec2 1] #(#(vec2 : (.length p) 1.0)))")
|
||||
"{(vec2){vec2ːlength(p), 1.0}}"))
|
||||
(test-assert "an address cannot be taken of a call"
|
||||
(reports? (ops-src "(.length (mk))") "receiver is not an lvalue"))
|
||||
;; the inner call has to be typed to find the outer one's receiver
|
||||
@@ -126,7 +212,11 @@
|
||||
;; fields, the record holding both, and a constructor each.
|
||||
(test-group "sum"
|
||||
(test-assert "the tag enum is named after the sum"
|
||||
(emits? (sum-src "") "enum shapeːtag"))
|
||||
(emits? (sum-src "") "enum shapeǂ {"))
|
||||
(test-assert "and its constants after the sum and the variant"
|
||||
(emits? (sum-src "") "shapeǂcircle"))
|
||||
(test-assert "a variant may be called tag"
|
||||
(emits? "(sum t ((tag ((x int))) (none ())))" "struct tːtag {"))
|
||||
(test-assert "a variant with fields gets a payload struct"
|
||||
(emits? (sum-src "") "struct shapeːcircle {"))
|
||||
(test-assert "the sum is typedef'd"
|
||||
@@ -137,8 +227,61 @@
|
||||
(test-assert "the typedef comes before the payloads, for a recursive sum"
|
||||
(emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))"
|
||||
"typedef struct expr expr;"))
|
||||
(test-assert "constructors are static even when the sum is pub"
|
||||
(emits? "(pub sum t ((a ((x int)))))" "static t tːa"))
|
||||
(test-assert "a constructor is written in place"
|
||||
(emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
|
||||
"(struct tːa){1}"))
|
||||
(test-assert "and is no function"
|
||||
(not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
|
||||
"t tːa (")))
|
||||
(test-assert "so it is a constant at file scope"
|
||||
(emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" "static t g = (t){"))
|
||||
(test-assert "and an lvalue a method can take the address of"
|
||||
(emits? (string-append
|
||||
"(sum t ((a ((x int)))))"
|
||||
"(ops t (fn get ((self (* const t))) int (return 1)))"
|
||||
"(fn f () int (return (.get (t/a 1))))")
|
||||
"tːget(&(t){"))
|
||||
(test-assert "a constructor takes as many arguments as its variant has fields"
|
||||
(reports? "(sum t ((a ((x int)))))(fn f () t (return (t/a 1 2)))"
|
||||
"variant takes this many fields"))
|
||||
(test-assert "and is not a function value"
|
||||
(reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))"
|
||||
"a constructor is not a function"))
|
||||
(test-assert "an array field takes a brace literal as it is"
|
||||
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2))))"
|
||||
"(struct tːa){{1, 2}}"))
|
||||
(test-assert "and an array by its elements"
|
||||
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 2] #(1 2)) (return (t/a v)))"
|
||||
"(struct tːa){{v[0], v[1]}}"))
|
||||
(test-assert "which have to be countable"
|
||||
(reports? "(fn n () int (return 2))(sum t ((a ((xs [int (n)])))))"
|
||||
"array field needs a length"))
|
||||
(test-assert "and as many as the field holds"
|
||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))"
|
||||
"array is not as long as its field"))
|
||||
(test-assert "an array field takes an array"
|
||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))"
|
||||
"an array field takes an array"))
|
||||
(test-assert "read from a path, not from a call"
|
||||
(reports? (string-append "(sum t ((a ((xs [int 2])))))(fn g () int (return 0))"
|
||||
"(fn f () t (var m [t 2]) (return (t/a (. [m (g)] u a xs))))")
|
||||
"bind it to a var first"))
|
||||
(test-assert "an array binder is a copy of each element"
|
||||
(emits? (string-append "(sum t ((a ((xs [int 2])))))"
|
||||
"(fn f ((s t)) int (match s ((a (xs)) (return [xs 0]))))")
|
||||
"int xs[2] = {s.u.a.xs[0], s.u.a.xs[1]}"))
|
||||
(test-assert "a sum cannot hold itself"
|
||||
(reports? "(sum box ((inner ((x box)))))" "a sum holds itself through a pointer"))
|
||||
(test-assert "nor an array of itself"
|
||||
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
|
||||
(test-assert "though it can point at itself"
|
||||
(emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
|
||||
(test-assert "a function argument becomes the closure its field holds"
|
||||
(emits? (string-append
|
||||
"(fn g ((n int)) int (return n))"
|
||||
"(sum t ((a ((k (closure ((int)) int))))))"
|
||||
"(fn f () t (return (t/a g)))")
|
||||
"ƛint_int_fromfn(g)"))
|
||||
(test-assert "a tag-only sum has no union at all"
|
||||
(not (emits? "(sum light ((red ()) (green ())))" "union")))
|
||||
(test-assert "a sum is declared once"
|
||||
@@ -146,7 +289,9 @@
|
||||
(test-assert "and needs variants"
|
||||
(reports? "(sum t)" "sum needs a name and a list of variants"))
|
||||
(test-assert "a variant is a name and a field list"
|
||||
(reports? "(sum t (a))" "a variant is")))
|
||||
(reports? "(sum t (a))" "a variant is"))
|
||||
(test-assert "and is declared once"
|
||||
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
|
||||
|
||||
;; A spec is a contract that emits nothing; a realization is its
|
||||
;; methods for one type. The refusals are what make it a contract.
|
||||
@@ -180,6 +325,9 @@
|
||||
(test-assert "a spec is declared once"
|
||||
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
|
||||
"spec is already declared"))
|
||||
(test-assert "a typedef realizes what its type does"
|
||||
(reports? (string-append (spec-src "") "(typedef alias v)(realize (p alias))")
|
||||
"spec is already realized for"))
|
||||
(test-assert "a type realizes a spec once"
|
||||
(reports? (string-append (spec-src "") "(realize (p v)"
|
||||
" (fn s ((a (* const v))) void (return)))")
|
||||
@@ -198,6 +346,23 @@
|
||||
" (fn q ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"q"))
|
||||
(test-assert "a docstring is not a body"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void \"doc\"))"
|
||||
"(realize (p v))")
|
||||
"realization is missing a method of"))
|
||||
(test-assert "nor is a comment"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) int\n"
|
||||
" ;; must be implemented\n"
|
||||
" ))"
|
||||
"(realize (p v))")
|
||||
"realization is missing a method of"))
|
||||
(test-assert "a documented default is still a default"
|
||||
(emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) int \"doc\" (return 1)))"
|
||||
"(realize (p v))")
|
||||
"/* doc */"))
|
||||
(test-assert "a method the spec has not got is refused"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
@@ -214,6 +379,11 @@
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a v)) void (return)))")
|
||||
"arguments do not match"))
|
||||
(test-assert "but not on how a pointer is spelled"
|
||||
(emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a * const T)) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"void vːpːs (const v * a)"))
|
||||
(test-assert "a method name already taken on the type is refused"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(ops v (fn s ((a (* const v))) void (return)))"
|
||||
@@ -243,6 +413,18 @@
|
||||
(test-assert "a path scrutinee is not copied"
|
||||
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
|
||||
"ƛm0")))
|
||||
(test-assert "a macro scrutinee is typed by what it expands to"
|
||||
(emits? (string-append "(defmacro (the a) a)"
|
||||
(sum-src "(match (the s) ((circle (r)) (= out r))"
|
||||
" (else (= out 0.0)))"))
|
||||
"shape ƛm0 = s"))
|
||||
(test-assert "a typedef of a sum is matched as the sum"
|
||||
(emits? (string-append
|
||||
"(sum shape ((circle ((r int))) (empty ())))"
|
||||
"(typedef alias shape)"
|
||||
"(fn f () int (var s alias (shape/circle 1))"
|
||||
" (match s ((circle (r)) (return r)) ((empty ()) (return 0))))")
|
||||
"case shapeǂcircle"))
|
||||
(test-assert "else becomes default"
|
||||
(emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
|
||||
"default:"))
|
||||
@@ -269,6 +451,88 @@
|
||||
(reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))"
|
||||
" (else (= out 0.0)))")
|
||||
"arm is written twice"))
|
||||
(test-assert "so is a second else"
|
||||
(reports? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0))"
|
||||
" (else (= out 1.0)))")
|
||||
"more than one else"))
|
||||
(test-assert "so is an arm that is not one"
|
||||
(reports? (sum-src "(match s foo)") "an arm is"))
|
||||
(test-assert "match has no value"
|
||||
(reports? (sum-src "(var n float (match s ((circle (r)) r) (else 0.0)))")
|
||||
"match is a statement"))
|
||||
(test-assert "not even as an argument"
|
||||
(reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))")
|
||||
"match is a statement"))
|
||||
(test-assert "but a case body is a statement"
|
||||
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
|
||||
" (else (= out 0.0)))))")
|
||||
"switch (s.tag)"))
|
||||
(test-assert "and so is a closure's, wherever the closure stands"
|
||||
(emits? (sum-src "(var c (closure () int) (closure () int ((t s))"
|
||||
" (match t ((circle (r)) (return 1)) (else (return 0)))))")
|
||||
"switch (t.tag)"))
|
||||
(test-assert "and a scrutinee that is not a sum"
|
||||
(reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))"
|
||||
"match wants a sum"))))
|
||||
"match wants a sum")))
|
||||
|
||||
;; An importer is given the pub forms and nothing else, so a type one
|
||||
;; of them names has to be among them, or C is told no more of it
|
||||
;; than a declaration can say
|
||||
(test-group "what importers can see"
|
||||
(test "a private record behind a pointer is declared for them"
|
||||
'((record cell))
|
||||
(interface-of "(record cell ((v int))) (pub record shape ((c (* cell))))"))
|
||||
(test "once"
|
||||
'((record cell))
|
||||
(interface-of "(record cell ((v int))) (pub fn f ((a (* cell)) (b (* cell))) void)"))
|
||||
(test "a struct as a struct"
|
||||
'((struct cell))
|
||||
(interface-of "(struct cell ((v int))) (pub fn f ((a (* struct cell))) void)"))
|
||||
(test "a pub one needs nothing"
|
||||
'()
|
||||
(interface-of "(pub record cell ((v int))) (pub record shape ((c cell)))"))
|
||||
(test "nor one only C knows"
|
||||
'()
|
||||
(interface-of "(pub fn f ((p (* FILE)) (n size-t)) void)"))
|
||||
(test "nor a private fn's"
|
||||
'()
|
||||
(interface-of "(record cell ((v int))) (fn f ((c cell)) void)"))
|
||||
(test-assert "held by value it is an error"
|
||||
(interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))"
|
||||
"held by value"))
|
||||
(test-assert "naming the line"
|
||||
(interface-reports? "(record cell ((v int)))\n(pub record shape ((c cell)))"
|
||||
"codegen.sex:2:"))
|
||||
(test-assert "in an array too"
|
||||
(interface-reports? "(record cell ((v int))) (pub record shape ((cs [cell 4])))"
|
||||
"held by value"))
|
||||
(test-assert "returned"
|
||||
(interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value"))
|
||||
(test-assert "or taken by a pub method"
|
||||
(interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))"
|
||||
"held by value"))
|
||||
(test-assert "a typedef has no declaration to give, pointer or not"
|
||||
(interface-reports? "(typedef small int) (pub fn f ((p (* small))) void)"
|
||||
"this typedef, and C declares one only by defining it"))
|
||||
(test-assert "nor has an enum"
|
||||
(interface-reports? "(enum mood (up down)) (pub var m (* enum mood))"
|
||||
"this enum, and C declares"))
|
||||
(test-assert "a pub handle is held through a pointer"
|
||||
(interface-reports? "(pub record h) (record h ((n int))) (pub fn f ((x h)) void)"
|
||||
"only a handle"))
|
||||
(test "which is all it takes"
|
||||
'()
|
||||
(interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)"))
|
||||
;; A constant has no declaration either, and an array bound or a
|
||||
;; pub define's body hands its name to importers all the same
|
||||
(test-assert "a constant sizing a pub record's array"
|
||||
(interface-reports? "(define N 4) (pub record r ((xs [int N])))"
|
||||
"this define, and C declares one only by defining it"))
|
||||
(test-assert "or used by a pub define"
|
||||
(interface-reports? "(define N 4) (pub define M (* 2 N))" "this define"))
|
||||
(test "is fine when pub"
|
||||
'()
|
||||
(interface-of "(pub define N 4) (pub record r ((xs [int N])))"))
|
||||
(test "as is a literal bound"
|
||||
'()
|
||||
(interface-of "(pub record r ((xs [int 4])))"))))
|
||||
|
||||
@@ -86,7 +86,10 @@
|
||||
" (: done)" ; 52
|
||||
" (var svar u64 (sizeof (struct pt)))" ; 53
|
||||
" (var cvar int (cast mvar int))" ; 54
|
||||
" (return 122))" ; 55
|
||||
" (putchar (if (< mvar 123)" ; 55 a conditional as an
|
||||
" (putchar 124)" ; 56 argument: an expression,
|
||||
" 125))" ; 57 so no anchor inside it
|
||||
" (return 122))" ; 58
|
||||
))
|
||||
|
||||
(define fixture (string-intersperse fixture-lines "\n"))
|
||||
@@ -231,7 +234,14 @@ after that is one more. Lines before the first directive get #f."
|
||||
;; Expressions that are their own statement
|
||||
(test-group "expressions"
|
||||
(maps/tokens "sizeof" "(var svar" "sizeof")
|
||||
(maps/tokens "cast" "(var cvar" "(int)mvar"))
|
||||
(maps/tokens "cast" "(var cvar" "(int)mvar")
|
||||
;; an `if' arm is a statement only where the `if' is one: a
|
||||
;; directive between `?' and `:' does not compile
|
||||
(maps "conditional argument" "123")
|
||||
(test-assert "holds no directive"
|
||||
(let ((start (string-contains c-out "123")))
|
||||
(not (string-contains (substring c-out start (string-contains c-out "125" start))
|
||||
"#line")))))
|
||||
|
||||
;; A location is (file . line); every directive must name the file the
|
||||
;; form was read from.
|
||||
|
||||
22
tests/module-path.scm
Normal file
22
tests/module-path.scm
Normal file
@@ -0,0 +1,22 @@
|
||||
;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the
|
||||
;;; start, from the directory sexc was started in.
|
||||
|
||||
(import (chicken pathname)
|
||||
(chicken process-context)
|
||||
sex-modules)
|
||||
|
||||
(test-group "module path"
|
||||
;; make-absolute-pathname took `src' for a directory under the root,
|
||||
;; and an import searched /src/
|
||||
(set-environment-variable! "SEX_MODULE_PATH" "src:/abs/lib")
|
||||
(load-persistent-module-paths)
|
||||
(test "a relative entry is from the working directory"
|
||||
(make-absolute-pathname (current-directory) "src")
|
||||
(second (get-module-paths)))
|
||||
(test "an absolute one is as written"
|
||||
"/abs/lib"
|
||||
(third (get-module-paths)))
|
||||
|
||||
(set-environment-variable! "SEX_MODULE_PATH" "")
|
||||
(load-persistent-module-paths)
|
||||
(unset-environment-variable! "SEX_MODULE_PATH"))
|
||||
@@ -17,15 +17,31 @@
|
||||
# alone, its fields left behind and its methods still found.
|
||||
#
|
||||
# The public forms carry comments in their headers, which the reduction
|
||||
# to a prototype and to an extern both have to look past.
|
||||
# to a prototype and to an extern both have to look past. And a type the
|
||||
# app cannot see -- private to greet, or from a module greet imports
|
||||
# without `pub' -- crosses behind a pointer, declared and no more.
|
||||
#
|
||||
# The interface prints as importers get it: the declarations first, then
|
||||
# the pub forms in the order they were written.
|
||||
#
|
||||
# The app's dependency rule names both modules: greet, which it imports,
|
||||
# and ledger, which only greet does but which decides what the app is
|
||||
# told of it.
|
||||
|
||||
SEXC ?= ../../sexc
|
||||
|
||||
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\ncolour 123
|
||||
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123
|
||||
|
||||
check:
|
||||
@if [ "`$(SEXC) --public-interface greet.sex | head -3`" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \
|
||||
echo "modules FAILED, the interface begins:"; $(SEXC) --public-interface greet.sex | head -3; exit 1; \
|
||||
fi
|
||||
@$(SEXC) ledger.sex -c -o ledger.o
|
||||
@$(SEXC) greet.sex -c -o greet.o
|
||||
@$(SEXC) greet-app.sex -o greet-app -- greet.o
|
||||
@$(SEXC) greet-app.sex -o greet-app --depfile=greet-app.d -- greet.o ledger.o
|
||||
@if ! head -1 greet-app.d | grep -q '^greet-app: greet-app.sex .*/greet.sex .*/ledger.sex$$'; then \
|
||||
echo "modules FAILED, the dependency rule is:"; cat greet-app.d; $(MAKE) clean; exit 1; \
|
||||
fi
|
||||
@if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \
|
||||
echo "modules ok"; \
|
||||
else \
|
||||
@@ -34,6 +50,6 @@ check:
|
||||
@$(MAKE) --no-print-directory clean
|
||||
|
||||
clean:
|
||||
@rm -f greet.o greet-app
|
||||
@rm -f greet.o ledger.o greet-app greet-app.d
|
||||
|
||||
.PHONY: check clean
|
||||
|
||||
@@ -47,6 +47,11 @@
|
||||
(printf "tally %d\n" (.count t))
|
||||
(.drop t)
|
||||
|
||||
;; neither cell nor ledger is visible here, only declared
|
||||
(var b board (make-board))
|
||||
(printf "board %d\n" (board-total (& b)))
|
||||
(printf "ledger %d\n" (ledger-total (greet-ledger)))
|
||||
|
||||
(var c colour (colour/rgb 1 2 3))
|
||||
(match c
|
||||
((rgb (r g b)) (printf "colour %d%d%d\n" r g b))
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
(pub include stdio.h)
|
||||
(include stdlib.h)
|
||||
|
||||
(import ledger)
|
||||
|
||||
(pub var greet-count ;; a comment in the header of a public form is
|
||||
;; not part of it: what the importer is given has
|
||||
;; to be `extern int greet-count', not a form
|
||||
@@ -30,12 +32,36 @@
|
||||
(lambda (name field-type)
|
||||
`(printf "%s " ,(symbol->string name))))))
|
||||
|
||||
(var greetings ledger #(ledger : 0))
|
||||
|
||||
(pub fn greet ;; ...and here the prototype would lose its return type
|
||||
((name (* const char))) void
|
||||
"Print a greeting for NAME."
|
||||
(++ greet-count)
|
||||
(ledger-add (& greetings) 1)
|
||||
(printf "hello, %s\n" name))
|
||||
|
||||
;;; Types the importer cannot see, crossing behind a pointer. `cell' is
|
||||
;;; private and `ledger' was imported without `pub', and the importer
|
||||
;;; is handed a declaration of each and nothing else.
|
||||
(record cell ((v int)))
|
||||
|
||||
(var the-cell cell #(cell : 40))
|
||||
|
||||
(pub record board ((first (* cell)) (size int)))
|
||||
|
||||
(pub fn make-board () board
|
||||
(return #(board : (& the-cell) 2)))
|
||||
|
||||
(pub fn board-total ((b (* const board))) int
|
||||
(return (+ (. b first v) (. b size))))
|
||||
|
||||
(pub fn greet-ledger () (* ledger)
|
||||
(return (& greetings)))
|
||||
|
||||
(pub fn ledger-total ((l (* const ledger))) int
|
||||
(return (. l total)))
|
||||
|
||||
;;; A closure type crossing the boundary. Both units generate the
|
||||
;;; struct for this signature independently, so they have to agree on
|
||||
;;; its tag and its layout, or the value is passed wrong and nothing
|
||||
@@ -80,8 +106,8 @@
|
||||
(free self)))
|
||||
|
||||
;;; A pub sum is pasted whole, so the importer builds its own copy of
|
||||
;;; the declarations -- and of the constructors, which is why those are
|
||||
;;; static: two units defining colourːrgb would not link.
|
||||
;;; the declarations; a constructor is written in place where it is
|
||||
;;; called, so there is no function for two units to both define.
|
||||
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
|
||||
|
||||
;;; A spec and a realization over the boundary. The written method
|
||||
|
||||
8
tests/modules/ledger.sex
Normal file
8
tests/modules/ledger.sex
Normal file
@@ -0,0 +1,8 @@
|
||||
;;; A module greet.sex imports without `pub'. greet-app.sex never
|
||||
;;; imports it, yet holds a (* ledger) that greet hands out: what greet
|
||||
;;; exports has to declare the type for it.
|
||||
|
||||
(pub record ledger ((total int)))
|
||||
|
||||
(pub fn ledger-add ((l (* ledger)) (n int)) void
|
||||
(+= (. l total) n))
|
||||
@@ -38,6 +38,22 @@
|
||||
;; a `.'-prefixed symbol is an ordinary symbol, not dot-access
|
||||
(reader-test '((.field obj)) "(.field obj)")
|
||||
|
||||
;; a leading `-' on a name is negation, the way it is on a number:
|
||||
;; no name is spelled with one, and -INFINITY otherwise mangled into
|
||||
;; _INFINITY. The operators that start with one are left alone
|
||||
(reader-test '((- INFINITY)) "-INFINITY")
|
||||
(reader-test '((var best double (- INFINITY))) "(var best double -INFINITY)")
|
||||
(reader-test '((- _x)) "-_x")
|
||||
(reader-test '(-1 -1.5) "-1 -1.5")
|
||||
(reader-test '(- -> ->> -- -=) "- -> ->> -- -=")
|
||||
|
||||
;; a number in another radix, spelled the way C does or the way
|
||||
;; Scheme does; either is an ordinary integer from here on
|
||||
(reader-test '(224 224 5 5 -16) "0xE0 0Xe0 0b101 0B101 -0x10")
|
||||
(reader-test '(128 128 5 8 -16) "#x80 #X80 #b101 #o10 #x-10")
|
||||
;; ...and only a number: a prefix with nothing after it is a name
|
||||
(reader-test '(0x 0xg) "0x 0xg")
|
||||
|
||||
;; `;' comments are preserved as (comment "...") forms
|
||||
(reader-test '((comment " hi")) "; hi")
|
||||
(reader-test '((comment ";; Prototypes")) ";;; Prototypes")
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
(include "codegen.scm")
|
||||
(include "encapsulation.scm")
|
||||
(include "args.scm")
|
||||
(include "module-path.scm")
|
||||
(include "types.scm")
|
||||
(include "infer.scm")
|
||||
|
||||
|
||||
@@ -66,12 +66,12 @@
|
||||
|
||||
(printf "Through a parameter: %d\n" (apply-twice (make-adder 50) 10))
|
||||
|
||||
(var table (¤ (closure ((int)) int) 3))
|
||||
(var table [(closure ((int)) int) 3])
|
||||
(var i int 0)
|
||||
(for (= i 0) (< i 3) (++ i)
|
||||
(= (¤ table i) (make-adder i)))
|
||||
(= [table i] (make-adder i)))
|
||||
(printf "From an array: %d %d %d\n"
|
||||
((¤ table 0) 1) ((¤ table 1) 1) ((¤ table 2) 1))
|
||||
([table 0] 1) ([table 1] 1) ([table 2] 1))
|
||||
|
||||
;; the index must be evaluated once, so `i' ends at 1 and not 2 --
|
||||
;; read in a separate statement, since reading and bumping it in one
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
"through a pointer 9"
|
||||
"array 10 20 30"
|
||||
"argument 6"
|
||||
"mixed 1 5")
|
||||
"mixed 1 5"
|
||||
"read through a pointer 1 5")
|
||||
(return 0)
|
||||
|
||||
;;; `:' inside #(...) ends a type and makes the rest a C99 compound
|
||||
@@ -38,7 +39,7 @@
|
||||
|
||||
;; an array literal decays the way an array does
|
||||
(var a (* int) #([int 3] : 10 20 30))
|
||||
(printf "array %d %d %d\n" (¤ a 0) (¤ a 1) (¤ a 2))
|
||||
(printf "array %d %d %d\n" [a 0] [a 1] [a 2])
|
||||
|
||||
(printf "argument %d\n" (sum #(struct point : 2 4)))
|
||||
|
||||
@@ -46,4 +47,10 @@
|
||||
(var m (struct point) #(struct point : 1 .y 5))
|
||||
(printf "mixed %d %d\n" (. m x) (. m y))
|
||||
|
||||
;; what a literal holds is walked like any expression, so a path in
|
||||
;; it reads through a pointer as it does outside one
|
||||
(var pm (* (struct point)) (& m))
|
||||
(var c (struct point) #(struct point : (. pm x) (. pm y)))
|
||||
(printf "read through a pointer %d %d\n" (. c x) (. c y))
|
||||
|
||||
(return 0))
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
;;;
|
||||
;;; 1. SETTLED. `type-match' took `_' on the pattern side, so
|
||||
;;; `(closure _ int)' above is one clause rather than one per
|
||||
;;; signature, and `(* _)' and `(¤ _ _)' say "any pointer" and "any
|
||||
;;; signature, and `(* _)' and `[_ _]' say "any pointer" and "any
|
||||
;;; array". A `_' written last takes the rest, since a type's words
|
||||
;;; are spread and not nested: `(* const char)' is three elements.
|
||||
;;; Nothing destructures -- a macro body is Scheme and a type is a
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
"unsigned wins either way: 4294967295 4294967295"
|
||||
"toplevel: 1 2.5 hi 12"
|
||||
"closure in place: 5"
|
||||
"a type is not a call: 7")
|
||||
"a type is not a call: 7"
|
||||
"radix literals: 224 5 128"
|
||||
"a double reaches C whole: 1")
|
||||
(return 0)
|
||||
|
||||
;;; The walk types an expression by its head, and the heads it had a
|
||||
@@ -61,10 +63,10 @@
|
||||
(printf "increment: %d\n" inc)
|
||||
|
||||
;; an array operand decays, so this is a pointer and not an array
|
||||
(var xs (¤ int 4) #(1 2 3 4))
|
||||
(var xs [int 4] #(1 2 3 4))
|
||||
(var p _ (+ xs 1))
|
||||
(var q _ (+ 1 xs))
|
||||
(var names (¤ (* const char) 2) #("hi" "there"))
|
||||
(var names [(* const char) 2] #("hi" "there"))
|
||||
(var np _ (+ names 1))
|
||||
(printf "decayed: %d %d %s\n" (* p) (* q) (* np))
|
||||
|
||||
@@ -87,4 +89,12 @@
|
||||
(var f (closure ((int)) int) (make-adder 1))
|
||||
(var fp (fn ((f int) (g int)) int) area)
|
||||
(printf "a type is not a call: %d\n" (f 6))
|
||||
|
||||
;; a mask reads best in the radix it is a mask in
|
||||
(var lead int 0xE5)
|
||||
(printf "radix literals: %d %d %d\n" (& lead 0xE0) (& lead 0b111) #x80)
|
||||
|
||||
;; ...and a double in all the digits it was written with
|
||||
(var sixth double (/ 1.0 6.0))
|
||||
(printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth))
|
||||
(return 0))
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
(input)
|
||||
(output "5.0 5.0 10.0 14.0 14.0 6.0"
|
||||
"struct receiver: 14"
|
||||
"private: 8.0")
|
||||
"private: 8.0"
|
||||
"forward call: 28.0")
|
||||
(return 0)
|
||||
|
||||
;;; An ops block is mangled fns plus a registry entry, so a method is
|
||||
@@ -22,6 +23,10 @@
|
||||
(record vec2 ((x float) (y float)))
|
||||
|
||||
(ops vec2
|
||||
;; a method may call one written below it
|
||||
(fn twice-sum ((self vec2)) float
|
||||
(return (* 2.0 (.sum-of self))))
|
||||
|
||||
(pub fn length ((self (* const vec2))) float
|
||||
"Pointer self, so (.length v) has to take the address."
|
||||
(return (sqrtf (+ (* (. self x) (. self x))
|
||||
@@ -55,4 +60,5 @@
|
||||
|
||||
(var u vec2 #(vec2 : 8.0 0.0))
|
||||
(printf "private: %.1f\n" (vec2/sum-of u))
|
||||
(printf "forward call: %.1f\n" (.twice-sum v))
|
||||
(return 0))
|
||||
|
||||
32
tests/sex-programs/precedence.sex
Normal file
32
tests/sex-programs/precedence.sex
Normal file
@@ -0,0 +1,32 @@
|
||||
(input)
|
||||
(output "conditional operand: 75"
|
||||
"cast as object of .: 7"
|
||||
"cast of bitwise: 1"
|
||||
"cast of conditional: 44"
|
||||
"define body: 6")
|
||||
(return 0)
|
||||
|
||||
;;; A Sex form is parenthesised by construction, and C is not: whatever
|
||||
;;; the writer leaves bare, C regroups by its own precedence. Each line
|
||||
;;; below came out regrouped, and all but the member access still
|
||||
;;; compiled -- computing 4, 257, 300, and 4 from `2 * 1 + 2'.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(record wanted ((distance int)))
|
||||
|
||||
(define SUM (+ 1 2))
|
||||
|
||||
(pub fn main () int
|
||||
(var compared int 4)
|
||||
(printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1)))
|
||||
|
||||
(var w wanted #(wanted : 7))
|
||||
(var pa (* const void) (& w))
|
||||
(printf "cast as object of .: %d\n" (. (cast pa (* const wanted)) distance))
|
||||
|
||||
(var x int 1)
|
||||
(printf "cast of bitwise: %d\n" (cast (| x 256) u8))
|
||||
(printf "cast of conditional: %d\n" (cast (if x 300 1) u8))
|
||||
(printf "define body: %d\n" (* 2 SUM))
|
||||
(return 0))
|
||||
@@ -2,14 +2,15 @@
|
||||
(output "3.14 12.00 0.00"
|
||||
"held once: a 1"
|
||||
"nested: -(2 + 3) = -5"
|
||||
"tagged only: 1")
|
||||
"tagged only: 1"
|
||||
"rows: 18 5")
|
||||
(return 0)
|
||||
|
||||
;;; A sum is a tag enum, a payload struct per variant that carries
|
||||
;;; fields, the record holding both, and a constructor each. match is
|
||||
;;; a switch over the tag whose arms bind the payload as locals, and
|
||||
;;; the compiler refuses one that leaves a variant out -- which is the
|
||||
;;; thing the form exists for.
|
||||
;;; fields, and the record holding both; a constructor is the value
|
||||
;;; itself, written in place. match is a switch over the tag whose arms
|
||||
;;; bind the payload as locals, and the compiler refuses one that leaves
|
||||
;;; a variant out -- which is the thing the form exists for.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
@@ -52,6 +53,12 @@
|
||||
(sum held ((a ((x int) (y int))) (b ())))
|
||||
(fn mk-held () held (return (held/a 1 2)))
|
||||
|
||||
;;; An array field is handed elements, never an array: C copies neither
|
||||
;;; into a parameter nor into another array, so both the constructor
|
||||
;;; and the binder spell it out
|
||||
(define N 4)
|
||||
(sum row ((cells ((xs [int N]))) (none ())))
|
||||
|
||||
(pub fn main () int
|
||||
(printf "%.2f %.2f %.2f\n"
|
||||
(area (mk-shape))
|
||||
@@ -75,4 +82,16 @@
|
||||
(match l
|
||||
((red ()) (printf "tagged only: 0\n"))
|
||||
((green ()) (printf "tagged only: 1\n")))
|
||||
|
||||
(var a [int N] #(5 6 7 8))
|
||||
(var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4))))
|
||||
(= [a 0] 50) ; the row holds a copy
|
||||
(var sum int 0)
|
||||
(for (var i int 0) (< i 2) (++ i)
|
||||
(match [rows i]
|
||||
((cells (xs))
|
||||
(= [xs 0] 100) ; and so does the binder
|
||||
(+= sum (+ [xs 1] [xs 2])))
|
||||
((none ()) (+= sum 0))))
|
||||
(printf "rows: %d %d\n" sum (. [rows 0] u cells [xs 0]))
|
||||
(return 0))
|
||||
|
||||
@@ -5,12 +5,15 @@
|
||||
"through a pointer: 55"
|
||||
"unsized of a typedef: 1 2"
|
||||
"unsized of a pointer: 5"
|
||||
"unnamed parameters: 7 -1 2")
|
||||
"named bound: 2 4 b"
|
||||
"unnamed parameters: 7 -1 2"
|
||||
"typedefs: hi 4 2"
|
||||
"sizeof a pointer type: 1 1")
|
||||
(return 0)
|
||||
|
||||
;;; Three questions about a written type that used to be answered in
|
||||
;;; three places and disagreed: is `(a b)' a named parameter or a bare
|
||||
;;; type, is the last element of a `¤' its bound or the last word of
|
||||
;;; type, is the last element of a `[...]' its bound or the last word of
|
||||
;;; its element type, and what is one element of an array.
|
||||
;;;
|
||||
;;; They are one question -- where does the type end -- so the answer
|
||||
@@ -21,6 +24,11 @@
|
||||
(struct point ((x int) (y int)))
|
||||
|
||||
(typedef small int)
|
||||
(typedef cstr (* const char))
|
||||
(typedef vec4 [float 4])
|
||||
(typedef unary (fn ((small)) small))
|
||||
|
||||
(define CAP 2)
|
||||
|
||||
;;; a parameter that names nothing is a type, however many words it
|
||||
;;; takes: `(unsigned int)' is one of them, not a `unsigned' called
|
||||
@@ -37,36 +45,54 @@
|
||||
|
||||
(pub fn main () int
|
||||
;; an element keeps every word of its type, tag and all
|
||||
(var pts (¤ (struct point) 2) #(#((struct point) : 1 2)
|
||||
(var pts [(struct point) 2] #(#((struct point) : 1 2)
|
||||
#((struct point) : 3 4)))
|
||||
(var p _ (¤ pts 1))
|
||||
(var p _ [pts 1])
|
||||
(printf "aggregate element: %d %d\n" (. p x) (. p y))
|
||||
|
||||
(var names (¤ (* const char) 2) #("hi" "there"))
|
||||
(var s _ (¤ names 1))
|
||||
(var names [(* const char) 2] #("hi" "there"))
|
||||
(var s _ [names 1])
|
||||
(printf "pointer element: %s\n" s)
|
||||
|
||||
(var nums (¤ unsigned int 3) #(7 8 9))
|
||||
(var u _ (¤ nums 2))
|
||||
(var nums [unsigned int 3] #(7 8 9))
|
||||
(var u _ [nums 2])
|
||||
(printf "multi-word element: %u\n" u)
|
||||
|
||||
;; subscripting a pointer answers the same as subscripting an array
|
||||
(var q (* (struct point)) (& (¤ pts 0)))
|
||||
(var r _ (¤ q 1))
|
||||
(var q (* (struct point)) (& [pts 0]))
|
||||
(var r _ [q 1])
|
||||
(printf "through a pointer: %d\n" (+ (. r x) (* 13 (. r y))))
|
||||
|
||||
;; the last word of an unsized array's type is not its bound: neither
|
||||
;; a typedef name nor the target of a `*' can be one
|
||||
(var tail (¤ const small) #(1 2))
|
||||
(printf "unsized of a typedef: %d %d\n" (¤ tail 0) (¤ tail 1))
|
||||
(var tail [const small] #(1 2))
|
||||
(printf "unsized of a typedef: %d %d\n" [tail 0] [tail 1])
|
||||
|
||||
(var one size-t 5)
|
||||
(var sizes (¤ * size-t) #((& one)))
|
||||
(var w _ (¤ sizes 0))
|
||||
(var sizes [* size-t] #((& one)))
|
||||
(var w _ [sizes 0])
|
||||
(printf "unsized of a pointer: %d\n" (cast (* w) int))
|
||||
|
||||
;; ...but after a whole type, a name is: `size-t' is a typedef only C
|
||||
;; knows of, and `(* const char)' a type grouped into one element
|
||||
(var ws [size-t CAP] #(3 4))
|
||||
(var gs [(* const char) CAP] #("a" "b"))
|
||||
(printf "named bound: %zu %zu %s\n"
|
||||
(/ (sizeof ws) (sizeof [ws 0])) [ws 1] [gs 1])
|
||||
|
||||
;; the same question in type position: `(fn ((unsigned int)) int)'
|
||||
;; takes one parameter, not two
|
||||
(var fp (fn ((unsigned int)) int) width)
|
||||
(printf "unnamed parameters: %d %d %d\n" (fp 7) (sign #\a) (twice 1))
|
||||
|
||||
;; a typedef's target is every one of those shapes as well
|
||||
(var greeting cstr "hi")
|
||||
(var v vec4 #(1.0 2.0 3.0 4.0))
|
||||
(var op unary twice)
|
||||
(printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof [v 0])) (op 1))
|
||||
|
||||
;; `(* T)' is a type or a dereference, and only what is in scope says
|
||||
(printf "sizeof a pointer type: %d %d\n"
|
||||
(== (sizeof (* const char)) (sizeof greeting))
|
||||
(== (sizeof (* greeting)) 1))
|
||||
(return 0))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
(input)
|
||||
(output "café 日本語 🍺" "café1" "naïve: 3")
|
||||
(output "café 日本語 🍺" "café1" "naïve: 3" "predicate: 1 0")
|
||||
(return 0)
|
||||
|
||||
;;; Non-ASCII string literals and identifiers.
|
||||
@@ -13,12 +13,22 @@
|
||||
;;; non-ASCII characters must survive unkebabify intact -- getting this
|
||||
;;; wrong truncates the name silently, and the program still compiles
|
||||
;;; and runs, just under a different name than the one written.
|
||||
;;;
|
||||
;;; `?' and `!' end Lisp predicates and mutators, and C takes neither:
|
||||
;;; they become the letters ʔ and ꜝ.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(fn zero? ((n int)) bool (return (== n 0)))
|
||||
(fn clear! ((n (* int))) void (= (* n) 0))
|
||||
|
||||
(pub fn main () int
|
||||
(puts "café 日本語 🍺")
|
||||
(puts "café1")
|
||||
(var naïve-count int 3)
|
||||
(printf "naïve: %d\n" naïve-count)
|
||||
(var n int 5)
|
||||
(var before bool (zero? n))
|
||||
(clear! (& n))
|
||||
(printf "predicate: %d %d\n" (zero? n) before)
|
||||
(return 0))
|
||||
|
||||
@@ -25,8 +25,8 @@
|
||||
(fn origin-x ((p (* (struct point)))) int
|
||||
(return (. (* p) x)))
|
||||
|
||||
(fn second-of ((xs (¤ float 4))) float
|
||||
(return (¤ xs 1)))
|
||||
(fn second-of ((xs [float 4])) float
|
||||
(return [xs 1]))
|
||||
|
||||
(fn say ((fmt (* const char)) ...) void
|
||||
(var ap va-list)
|
||||
@@ -43,8 +43,8 @@
|
||||
(var f (fn ((* (struct point))) int) origin-x)
|
||||
(printf "aggregate: %d\n" (f (& p)))
|
||||
|
||||
(var xs (¤ float 4) #(1.5 2.5 3.5 4.5))
|
||||
(var g (fn ((¤ float 4)) float) second-of)
|
||||
(var xs [float 4] #(1.5 2.5 3.5 4.5))
|
||||
(var g (fn ([float 4]) float) second-of)
|
||||
(printf "array: %g\n" (g xs))
|
||||
|
||||
(say "variadic: %d %s\n" 1 "two")
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"loop: 0 1 2"
|
||||
"shadowed: 9 then 42"
|
||||
"still an int: 200"
|
||||
"case scope: 200"
|
||||
"partial: 1 2.5"
|
||||
"joined: 43.5 84 49 1"
|
||||
"promoted: 200 60000 3705032704"
|
||||
@@ -44,11 +45,11 @@
|
||||
(var pp _ (& p))
|
||||
(printf "pointers: %d %g\n" (. pp x) (. pp y))
|
||||
|
||||
(var table (¤ int 3))
|
||||
(= (¤ table 0) 10)
|
||||
(= (¤ table 1) 20)
|
||||
(var first _ (¤ table 0))
|
||||
(var second _ (¤ table 1))
|
||||
(var table [int 3])
|
||||
(= [table 0] 10)
|
||||
(= [table 1] 20)
|
||||
(var first _ [table 0])
|
||||
(var second _ [table 1])
|
||||
(printf "arrays: %d\n" (+ first second))
|
||||
|
||||
;; a for opens a scope, and its initializer is declared inside it
|
||||
@@ -67,14 +68,18 @@
|
||||
(var wide int 200)
|
||||
(while false (var wide char 1) (printf "%d" wide))
|
||||
(if false (do (var wide char 1) (printf "%d" wide)))
|
||||
;; a statement before the declaration: a label may not be followed by
|
||||
;; one until C23
|
||||
(switch a (case 1 (printf "") (var wide char 1) (printf "%d" wide) (break)))
|
||||
(switch a (case 1 (var wide char 1) (printf "%d" wide)))
|
||||
;; a copy, not a sum: an arithmetic result would be promoted to `int'
|
||||
;; whatever leaked, and say nothing
|
||||
(var copy _ wide)
|
||||
(printf "still an int: %d\n" copy)
|
||||
|
||||
;; each case is a block of its own: the second sees the outer `wide',
|
||||
;; not the first one's
|
||||
(switch 2
|
||||
(case 1 (var wide double 1.5) (printf "%g" wide))
|
||||
(case 2 (var seen _ wide) (printf "case scope: %d\n" seen)))
|
||||
|
||||
;; a wildcard inside a written type: only it is solved
|
||||
(var pp2 (* _) (& p))
|
||||
(printf "partial: %d %g\n" (. pp2 x) (. pp2 y))
|
||||
@@ -103,7 +108,7 @@
|
||||
;; a brace initializer has no type of its own, but its elements solve
|
||||
;; the hole in the array type around it -- and the length stays as
|
||||
;; written, whether or not every slot is initialized
|
||||
(var squares (¤ _ 4) #(0 1 4 9))
|
||||
(var sparse (¤ _ 8) #(0 1))
|
||||
(printf "from elements: %d %d %d\n" (¤ squares 2) (¤ squares 3) (¤ sparse 7))
|
||||
(var squares [_ 4] #(0 1 4 9))
|
||||
(var sparse [_ 8] #(0 1))
|
||||
(printf "from elements: %d %d %d\n" [squares 2] [squares 3] [sparse 7])
|
||||
(return 0))
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
(ops expr
|
||||
(pub fn eval ((self (* const expr))) float
|
||||
;; v, e, l and r are copies of the fields, not references to them
|
||||
(match (* self)
|
||||
((lit (v)) (return v))
|
||||
((neg (e)) (return (- (.eval e))))
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
add-sum!
|
||||
get-sum
|
||||
add-constructor!
|
||||
get-constructor
|
||||
variant-fields
|
||||
reset-declarations!
|
||||
|
||||
@@ -40,7 +42,6 @@
|
||||
|
||||
type-head?
|
||||
named-arg?
|
||||
typedef-name?
|
||||
array-bound?
|
||||
array-element-type)
|
||||
"../types.scm")
|
||||
|
||||
@@ -139,6 +139,10 @@
|
||||
(test "enum values are fields whose type is the enum"
|
||||
'((red (enum t-color)) (green (enum t-color)) (blue (enum t-color)))
|
||||
(map-fields 't-color (lambda (name type) (list name type))))
|
||||
(add-enum 't-wire '(enum t-wire ((t-varint 0) (t-fixed64 1) t-bytes)))
|
||||
(test "an enumerator with a value is still named by its name"
|
||||
'(t-varint t-fixed64 t-bytes)
|
||||
(map-fields 't-wire (lambda (name type) name)))
|
||||
(test "a typedef has no fields to map"
|
||||
#f
|
||||
(map-fields 't-u8 (lambda (name type) name)))
|
||||
@@ -217,4 +221,24 @@
|
||||
(get-name-type 't-never-declared))
|
||||
(test "nor a return type"
|
||||
#f
|
||||
(get-return-type 't-never-declared)))
|
||||
(get-return-type 't-never-declared))
|
||||
|
||||
;; Where an array's element type ends is a matter of shape, not of
|
||||
;; what the database happens to hold: a typedef from a C header is
|
||||
;; never in it
|
||||
(test-group "array bounds"
|
||||
(test-assert "a number" (array-bound? '(¤ int 4)))
|
||||
(test-assert "a name after a specifier" (array-bound? '(¤ int N)))
|
||||
(test-assert "a name after a type name unknown to Sex"
|
||||
(array-bound? '(¤ pthread-t N)))
|
||||
(test-assert "a name after a grouped type"
|
||||
(array-bound? '(¤ (* t-point) N)))
|
||||
(test-assert "a name after a tag" (array-bound? '(¤ struct t-point N)))
|
||||
(test-assert "not a lone type" (not (array-bound? '(¤ pthread-t))))
|
||||
(test-assert "not a specifier" (not (array-bound? '(¤ unsigned int))))
|
||||
(test-assert "not a qualified name" (not (array-bound? '(¤ const t))))
|
||||
(test-assert "not a pointer's target" (not (array-bound? '(¤ * size-t))))
|
||||
(test-assert "not a tag" (not (array-bound? '(¤ struct t-point))))
|
||||
(test "the element of a grouped type is the group"
|
||||
'(* t-point)
|
||||
(array-element-type '(¤ (* t-point) N)))))
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
(chicken io)
|
||||
(chicken pathname)
|
||||
(chicken port)
|
||||
(chicken flonum) ; flonum-print-precision
|
||||
(chicken process)
|
||||
(chicken process-context)
|
||||
(chicken string) ; string-split
|
||||
@@ -93,6 +94,9 @@
|
||||
(let* ((proc (process compiler (append (list "-o" compiled-file) flags)))
|
||||
(sexc-stdin (process-input-port proc)))
|
||||
(symbol-escape #f)
|
||||
;; ...nor any double in the 15 digits CHICKEN prints by default,
|
||||
;; which make 0.16666666666666666 another number
|
||||
(flonum-print-precision 17)
|
||||
(with-output-to-port sexc-stdin
|
||||
(fn (map (fn (fmt #t x)) src)))
|
||||
(close-output-port sexc-stdin)
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
add-sum!
|
||||
get-sum
|
||||
add-constructor!
|
||||
get-constructor
|
||||
variant-fields
|
||||
reset-declarations!
|
||||
|
||||
@@ -40,7 +42,6 @@
|
||||
|
||||
type-head?
|
||||
named-arg?
|
||||
typedef-name?
|
||||
array-bound?
|
||||
array-element-type)
|
||||
"types.scm")
|
||||
|
||||
80
types.scm
80
types.scm
@@ -100,10 +100,19 @@
|
||||
(define +sum-db+ (make-hash-table))
|
||||
|
||||
(define (add-sum! name variants)
|
||||
(hash-table-set! +sum-db+ name variants))
|
||||
(hash-table-set! +sum-db+ (type-key name) variants))
|
||||
|
||||
(define (get-sum name)
|
||||
(hash-table-ref/default +sum-db+ name #f))
|
||||
(hash-table-ref/default +sum-db+ (type-key name) #f))
|
||||
|
||||
;;; shape/circle -> (shape . circle), for each variant of each sum
|
||||
(define +constructor-db+ (make-hash-table))
|
||||
|
||||
(define (add-constructor! constructor sum variant)
|
||||
(hash-table-set! +constructor-db+ constructor (cons sum variant)))
|
||||
|
||||
(define (get-constructor name)
|
||||
(hash-table-ref/default +constructor-db+ name #f))
|
||||
|
||||
(define (variant-fields variants name)
|
||||
(let ((entry (assq name variants)))
|
||||
@@ -130,17 +139,18 @@
|
||||
(define (spec-methods spec) (cdr spec))
|
||||
|
||||
(define (add-realization! spec type)
|
||||
(hash-table-set! +realize-db+ (cons spec type) #t))
|
||||
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
|
||||
|
||||
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
|
||||
(define (realizes? spec type)
|
||||
(hash-table-exists? +realize-db+ (cons spec type)))
|
||||
(hash-table-exists? +realize-db+ (cons spec (type-key type))))
|
||||
|
||||
;;; Both of these refuse a second declaration of the same name, which
|
||||
;;; is per translation unit rather than per process -- so a process
|
||||
;;; that compiles two units has to start the second one clean.
|
||||
(define (reset-declarations!)
|
||||
(set! +sum-db+ (make-hash-table))
|
||||
(set! +constructor-db+ (make-hash-table))
|
||||
(set! +ops-db+ (make-hash-table))
|
||||
(set! +spec-db+ (make-hash-table))
|
||||
(set! +realize-db+ (make-hash-table)))
|
||||
@@ -156,10 +166,10 @@
|
||||
(define +ops-db+ (make-hash-table))
|
||||
|
||||
(define (add-method! type method qualified)
|
||||
(hash-table-set! +ops-db+ (cons type method) qualified))
|
||||
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
|
||||
|
||||
(define (get-method type method)
|
||||
(hash-table-ref/default +ops-db+ (cons type method) #f))
|
||||
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
|
||||
|
||||
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
|
||||
(define (qualify-op type name)
|
||||
@@ -169,13 +179,33 @@
|
||||
;;; The name an `ops' block was written against: `(struct point)' and a
|
||||
;;; `const' wrapper both name `point', and anything else names nothing.
|
||||
(define (ops-key type)
|
||||
(cond ((symbol? type) type)
|
||||
(cond ((symbol? type) (type-key type))
|
||||
((not (and (pair? type) (symbol? (car type)))) #f)
|
||||
((memq (car type) '(struct union enum))
|
||||
(and (pair? (cdr type)) (symbol? (cadr type)) (cadr type)))
|
||||
((memq (car type) '(const volatile)) (ops-key (cadr type)))
|
||||
(else #f)))
|
||||
|
||||
;;; The name methods, realizations and sums are filed under. A typedef
|
||||
;;; is followed to the aggregate it names, and one that ends in anything
|
||||
;;; else stops at the last typedef, so a scalar does not share them:
|
||||
;;;
|
||||
;;; (record v ...) (typedef alias v) alias -> v
|
||||
;;; (typedef meters float) meters -> meters
|
||||
;;; (typedef km meters) km -> meters
|
||||
(define (type-key name)
|
||||
(let follow ((name name) (seen (list)))
|
||||
(let ((target (and (not (memq name seen)) (typedef-target name))))
|
||||
(cond ((not target) name)
|
||||
((symbol? target)
|
||||
(if (typedef-target target) (follow target (cons name seen)) name))
|
||||
((target-tag target))
|
||||
(else name)))))
|
||||
|
||||
(define (typedef-target name)
|
||||
(let ((info (and (symbol? name) (get-type-info name))))
|
||||
(and info (eq? (car info) 'typedef) (caddr info))))
|
||||
|
||||
(define (add-name-type! name type)
|
||||
(hash-table-set! +name-db+ name type))
|
||||
|
||||
@@ -304,7 +334,8 @@
|
||||
(else (equal? pattern type))))
|
||||
|
||||
;;; Map function to each field/value of a structure/union/enum
|
||||
;;; For enums, field-type is the type of the enum (since C 23)
|
||||
;;; For enums, field-type is the type of the enum (since C 23), and
|
||||
;;; field-name the enumerator's name, (wire-varint 0) or not
|
||||
;;; (map-fields type-name
|
||||
;;; (lambda (field-name field-type) ...))
|
||||
;;;
|
||||
@@ -320,7 +351,8 @@
|
||||
;; declared, since `enum some-typedef' is not a C type.
|
||||
((enum)
|
||||
(let ((type (list 'enum (cadr info))))
|
||||
(map (lambda (value) (fn value type))
|
||||
(map (lambda (value)
|
||||
(fn (if (pair? value) (car value) value) type))
|
||||
(caddr info))))
|
||||
(else #f)))))
|
||||
|
||||
@@ -357,22 +389,15 @@
|
||||
(pair? (cdr arg)) ; 1 element args are always type
|
||||
(not (type-head? arg))))
|
||||
|
||||
;;; A typedef and a `define' share +type-db+; only the typedef is part
|
||||
;;; of a type:
|
||||
;;; The last element is a bound unless what precedes it is still
|
||||
;;; waiting for a type name -- a `*', a qualifier, a tag's keyword. C
|
||||
;;; spells a type with one name at most, so a name after a name, or
|
||||
;;; after a grouped type, can only be the bound:
|
||||
;;;
|
||||
;;; (typedef small int) -> (¤ small N) is N of small
|
||||
;;; (define CAP 4) -> (¤ int CAP) is CAP of int
|
||||
(define (typedef-name? name)
|
||||
(let ((info (and (symbol? name) (get-type-info name))))
|
||||
(and info (memq (car info) '(typedef struct union enum)) #t)))
|
||||
|
||||
;;; The last element is a bound only where what precedes it already
|
||||
;;; spells a whole type -- a specifier, a tag after its keyword, or a
|
||||
;;; typedef we have seen declared:
|
||||
;;;
|
||||
;;; (¤ int 4) four of int (¤ unsigned int) unsized
|
||||
;;; (¤ mytype CAP) CAP of mytype (¤ struct point) unsized
|
||||
;;; (¤ const mytype) unsized (¤ * size-t) unsized
|
||||
;;; (¤ int 4) four of int (¤ unsigned int) unsized
|
||||
;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized
|
||||
;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized
|
||||
;;; (¤ * size-t) unsized
|
||||
;;;
|
||||
;;; TYPE is the whole `(¤ ...)' form.
|
||||
(define (array-bound? type)
|
||||
@@ -382,11 +407,8 @@
|
||||
(cond
|
||||
((not (symbol? bound)) #t)
|
||||
((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f)
|
||||
((memq preceding +c-specifiers+) #t)
|
||||
;; a tag always follows its keyword, so `(¤ * struct tt)' ends
|
||||
;; in a name belonging to the type
|
||||
((memq preceding '(struct union enum)) #f)
|
||||
(else (typedef-name? preceding))))))
|
||||
(else (not (or (memq preceding '(* struct union enum))
|
||||
(memq preceding +c-qualifiers+))))))))
|
||||
|
||||
;;; What one element of a written array type is:
|
||||
;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char)
|
||||
|
||||
Reference in New Issue
Block a user