diff --git a/Makefile b/Makefile index 2ba0f4c..08e181e 100644 --- a/Makefile +++ b/Makefile @@ -119,6 +119,7 @@ SEX_TEST_PROGRAMS = c11 \ lists \ operators \ ops \ + precedence \ records \ serialize \ specs \ diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 35be150..c3f6219 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -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 all three parts in init's slot and the body in test's +(define (check-for-header form slots) + (cond ((and (pair? slots) (list? (car slots)) (= 3 (length (car slots))) + (every pair? (car 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,24 @@ 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+ + (map (lambda (spelling) (cons (irregex (car spelling)) (cdr spelling))) + '(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ")))) + (define (unkebabify sym) - (case sym - ((- -- -> -= / /=) sym) ; bare operators, not names - (else - (string->symbol - (irregex-replace/all - "/" - (irregex-replace/all "-(?!>)" (symbol->string sym) "_") - "ː"))))) + (let ((name (symbol->string sym))) + (if (or (memq sym '(- -- -> -= / /= ! != ?)) ; bare operators, not names + (not (string-index name (lambda (c) (memv c '(#\- #\/ #\? #\!)))))) + sym + (string->symbol + (fold (lambda (spelling name) + (irregex-replace/all (car spelling) name (cdr spelling))) + name + +name-spellings+))))) (define (atom-to-fmt-c atom) (case atom @@ -194,6 +229,12 @@ forms, and what remains." ;; path lowers to where the thing it reads from is a pointer (('%-> . 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) @@ -208,15 +249,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)) @@ -235,12 +275,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))))) @@ -315,7 +355,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))))) @@ -446,11 +486,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 . _) @@ -498,7 +544,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 diff --git a/reader.scm b/reader.scm index 566fd10..42ec90b 100644 --- a/reader.scm +++ b/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) diff --git a/semen.scm b/semen.scm index 62aba86..a60efa5 100644 --- a/semen.scm +++ b/semen.scm @@ -415,17 +415,32 @@ ;;; 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)) + ;; the signatures too, which a call's receiver is fitted to + (protos (map (lambda (m) (process-fn (sex-fn-prototype m) (list))) fns)) + (bodies (map (lambda (m) + (if (comment-form? m) (list m) (process-fn m (list)))) + methods)) + (early (filter-map (lambda (m proto) + (and (called-before? m methods bodies) proto)) + fns protos))) + (append (concatenate (reverse bodies)) + (fold append 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))) @@ -433,9 +448,23 @@ (let ((name (second core))) (when (get-method type name) (sex-error form "method is already defined on" type name)) - (let ((qualified (qualify-op type name))) + (let* ((qualified (qualify-op type name)) + (renamed (rename-fn form qualified))) (add-method! type name qualified) - (process-fn (rename-fn form qualified) acc)))))) + renamed))))) + +;;; Does a body written above METHOD call it? +(define (called-before? method methods bodies) + (let ((name (sex-fn-name method))) + (let loop ((ms methods) (bs bodies)) + (and (not (eq? (car ms) method)) + (or (mentions? (car bs) name) + (loop (cdr ms) (cdr bs))))))) + +;;; (pub fn name args ret ...) -> (pub fn name args ret) +(define (sex-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)) @@ -458,25 +487,6 @@ (set! (hash-table-ref env :scopes) (list parameters)) env)) -;;; `(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 (named-arg? param) - (list (named-arg-type param)) - param)) - arglist)) - (define (fn-type-of fn-form) `(fn ,(arglist-types (sex-fn-arglist fn-form)) ,(sex-fn-return-type fn-form))) @@ -501,9 +511,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)) @@ -572,7 +581,7 @@ (define (walk-statement form env) (cond - ((vector? form) (walk-literal form env)) + ((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 @@ -584,20 +593,13 @@ (cons walk-embed-result (walk-body expansion env))))) (else (case (car form) - ((do) + ((do default) (parameterize ((operand-position? #f)) (with-scope env (lambda () (walk-parts form env))))) - ((for while if switch) + ((for while if switch case case/fallthrough) (with-scope env (lambda () (walk-control form env)))) - ((case case/fallthrough) - (walk-control form env)) - - ((default) - (parameterize ((operand-position? #f)) - (walk-parts form env))) - ((lambda) (let ((name (aux-name! env make-lambda-name))) (add-aux-code! env (lift-lambda name form)) @@ -668,6 +670,14 @@ ((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 (cond ((method-head? (car form)) (walk-method-call form env)) @@ -766,14 +776,31 @@ (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-operand 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) + (match form + ((or ('* operand) ('¤ operand _)) + (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) @@ -835,9 +862,11 @@ (define (wildcard-type? type) (mentions? type '_)) -(define (mentions? type word) - (cond ((eq? type word) #t) - ((list? type) (any (lambda (part) (mentions? part word)) type)) +;;; WORD anywhere in FORM, a literal's contents included +(define (mentions? form word) + (cond ((eq? form word) #t) + ((pair? form) (or (mentions? (car form) word) (mentions? (cdr form) word))) + ((vector? form) (mentions? (vector->list form) word)) (else #f))) ;;; `(each xs compare)' where `each' takes a closure: the argument is @@ -1085,7 +1114,10 @@ ;;; (. 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 x) warns of (. font handle), not +;;; font. A field a struct declared here lacks is an error. (define (walk-member-path form env) (let ((base (second form))) (let step ((expr (walk-operand base env)) @@ -1094,15 +1126,25 @@ (told? #f)) (if (null? fields) (copy-form-source! form expr) - (let ((target (pointer-target type))) + (let* ((target (pointer-target type)) + (known (type-fields (or target type)))) + (when (and (pair? known) (not (assq (field-name (car fields)) known))) + (sex-error form "no field of this name in" (or target type) (car fields))) (unless (or type told?) - (sex-warning form "cannot type this; `.' reads it as a value" - base)) + (let ((walked (drop-right (cddr form) (length fields)))) + (sex-warning form "cannot type this; `.' reads it as a value" + (if (null? walked) base `(|.| ,base ,@walked))))) (step (list (if target '%-> 'dot-access) expr (car fields)) (field-type (or target type) (car fields)) (cdr fields) (or told? (not type)))))))) +;;; A field of a path, indexed or not: xs, [xs 0] -> xs +(define (field-name field) + (if (and (array-form? field) (pair? (cdr field))) + (second field) + field)) + (define (lvalue? expr) (cond ((symbol? expr) #t) ((vector? expr) #t) ; a compound literal is one @@ -1844,7 +1886,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)) @@ -1935,12 +1979,6 @@ Returns #f if the form is not a function, returns the form otherwise" (fmt #f "Form " fn-form " is not a function")) (fourth (fn-core fn-form))) -(define (sex-fn-prototype fn-form) - "Returns all except body" - (assert (sex-fn? fn-form) - (fmt #f "Form " fn-form " is not a function")) - (take fn-form (fn-header-length fn-form))) - (define (sex-fn-body fn-form) (assert (sex-fn? fn-form) (fmt #f "Form " fn-form " is not a function")) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 89f8835..4be8e0c 100644 --- a/sex-fmt-c.scm +++ b/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,20 +901,31 @@ tail)))) st)))) + ;; 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 c p . rest) - (let lp ((c c) (p p) (ls rest)) - (cond - ((or (eq? c 'else) (eq? c #t)) - (if (not (null? ls)) - (error "forms after else clause in IF" c p ls) - (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) '())))) - (else - (c-or (c-in-test (c-expr c)) (c-expr p)))))) + (c-maybe-paren + '? + (let lp ((c c) (p p) (ls rest)) + (cond + ((or (eq? c 'else) (eq? c #t)) + (if (not (null? ls)) + (error "forms after else clause in IF" c p ls) + (c-expr p))) + ((pair? ls) + (cat (c-in-test (c-expr c)) " ? " (c-expr p) " : " + (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))))))) (define (c-if . args) (fmt-if fmt-expression? diff --git a/sex-modules.module.scm b/sex-modules.module.scm index 7b56569..82f61e7 100644 --- a/sex-modules.module.scm +++ b/sex-modules.module.scm @@ -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") diff --git a/sex-modules.scm b/sex-modules.scm index c3f1c61..428e398 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -78,17 +78,234 @@ (file-readable? module-path) module-path)))) +;;; Every module file read for this unit, with its forms, last read +;;; first: what its output depends on, besides the unit itself. A module +;;; that an import chain and the interface check both reach is read once +(define +modules-read+ (list)) + +(define (module-dependencies) (reverse (map car +modules-read+))) + +(define (read-module path) + (cond ((assoc path +modules-read+) => cdr) + (else (let ((forms (read-from-file path))) + (set! +modules-read+ (cons (cons path forms) +modules-read+)) + forms)))) + (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)) + (remedy (if (and kept (fourth kept)) "import its module with pub" "make it pub"))) + (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; " + remedy) + name)) + ((not (cdr use)) + (sex-error form (string-append "importers cannot see this type, held by value; " + remedy ", 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 pub-form? 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 (arglist-types (remove comment-form? args)))) + +;;; 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 . #f) (int . #f)) +;;; +;;; A function type takes and returns by value whatever it is held +;;; through: C wants the body to define or call one of its functions. +(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 #f)) + (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 (strip-pub 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: its whole entries come first, for `assq' +(define (visible-types forms) + (let ((all (append (declared-types (filter pub-form? forms)) + (append-map exported-types (imported-modules forms #t))))) + (append (filter third all) (remove third 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 next ((modules (list module)) (seen (list)) (acc (list))) + (if (null? modules) + (concatenate (reverse acc)) + (let ((path (locate-module (symbol->string (car modules))))) + (if (or (not path) (member path seen)) + (next (cdr modules) seen acc) + (let ((exports (module-exports path))) + (next (append (cdr modules) (cdr exports)) + (cons path seen) + (cons (car exports) acc)))))))) + +;;; The types the module at PATH declares to its importers, and the +;;; modules its interface imports; worked out once, though the check of +;;; every module above it on a pub import chain walks there +(define +module-exports+ (list)) + +(define (module-exports path) + (cond ((assoc path +module-exports+) => cdr) + (else (let* ((forms (interface-forms (read-module path))) + (exports (cons (declared-types forms) + (imported-modules forms #f)))) + (set! +module-exports+ (cons (cons path exports) +module-exports+)) + exports)))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so @@ -159,6 +376,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 ":")))))) diff --git a/sexc.scm b/sexc.scm index ac612a0..9708be3 100644 --- a/sexc.scm +++ b/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) "With -C, -m or --public-interface, defaults to stdout," nl + (pad padding) "which `-' names 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))) @@ -125,8 +142,17 @@ 'stdin (car rest-args)))) +(define (stdout-output? output) + (or (eq? output 'default) (equal? output "-"))) + +;;; Whether ARGS ask for text, which `-o -' can send to stdout. An +;;; executable or an object goes to cc's -o, where `-' is a file name +(define (text-output? args) + (any (lambda (option) (get-arg args option #f)) + '(emit-c macro-expand public-interface))) + (define (write-to-file-or-stdout output what) - (if (eq? output 'default) + (if (stdout-output? output) (what) (with-output-to-file output (fn (what))))) @@ -138,6 +164,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 (stdout-output? 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 +216,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 +248,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)) @@ -208,6 +260,8 @@ status, which is ours to pass on." (when help (print-help) (return #f)) + (when (and (equal? output "-") (not (text-output? args))) + (error "-o - is stdout, which takes only -C, -m or --public-interface")) ;; Read time comes before everything, so the features have to be ;; in place before the first form is read (current-features @@ -216,16 +270,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 +291,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 diff --git a/tests/Makefile b/tests/Makefile index 1e87b3c..9a4b6c6 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -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) diff --git a/tests/args.scm b/tests/args.scm index c4ced0f..a757a1b 100644 --- a/tests/args.scm +++ b/tests/args.scm @@ -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")))) diff --git a/tests/basic.scm b/tests/basic.scm index 3456f0b..f03157d 100644 --- a/tests/basic.scm +++ b/tests/basic.scm @@ -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, diff --git a/tests/codegen.scm b/tests/codegen.scm index 7fe9c25..d3cd632 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -15,12 +15,15 @@ semen utils) +(define (read-source source) + (with-input-from-string source + (lambda () + (parameterize ((current-source-file "codegen.sex")) + (parse-all (current-input-port)))))) + (define (sex->c source) "Compile SOURCE, a string of Sex, and return the generated C." - (let ((forms (with-input-from-string source - (lambda () - (parameterize ((current-source-file "codegen.sex")) - (parse-all (current-input-port))))))) + (let ((forms (read-source source))) (with-output-to-string (lambda () (parameterize ((sex-line-directives 'none)) @@ -37,21 +40,32 @@ (define (emits? source fragment) (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) -(define (error-message source) - "Compile SOURCE and return the error text as the user sees it -- -message plus arguments, the way CHICKEN prints it -- or #f if SOURCE -compiles." +(define (failure-message thunk) + "The error THUNK raises as the user sees it -- message plus arguments, +the way CHICKEN prints it -- or #f if it raises none." (handle-exceptions e (with-output-to-string (lambda () (display ((condition-property-accessor 'exn 'message) e)) (for-each (lambda (a) (display " ") (write a)) ((condition-property-accessor 'exn 'arguments) e)))) - (begin (sex->c source) #f))) + (begin (thunk) #f))) + +(define (fails-with? thunk fragment) + (let ((m (failure-message thunk))) + (and m (string-contains m fragment) #t))) (define (reports? source fragment) - (let ((m (error-message source))) - (and m (string-contains m fragment) #t))) + (fails-with? (lambda () (sex->c source)) fragment)) + +(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 ")")) @@ -75,6 +89,22 @@ compiles." (test-group "codegen" + ;; 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))))") + "{" "{")))) + ;; 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))'. @@ -114,7 +144,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 +253,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 @@ -244,6 +335,25 @@ compiles." (test-assert "pub with nothing to define" (reports? "(pub 1)" "codegen.sex:1:"))) + ;; 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 "whatever its init is" + (reports? (in-fn "(for ((= a 0) (< a 4) (++ a)) (g a))") + "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:"))) + ;; A nested pointer chain used to silently lose a level: ;; (var p (* (* char))) emitted `char *p' (test-group "malformed types are rejected" @@ -328,7 +438,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 +559,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 +633,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 +644,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" @@ -631,7 +741,8 @@ compiles." (not (emits? "(struct pt ((x int))) (fn f ((p (* (struct pt)))) int (return (. (* p) x)))" "*(p).x"))) (test-assert "member access through a cast" - (emits? (in-fn "(var n int (. (* (cast a (* (struct s)))) f))") + (emits? (string-append "(struct s ((f int)))" + (in-fn "(var n int (. (* (cast a (* (struct s)))) f))")) "(*(struct s*)a).f")) ;; ...without gaining parens where none are due (test-assert "a bare dereference is left alone" @@ -642,26 +753,113 @@ 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[]")) + ;; a qualifier waits for a type name only when none came before it + (test-assert "a name after a qualified type is a bound" + (emits? (in-fn "(var b [int const N])") "int const b[N]")) + (test-assert "after a qualified name too" + (emits? (in-fn "(var b [mytype const N])") "mytype const b[N]")) + (test-assert "but a qualifier alone still waits for the type" + (emits? "(typedef mytype int) (struct s ((a [const mytype])))" "const mytype 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,6 +883,22 @@ 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"))) + (test-assert "but a struct declared here has only the fields it names" + (reports? (in-line "(= (. p z) 1)") "no field of this name")) + (test-assert "the last step included" + (reports? (in-line "(= (. lp a z) 1)") "no field of this name")) + (test-assert "an indexed one by its name" + (reports? (string-append "(struct v ((xs [int 2])))" + (in-fn "(var w (struct v)) (= (. w [ys 0]) 1)")) + "no field of this name")) ;; 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 diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 8df2b09..d4d9a67 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -5,8 +5,18 @@ ;;; is checked here is what the compiler refuses, and that it refuses ;;; it with the name of whatever is wrong. ;;; -;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, -;;; which run.scm includes first. +;;; `sex->c', `read-source', `fails-with?', `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 (read-source source))) + +(define (interface-reports? source fragment) + (fails-with? (lambda () (interface-of source)) fragment)) (define (ops-src . body) (string-append @@ -19,6 +29,13 @@ "(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 ())))" @@ -79,7 +96,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. @@ -473,4 +498,75 @@ "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 function a pub one takes" + (interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn ((c cell)) void))) void)" + "held by value")) + (test-assert "or returned by one" + (interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn () cell))) void)" + "held by value")) + (test "but a pointer there is still a pointer" + '((record cell)) + (interface-of "(record cell ((v int))) (pub fn take ((cb (fn ((c (* cell))) void))) void)")) + (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])))")))) diff --git a/tests/exit-code/Makefile b/tests/exit-code/Makefile index 4dc32f4..79b8837 100644 --- a/tests/exit-code/Makefile +++ b/tests/exit-code/Makefile @@ -1,12 +1,14 @@ # The failure paths. # -# Both need a process to show themselves, so neither fits the unit -# suite: sexc has to fail when cc fails -- exiting 0 after a failed -# compile makes every driver, sextest included, read it as success -- -# and it has to clean up its temporary .c when its own emission throws. +# Each needs a process to show itself, so none fits the unit suite: +# sexc has to fail when cc fails -- exiting 0 after a failed compile +# makes every driver, sextest included, read it as success -- it has to +# clean up its temporary .c when its own emission throws, and it has to +# refuse `-o -' for an executable, which cc would write to a file named +# `-'. # -# Everything is built inside a scratch TMPDIR, so nothing is left here -# to clean up. +# Everything is built inside a scratch directory, so nothing is left +# here to clean up. SEXC ?= ../../sexc @@ -21,6 +23,10 @@ check: echo "exit code FAILED: sexc reported success after cc failed"; \ rm -rf $$d; exit 1; \ fi; \ + if (cd $$d && $(abspath $(SEXC)) $(CURDIR)/hello.sex -o - >/dev/null 2>&1) || [ -e $$d/- ]; then \ + echo "exit code FAILED: -o - built an executable"; \ + rm -rf $$d; exit 1; \ + fi; \ rm -rf $$d; echo "exit code ok" .PHONY: check diff --git a/tests/line-directives.scm b/tests/line-directives.scm index fa11abd..7a82100 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -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. diff --git a/tests/module-path.scm b/tests/module-path.scm new file mode 100644 index 0000000..fbce788 --- /dev/null +++ b/tests/module-path.scm @@ -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")) diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 034cd95..d43c2f1 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -17,15 +17,32 @@ # 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: + @head="`$(SEXC) --public-interface greet.sex | head -3`"; \ + if [ "$$head" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \ + echo "modules FAILED, the interface begins:"; echo "$$head"; 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 +51,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 diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 7675207..0836313 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -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)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 3da58b3..575636e 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -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 diff --git a/tests/modules/ledger.sex b/tests/modules/ledger.sex new file mode 100644 index 0000000..14cbea7 --- /dev/null +++ b/tests/modules/ledger.sex @@ -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)) diff --git a/tests/reader.scm b/tests/reader.scm index 7367b48..a77ca0a 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -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") diff --git a/tests/run.scm b/tests/run.scm index d0cc9ca..8464382 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -10,6 +10,7 @@ (include "codegen.scm") (include "encapsulation.scm") (include "args.scm") +(include "module-path.scm") (include "types.scm") (include "infer.scm") diff --git a/tests/sex-programs/closures.sex b/tests/sex-programs/closures.sex index d5d3e06..fa20184 100644 --- a/tests/sex-programs/closures.sex +++ b/tests/sex-programs/closures.sex @@ -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 diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index ec1e5df..3aad6c5 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -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)) diff --git a/tests/sex-programs/inference.sex b/tests/sex-programs/inference.sex index b5d3f0a..d8b1ae5 100644 --- a/tests/sex-programs/inference.sex +++ b/tests/sex-programs/inference.sex @@ -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 diff --git a/tests/sex-programs/operators.sex b/tests/sex-programs/operators.sex index bd730bc..7481f55 100644 --- a/tests/sex-programs/operators.sex +++ b/tests/sex-programs/operators.sex @@ -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)) diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex index 12bb812..2a83491 100644 --- a/tests/sex-programs/ops.sex +++ b/tests/sex-programs/ops.sex @@ -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)) diff --git a/tests/sex-programs/precedence.sex b/tests/sex-programs/precedence.sex new file mode 100644 index 0000000..7e8ad2e --- /dev/null +++ b/tests/sex-programs/precedence.sex @@ -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)) diff --git a/tests/sex-programs/type-shapes.sex b/tests/sex-programs/type-shapes.sex index 56a99df..58f6c25 100644 --- a/tests/sex-programs/type-shapes.sex +++ b/tests/sex-programs/type-shapes.sex @@ -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)) diff --git a/tests/sex-programs/unicode.sex b/tests/sex-programs/unicode.sex index 93fa7d3..a89543c 100644 --- a/tests/sex-programs/unicode.sex +++ b/tests/sex-programs/unicode.sex @@ -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)) diff --git a/tests/sex-programs/unnamed-params.sex b/tests/sex-programs/unnamed-params.sex index 34e1940..225b62a 100644 --- a/tests/sex-programs/unnamed-params.sex +++ b/tests/sex-programs/unnamed-params.sex @@ -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") diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 1bf0764..558a6d5 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -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)) diff --git a/tests/types.module.scm b/tests/types.module.scm index 7b0f366..d905dff 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -42,7 +42,9 @@ type-head? named-arg? - typedef-name? + named-arg-type + arglist-types + strip-pub array-bound? array-element-type) "../types.scm") diff --git a/tests/types.scm b/tests/types.scm index ec17c68..144e770 100644 --- a/tests/types.scm +++ b/tests/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))))) diff --git a/tools/sextest/sextest.scm b/tools/sextest/sextest.scm index 43f3d5f..459a8e5 100644 --- a/tools/sextest/sextest.scm +++ b/tools/sextest/sextest.scm @@ -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) diff --git a/types.module.scm b/types.module.scm index e2a67c5..d4b98e1 100644 --- a/types.module.scm +++ b/types.module.scm @@ -42,7 +42,9 @@ type-head? named-arg? - typedef-name? + named-arg-type + arglist-types + strip-pub array-bound? array-element-type) "types.scm") diff --git a/types.scm b/types.scm index 78a183c..182ddac 100644 --- a/types.scm +++ b/types.scm @@ -335,7 +335,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) ...)) ;;; @@ -351,7 +352,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))))) @@ -388,22 +390,34 @@ (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: -;;; -;;; (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))) +;;; `(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))) -;;; 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: +;;; (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 (named-arg? param) + (list (named-arg-type param)) + param)) + arglist)) + +;;; The last element is a bound unless what precedes it is still +;;; waiting for a type name -- a `*', a tag's keyword, a qualifier with +;;; no type before it. 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: ;;; -;;; (¤ 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 +;;; (¤ int const N) N of const int (¤ * size-t) unsized ;;; ;;; TYPE is the whole `(¤ ...)' form. (define (array-bound? type) @@ -413,11 +427,13 @@ (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)))))) + ((memq preceding '(* struct union enum)) #f) + ((memq preceding +c-qualifiers+) + (any (lambda (word) + (not (or (memq word '(* struct union enum)) + (memq word +c-qualifiers+)))) + (drop-right (cdr type) 2))) + (else #t))))) ;;; What one element of a written array type is: ;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char)