Compare commits
71 Commits
main
...
25aa03ac77
| Author | SHA1 | Date | |
|---|---|---|---|
| 25aa03ac77 | |||
| e940f2d2f1 | |||
| b458f94566 | |||
| 0246f3b54f | |||
| bfb4c116b0 | |||
| 3f3e5f2358 | |||
| 6109242cb0 | |||
| ba06256c74 | |||
| 6af837834a | |||
| e47aa387f5 | |||
| 3f560594c4 | |||
| ca4ac949d8 | |||
| 28f815303a | |||
| 075da9191f | |||
| 25bd4484ba | |||
| df79f6b4ea | |||
| a29dd89792 | |||
| 6da6bb89fb | |||
| fd5db617fe | |||
| d75c3eb4a2 | |||
| bfc4521b89 | |||
| 150bcfa037 | |||
| fcb7524ba1 | |||
| 45ef052f43 | |||
| 63e6cec8e1 | |||
| aba8a411cc | |||
| fd76937fca | |||
| 755a733252 | |||
| b744fb2e31 | |||
| d14ca86e70 | |||
| 5a3ead0fa2 | |||
| fa8324348c | |||
| 6519f532f4 | |||
| 647f7f9eca | |||
| 28e967ef25 | |||
| e83a3b4a96 | |||
| 17d1467d1e | |||
| 0313b04a70 | |||
| d6ad58f9c0 | |||
| 817cddd2c8 | |||
| 0e4c2353e7 | |||
| e6863d1b43 | |||
| 59391de9d3 | |||
| a7f7c86ac9 | |||
| 3ca36ff633 | |||
| 3ce76c81f5 | |||
| 974657bc6b | |||
| 8bd991a934 | |||
| 8b5a94dbe0 | |||
| faa7c5fb93 | |||
| f9647df009 | |||
| 3a42340305 | |||
| 9a9df6a430 | |||
| d208ca2371 | |||
| 20fc8cf7ad | |||
| 9fdfbe26b8 | |||
| bc1b5b69d4 | |||
| 829acf3192 | |||
| 30cabc009a | |||
| f607db010f | |||
| 47c421b381 | |||
| 1cfa80595e | |||
| c1c6a3dd15 | |||
| 2568f289fe | |||
| 753406462d | |||
| e835d39f58 | |||
| edfae88e4d | |||
| 8d09d8f68b | |||
| de93c53cd8 | |||
| 910db917a0 | |||
| 7964a08b7a |
11
Makefile
11
Makefile
@@ -53,13 +53,11 @@ endif
|
||||
# imports, or a NAME.scm may have come to be the module an import
|
||||
# names; but modules.mk is rewritten only when that changed, since make
|
||||
# starts over each time it is, and a source dated in the future would
|
||||
# have it start over for good. A stamp without modules.mk stands for
|
||||
# nothing, and is redone whatever its date
|
||||
# have it start over for good
|
||||
modules.mk: modules.stamp ;
|
||||
|
||||
modules.stamp: $(SOURCES) $(filter-out %.import.scm,$(wildcard *.scm)) \
|
||||
tools/module-deps.scm dependencies.txt Makefile \
|
||||
$(if $(wildcard modules.mk),,FORCE)
|
||||
tools/module-deps.scm dependencies.txt Makefile
|
||||
$(CSI) -s tools/module-deps.scm $(PROGRAMS) > modules.mk.tmp \
|
||||
|| { rm -f modules.mk.tmp; exit 1; }
|
||||
if cmp -s modules.mk.tmp modules.mk; then rm modules.mk.tmp; \
|
||||
@@ -90,10 +88,9 @@ check run-tests: sexc sex-tests sextest
|
||||
./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS)
|
||||
@$(MAKE) --no-print-directory check-modules
|
||||
@$(MAKE) --no-print-directory check-exit-code
|
||||
@$(MAKE) --no-print-directory check-command-line
|
||||
|
||||
# The end-to-end checks, each on its own: run with the eggs on the path
|
||||
check-modules check-exit-code check-command-line: check-%: sexc
|
||||
check-modules check-exit-code: check-%: sexc
|
||||
cd tests/$* && SEXC='$(CURDIR)/sexc' $(CSI) -s check.scm
|
||||
|
||||
install: all installdirs
|
||||
@@ -117,4 +114,4 @@ clean:
|
||||
rm -f *.link $(PROGRAM_OBJ:.o=.link)
|
||||
rm -f $(PROGRAM_NAMES)
|
||||
|
||||
.PHONY: all check run-tests check-modules check-exit-code check-command-line install install-strip installdirs uninstall clean FORCE
|
||||
.PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean
|
||||
|
||||
11
Readme.org
11
Readme.org
@@ -317,15 +317,8 @@ best option.
|
||||
*** sex-mode.el
|
||||
To harness the power of sex-mode, add the following lines to your
|
||||
~$HOME/.config/emacs/init.el~:
|
||||
|
||||
#+begin_src emacs-lisp
|
||||
(use-package sex-mode
|
||||
:ensure nil
|
||||
:quelpa
|
||||
(sex-mode :fetcher git
|
||||
:url "https://git.kotobank.ch/alex-eg/sex.git"
|
||||
:files ("sex-mode.el")
|
||||
:upgrade t))
|
||||
:load-path "/path/to/sex"
|
||||
:mode ("\\.sex\\'"))
|
||||
#+end_src
|
||||
|
||||
~.sex~ files then open in ~sex-mode~.
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
(fn sum ((a int) (b int)) int
|
||||
(return (+ a b)))
|
||||
|
||||
;;; A lambda captures nothing and is a bare function pointer; a closure
|
||||
;;; captures and is a value carrying its own environment
|
||||
(fn make-adder ((a int)) (closure ((int)) int)
|
||||
(return (closure ((b int)) int (a)
|
||||
(return (+ a b)))))
|
||||
|
||||
(pub fn main () int
|
||||
(var a int 10)
|
||||
(var b int 20)
|
||||
@@ -35,4 +41,8 @@
|
||||
(return (+ 60 a))))
|
||||
(return (+ 600 (l-2 a)))))
|
||||
(printf "Calling nested lambdas: %d\n" (l-1 6))
|
||||
|
||||
(var add-10 (closure ((int)) int) (make-adder 10))
|
||||
(var add-20 (closure ((int)) int) (make-adder 20))
|
||||
(printf "Calling closures: %d %d\n" (add-10 24) (add-20 24))
|
||||
(return 0))
|
||||
|
||||
@@ -20,7 +20,11 @@
|
||||
|
||||
(export
|
||||
emit-c
|
||||
sex-line-directives)
|
||||
sex-line-directives
|
||||
|
||||
;; for the tests
|
||||
atom-to-fmt-c unkebabify type-convert-to-c
|
||||
process-toplevel-form walk-expr walk-type walk-var walk-fn-def walk-struct)
|
||||
|
||||
;;; egg `tree' not ported to CHICKEN 6 yet
|
||||
(define (tree-map f tree)
|
||||
@@ -134,7 +138,7 @@ forms, and what remains."
|
||||
;;; because the compiler composes these names and the user does not: a
|
||||
;;; hand-written vec2__length would collide, and an identifier holding
|
||||
;;; `__' is reserved in C++, which a pub header may be included from.
|
||||
;;; Lifted lambdas carry a λ for the same reason.
|
||||
;;; 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
|
||||
@@ -227,6 +231,14 @@ forms, and what remains."
|
||||
acc))))))
|
||||
(else (loop (cdr fs) (cons (car fs) acc))))))
|
||||
|
||||
(define (walk-generic-toplevel form)
|
||||
(cond ((atom? form) (name-to-fmt-c form))
|
||||
((list? form) (cons (if (symbol? (car form))
|
||||
(atom-to-fmt-c (car form))
|
||||
(walk-generic-toplevel (car form)))
|
||||
(map walk-generic-toplevel (cdr form))))
|
||||
(else (sex-error form "malformed form" form))))
|
||||
|
||||
(define (walk-expr form)
|
||||
(match form
|
||||
((? vector?) (walk-initializer (vector->list form)))
|
||||
|
||||
301
infer.scm
301
infer.scm
@@ -1,8 +1,8 @@
|
||||
;;; Type inference, layer 0: the type representation and unification.
|
||||
;;;
|
||||
;;; semen solves the wildcards of a declared type with it -- `(var n _
|
||||
;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand
|
||||
;;; decays or promotes to.
|
||||
;;; Nothing in the compiler calls this unit yet. It is the ground floor
|
||||
;;; of the pass described in Type-inference.org -- built and tested on
|
||||
;;; its own before a single form is routed through it.
|
||||
;;;
|
||||
;;; Two representations meet here. *Surface* types are the forms the
|
||||
;;; rest of the compiler passes around -- `int', `(* const char)',
|
||||
@@ -28,18 +28,32 @@
|
||||
(chicken module)
|
||||
matchable
|
||||
srfi-1
|
||||
srfi-69
|
||||
types
|
||||
utils)
|
||||
|
||||
(export
|
||||
;; The IR
|
||||
tvar?
|
||||
prim-type? prim-name
|
||||
ptr-type?
|
||||
array-type? array-elt
|
||||
tvar-id
|
||||
tvar-classes
|
||||
tvar-rigid?
|
||||
fresh-tvar
|
||||
fresh-rigid-tvar
|
||||
|
||||
prim-type? prim-name prim-quals make-prim
|
||||
ptr-type? ptr-target ptr-quals make-ptr
|
||||
array-type? array-elt array-size make-array-type
|
||||
fn-type? fn-ret fn-args fn-variadic? make-fn-type
|
||||
agg-type? agg-kind agg-name agg-spelling agg-quals make-agg
|
||||
alias-type? alias-name alias-expansion alias-quals make-alias
|
||||
unknown-type? the-unknown-type
|
||||
|
||||
resolve
|
||||
underlying
|
||||
c-primitive?
|
||||
type-quals
|
||||
free-tvars
|
||||
decay
|
||||
unqualified
|
||||
|
||||
@@ -47,7 +61,22 @@
|
||||
parse-type
|
||||
unparse-type
|
||||
|
||||
unify)
|
||||
;; Constraints
|
||||
register-class!
|
||||
add-instance!
|
||||
entails?
|
||||
default-tvar!
|
||||
default-type-variables!
|
||||
|
||||
;; Unification
|
||||
unify
|
||||
|
||||
;; Type schemes
|
||||
scheme? scheme-vars scheme-constraints scheme-type
|
||||
make-scheme
|
||||
generalize
|
||||
instantiate
|
||||
substitute)
|
||||
|
||||
;;; ---------------------------------------------------------------
|
||||
;;; The IR
|
||||
@@ -55,19 +84,29 @@
|
||||
|
||||
;;; A type variable is a mutable cell. `ref' is #f while unsolved and
|
||||
;;; the type it stands for once bound -- union-find, with the path
|
||||
;;; compression done in `resolve'. `quals' are the ones written on it --
|
||||
;;; compression done in `resolve'.
|
||||
;;;
|
||||
;;; `classes' is the list of type classes the variable must satisfy
|
||||
;;; (`numeric', and one day `ord'); see "constraints" below. `rigid?'
|
||||
;;; marks a variable that must not unify with anything but itself --
|
||||
;;; unused until a `fn' grows type parameters, and five lines now
|
||||
;;; against an IR change later. `quals' are the ones written on it --
|
||||
;;; `(const _)' -- and go onto whatever it is bound to.
|
||||
(define-record-type <tvar>
|
||||
(%make-tvar ref quals)
|
||||
(%make-tvar id ref classes rigid? quals)
|
||||
tvar?
|
||||
(id tvar-id)
|
||||
(ref tvar-ref tvar-ref-set!)
|
||||
(classes tvar-classes tvar-classes-set!)
|
||||
(rigid? tvar-rigid?)
|
||||
(quals tvar-quals tvar-quals-set!))
|
||||
|
||||
;;; A primitive or otherwise nominal type. `name' is the list of words
|
||||
;;; making it up, so `int', `(unsigned int)' and `(long long)' are all
|
||||
;;; one node, and so is a name we have never parsed a declaration for
|
||||
;;; (`size-t', `GLuint'). The two cases are told apart by
|
||||
;;; `c-primitive?'.
|
||||
;;; `c-primitive?', which is what keeps a constraint over an unparsed C
|
||||
;;; typedef from being an error.
|
||||
(define-record-type <prim>
|
||||
(make-prim name quals)
|
||||
prim-type?
|
||||
@@ -118,8 +157,25 @@
|
||||
(expansion alias-expansion)
|
||||
(quals alias-quals))
|
||||
|
||||
(define (fresh-tvar)
|
||||
(%make-tvar #f (list)))
|
||||
;;; `?'. Sex has full C interop, so `printf', `SDL-CreateWindow' and
|
||||
;;; `size-t' arrive from headers nobody parsed. Rather than reject
|
||||
;;; every real program, the lattice gets a top element: `?' is
|
||||
;;; consistent with every type and constrains nothing.
|
||||
(define-record-type <unknown>
|
||||
(%make-unknown)
|
||||
unknown-type?)
|
||||
|
||||
(define the-unknown-type (%make-unknown))
|
||||
|
||||
(define tvar-counter 0)
|
||||
|
||||
(define (fresh-tvar . classes)
|
||||
(set! tvar-counter (+ tvar-counter 1))
|
||||
(%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #f (list)))
|
||||
|
||||
(define (fresh-rigid-tvar . classes)
|
||||
(set! tvar-counter (+ tvar-counter 1))
|
||||
(%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #t (list)))
|
||||
|
||||
;;; Follow a bound variable to what it stands for, compressing the path
|
||||
;;; on the way out. Every procedure that looks at a type's shape starts
|
||||
@@ -165,6 +221,16 @@
|
||||
((alias-type? t) (make-alias (alias-name t) (alias-expansion t) (list)))
|
||||
(else t))))
|
||||
|
||||
(define (free-tvars type)
|
||||
(let collect ((t type) (acc (list)))
|
||||
(let ((t (resolve t)))
|
||||
(cond ((tvar? t) (if (memq t acc) acc (cons t acc)))
|
||||
((ptr-type? t) (collect (ptr-target t) acc))
|
||||
((array-type? t) (collect (array-elt t) acc))
|
||||
((alias-type? t) (collect (alias-expansion t) acc))
|
||||
((fn-type? t) (fold collect (collect (fn-ret t) acc) (fn-args t)))
|
||||
(else acc)))))
|
||||
|
||||
;;; ---------------------------------------------------------------
|
||||
;;; Surface -> IR
|
||||
;;; ---------------------------------------------------------------
|
||||
@@ -307,6 +373,7 @@
|
||||
(let ((t (resolve type)))
|
||||
(cond
|
||||
((tvar? t) '_)
|
||||
((unknown-type? t) '?)
|
||||
((alias-type? t) (qualify (alias-quals t) (list (alias-name t))))
|
||||
((prim-type? t) (qualify (prim-quals t) (prim-name t)))
|
||||
((agg-type? t) (qualify (agg-quals t) (agg-spelling t)))
|
||||
@@ -346,9 +413,69 @@
|
||||
(else surface)))
|
||||
|
||||
;;; ---------------------------------------------------------------
|
||||
;;; C's own types
|
||||
;;; Constraints
|
||||
;;; ---------------------------------------------------------------
|
||||
|
||||
;;; `(numeric a)' is already a type class, so it is written as one from
|
||||
;;; the start: one representation, one table, one entailment check. A
|
||||
;;; trait bound `(ord (struct circle))' is the same shape, discharged
|
||||
;;; the same way, and reported by the same procedure -- which is the
|
||||
;;; whole reason to build it this way while there is only one kind of
|
||||
;;; constraint to build.
|
||||
;;;
|
||||
;;; `default' is the type an unresolved constraint falls back to, the
|
||||
;;; way Haskell defaults `Num a' to Integer. `test' is how the built-in
|
||||
;;; classes say "every arithmetic type" without enumerating twenty
|
||||
;;; spellings as instances; a user trait has no test and lives entirely
|
||||
;;; in the instance table. `strict?' marks a class that must not be
|
||||
;;; guessed at: static dispatch needs a real instance, so `?' fails it.
|
||||
(define-record-type <type-class>
|
||||
(%make-type-class name default test strict?)
|
||||
type-class?
|
||||
(name type-class-name)
|
||||
(default type-class-default)
|
||||
(test type-class-test)
|
||||
(strict? type-class-strict?))
|
||||
|
||||
(define +classes+ (make-hash-table))
|
||||
(define +instances+ (make-hash-table))
|
||||
|
||||
(define (register-class! name default test strict?)
|
||||
(hash-table-set! +classes+ name (%make-type-class name default test strict?)))
|
||||
|
||||
(define (get-class name)
|
||||
(or (hash-table-ref/default +classes+ name #f)
|
||||
(error "no such type class" name)))
|
||||
|
||||
;;; Instances key on the *resolved* type, so `(impl show for size-t)'
|
||||
;;; and `(impl show for unsigned long)' collide rather than quietly
|
||||
;;; coexisting as two instances of one C type.
|
||||
(define (instance-key type)
|
||||
(unparse-type (underlying type)))
|
||||
|
||||
(define (add-instance! class-name type)
|
||||
(hash-table-set! +instances+ (cons class-name (instance-key type)) #t))
|
||||
|
||||
(define (has-instance? class-name type)
|
||||
(hash-table-exists? +instances+ (cons class-name (instance-key type))))
|
||||
|
||||
;;; #t, #f, or 'unknown -- and the third answer is the important one.
|
||||
;;; A C name we never parsed a declaration for might well be numeric;
|
||||
;;; saying #f there would reject working programs, and saying #t would
|
||||
;;; invent knowledge. 'unknown means "do not constrain, do not
|
||||
;;; complain".
|
||||
(define (entails? class-name type)
|
||||
(let ((cls (get-class class-name))
|
||||
(t (underlying type)))
|
||||
(cond
|
||||
((tvar? t) 'unknown)
|
||||
;; `?' is consistent with every type, but it entails nothing:
|
||||
;; there is no instance to select and no name to mangle.
|
||||
((unknown-type? t) (if (type-class-strict? cls) #f 'unknown))
|
||||
((has-instance? class-name t) #t)
|
||||
((type-class-test cls) => (lambda (test) (test t)))
|
||||
(else #f))))
|
||||
|
||||
(define +integer-words+ '(char short int long signed unsigned bool _Bool))
|
||||
(define +float-words+ '(float double))
|
||||
(define +known-words+ (append '(void) +integer-words+ +float-words+))
|
||||
@@ -359,18 +486,97 @@
|
||||
(and (prim-type? t)
|
||||
(every (lambda (word) (memq word +known-words+)) (prim-name t))))
|
||||
|
||||
(define (void-type? t)
|
||||
(and (prim-type? t) (equal? (prim-name t) '(void))))
|
||||
|
||||
(define (arithmetic-type? t)
|
||||
(cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t) ; an enum is an integer
|
||||
((not (prim-type? t)) #f)
|
||||
((not (c-primitive? t)) 'unknown)
|
||||
((void-type? t) #f)
|
||||
(else #t)))
|
||||
|
||||
(define (integral-type? t)
|
||||
(cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t)
|
||||
((not (prim-type? t)) #f)
|
||||
((not (c-primitive? t)) 'unknown)
|
||||
((void-type? t) #f)
|
||||
((any (lambda (word) (memq word +float-words+)) (prim-name t)) #f)
|
||||
(else #t)))
|
||||
|
||||
(define (floating-type? t)
|
||||
(cond ((not (prim-type? t)) #f)
|
||||
((not (c-primitive? t)) 'unknown)
|
||||
(else (and (any (lambda (word) (memq word +float-words+)) (prim-name t))
|
||||
#t))))
|
||||
|
||||
(define (scalar-type? t)
|
||||
(cond ((ptr-type? t) #t)
|
||||
((array-type? t) #t) ; decays to one
|
||||
((fn-type? t) #t) ; likewise
|
||||
(else (arithmetic-type? t))))
|
||||
|
||||
;;; The built-ins. They are ordinary classes, registered the same way a
|
||||
;;; trait will be -- that is the point.
|
||||
(register-class! 'numeric 'int arithmetic-type? #f)
|
||||
(register-class! 'integral 'int integral-type? #f)
|
||||
(register-class! 'floating 'double floating-type? #f)
|
||||
(register-class! 'scalar #f scalar-type? #f)
|
||||
|
||||
;;; A constraint that survives to the end of a function is defaulted:
|
||||
;;; `(numeric a)' with nothing else known is an `int'. A *strict*
|
||||
;;; class has no default and no business guessing, so an unresolved one
|
||||
;;; is an error -- the rule is worth stating while there is only one
|
||||
;;; kind of constraint to state it about.
|
||||
(define (default-tvar! v form)
|
||||
(let ((strict (find (lambda (c) (type-class-strict? (get-class c)))
|
||||
(tvar-classes v))))
|
||||
(cond
|
||||
(strict (sex-error form "unresolved constraint" (list strict (unparse-type v))))
|
||||
((find (lambda (c) (type-class-default (get-class c))) (tvar-classes v))
|
||||
=> (lambda (c)
|
||||
(tvar-ref-set! v (parse-type (type-class-default (get-class c))))
|
||||
#t))
|
||||
(else #f))))
|
||||
|
||||
;;; Default every variable still open in TYPE. Returns #t when none is
|
||||
;;; left unsolved, so a caller can tell "inferred" from "give up and
|
||||
;;; ask for the type in writing".
|
||||
(define (default-type-variables! type form)
|
||||
(fold (lambda (v ok) (and (default-tvar! v form) ok))
|
||||
#t
|
||||
(free-tvars type)))
|
||||
|
||||
(define (check-classes classes type form)
|
||||
(for-each
|
||||
(lambda (c)
|
||||
(when (eq? #f (entails? c type))
|
||||
(sex-error form "type does not satisfy a constraint"
|
||||
(list c (unparse-type type)))))
|
||||
classes))
|
||||
|
||||
;;; ---------------------------------------------------------------
|
||||
;;; Unification
|
||||
;;; ---------------------------------------------------------------
|
||||
|
||||
;;; Consistency in the gradual-typing sense rather than equality: `?'
|
||||
;;; succeeds against anything and binds nothing, which is what keeps
|
||||
;;; the pass from rejecting every program that includes a C header.
|
||||
;;;
|
||||
;;; FORM is carried only so a failure can say where it was written.
|
||||
(define (unify t1 t2 form)
|
||||
(let ((a (resolve t1))
|
||||
(b (resolve t2)))
|
||||
(cond
|
||||
((eq? a b) #t)
|
||||
((tvar? a) (bind-tvar! a b form))
|
||||
((tvar? b) (bind-tvar! b a form))
|
||||
((unknown-type? a) #t)
|
||||
((unknown-type? b) #t)
|
||||
;; Whichever side is free takes the binding: `(unify a r)' and
|
||||
;; `(unify r a)' both leave `a' bound to `r'. Two rigid and
|
||||
;; distinct is the mismatch `eq?' above let through.
|
||||
((and (tvar? a) (not (tvar-rigid? a))) (bind-tvar! a b form))
|
||||
((and (tvar? b) (not (tvar-rigid? b))) (bind-tvar! b a form))
|
||||
((or (tvar? a) (tvar? b)) (type-mismatch a b form))
|
||||
;; A typedef unifies as what it stands for. Its name survives in
|
||||
;; whichever side is printed later, since neither side is rebuilt.
|
||||
((alias-type? a) (unify (alias-expansion a) b form))
|
||||
@@ -424,7 +630,16 @@
|
||||
;; Without recursive types this cannot trigger. It is four lines,
|
||||
;; and the alternative to having it is a hang.
|
||||
((occurs? v t) (sex-error form "recursive type" (unparse-type v)))
|
||||
(else (tvar-ref-set! v (with-quals t (tvar-quals v))) #t)))
|
||||
;; A rigid variable is a type *parameter*: inside a generic body it
|
||||
;; stands for one specific unknown type and must not be solved.
|
||||
((tvar-rigid? v) (type-mismatch v t form))
|
||||
(else
|
||||
(when (tvar? t)
|
||||
(tvar-classes-set! t (lset-union eq? (tvar-classes t) (tvar-classes v))))
|
||||
(tvar-ref-set! v (with-quals t (tvar-quals v)))
|
||||
(unless (tvar? t)
|
||||
(check-classes (tvar-classes v) t form))
|
||||
#t)))
|
||||
|
||||
(define (occurs? v type)
|
||||
(let ((t (resolve type)))
|
||||
@@ -435,3 +650,57 @@
|
||||
((fn-type? t) (or (occurs? v (fn-ret t))
|
||||
(any (lambda (a) (occurs? v a)) (fn-args t))))
|
||||
(else #f))))
|
||||
|
||||
;;; ---------------------------------------------------------------
|
||||
;;; Type schemes
|
||||
;;; ---------------------------------------------------------------
|
||||
|
||||
;;; Nothing generalizes yet -- every `fn' in Sex carries a written
|
||||
;;; signature and there is no polymorphism to abstract over. These are
|
||||
;;; here because they are ten lines on top of unification and because
|
||||
;;; they are exactly what a `fn' with type parameters needs, and
|
||||
;;; because a scheme without a constraint list is the wrong shape for
|
||||
;;; every bounded generic. `(forall vars constraints type)' it is,
|
||||
;;; from the start.
|
||||
(define-record-type <scheme>
|
||||
(make-scheme vars constraints type)
|
||||
scheme?
|
||||
(vars scheme-vars)
|
||||
(constraints scheme-constraints)
|
||||
(type scheme-type))
|
||||
|
||||
;;; Quantify over everything free in TYPE that is not also free in the
|
||||
;;; environment, carrying each variable's class constraints along as
|
||||
;;; the scheme's context.
|
||||
(define (generalize type env-tvars)
|
||||
(let ((vars (lset-difference eq? (free-tvars type) env-tvars)))
|
||||
(make-scheme vars
|
||||
(append-map (lambda (v)
|
||||
(map (lambda (c) (cons c v)) (tvar-classes v)))
|
||||
vars)
|
||||
type)))
|
||||
|
||||
(define (instantiate scheme)
|
||||
(let ((subst (map (lambda (v) (cons v (fresh-tvar (tvar-classes v))))
|
||||
(scheme-vars scheme))))
|
||||
(substitute (scheme-type scheme) subst)))
|
||||
|
||||
;;; Structural copy with the variables in SUBST replaced. Copying is
|
||||
;;; how a generic body must be handled anyway -- `form-type' is keyed
|
||||
;;; by cons cell, one form one type, so an instantiation gets fresh
|
||||
;;; cells rather than a second type for the same cell.
|
||||
(define (substitute type subst)
|
||||
(let ((t (resolve type)))
|
||||
(cond
|
||||
((tvar? t) (let ((hit (assq t subst))) (if hit (cdr hit) t)))
|
||||
((ptr-type? t) (make-ptr (substitute (ptr-target t) subst) (ptr-quals t)))
|
||||
((array-type? t) (make-array-type (substitute (array-elt t) subst)
|
||||
(array-size t)))
|
||||
((alias-type? t) (make-alias (alias-name t)
|
||||
(substitute (alias-expansion t) subst)
|
||||
(alias-quals t)))
|
||||
((fn-type? t) (make-fn-type (substitute (fn-ret t) subst)
|
||||
(map (lambda (a) (substitute a subst))
|
||||
(fn-args t))
|
||||
(fn-variadic? t)))
|
||||
(else t))))
|
||||
|
||||
10
reader.scm
10
reader.scm
@@ -34,7 +34,10 @@
|
||||
|
||||
number-literal?
|
||||
number-literal-value
|
||||
number-literal-suffix)
|
||||
number-literal-suffix
|
||||
|
||||
;; for the tests
|
||||
parse-all)
|
||||
|
||||
;;; Sentinels for structural tokens
|
||||
(define close-paren (list '%close-paren))
|
||||
@@ -234,9 +237,7 @@
|
||||
;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400,
|
||||
;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide
|
||||
;;; for long long is unsigned to C, which says so only by a warning
|
||||
;;; unless it is written with a `u'; so it is. -9223372036854775808 is
|
||||
;;; one too: C negates the unsigned 9223372036854775808, so it is
|
||||
;;; spelled as LLONG_MIN is, -9223372036854775807 - 1.
|
||||
;;; unless it is written with a `u'; so it is.
|
||||
(define +llong-min+ (- (expt 2 63)))
|
||||
(define +llong-max+ (- (expt 2 63) 1))
|
||||
(define +ullong-max+ (- (expt 2 64) 1))
|
||||
@@ -247,7 +248,6 @@
|
||||
(error "too large for any C integer type" s))
|
||||
((> n +llong-max+) (make-number-literal n "u" #f))
|
||||
((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f)))
|
||||
((= n +llong-min+) (list '- (+ n 1) 1))
|
||||
(else n)))
|
||||
((and (real? n) (inexact? n) (finite? n)) n)
|
||||
(else (error "C has no literal for this number" s))))
|
||||
|
||||
741
semen.scm
741
semen.scm
@@ -20,6 +20,11 @@
|
||||
)
|
||||
|
||||
(export/rename (process semen-process))
|
||||
(export closure-env-declaration
|
||||
;; for the tests
|
||||
sex-fn? sex-fn-public? sex-fn-name sex-fn-arglist
|
||||
sex-fn-return-type sex-fn-prototype sex-fn-body
|
||||
walk-form macro-expand)
|
||||
|
||||
;;; for lambda extraction, docstring processing, macro expansion,
|
||||
;;; injection of module headers, i.e. all things that rearrange code
|
||||
@@ -55,10 +60,13 @@
|
||||
(macroexpand (car forms) (cdr forms))
|
||||
acc))
|
||||
(else
|
||||
;; `struct ƛint_int' has to be declared before the function whose
|
||||
;; signature first mentioned it, so the forms that function produced
|
||||
;; are lifted off and the structs slid underneath them
|
||||
(let* ((processed (match-sex-form (car forms) acc))
|
||||
(new (take-until processed acc)))
|
||||
(process-rec (cdr forms)
|
||||
(append new acc))))))
|
||||
(append new (flush-closure-structs!) acc))))))
|
||||
|
||||
(define (take-until forms tail)
|
||||
(if (eq? forms tail)
|
||||
@@ -100,6 +108,10 @@
|
||||
((or ('fn . _)
|
||||
('pub 'fn . _)
|
||||
('extern 'fn . _)) (process-fn sex-form acc))
|
||||
((or ('spec . _)
|
||||
('pub 'spec . _)) (process-spec sex-form acc))
|
||||
((or ('realize . _)
|
||||
('pub 'realize . _)) (process-realize sex-form acc))
|
||||
(('ops . _) (process-ops sex-form acc))
|
||||
(('pub 'ops . _)
|
||||
(sex-error sex-form "pub belongs on the methods, not on ops" sex-form))
|
||||
@@ -117,7 +129,8 @@
|
||||
('pub 'var . _)
|
||||
('extern 'var . _)) (process-global-var sex-form acc))
|
||||
;; `pub' on either of these is what read-public-interface already
|
||||
;; accepts: a module may export what its interface needs
|
||||
;; accepts, and a module whose spec defaults call printf has to be
|
||||
;; able to say so
|
||||
((or ('include . includes)
|
||||
('pub 'include . includes)) (process-includes sex-form includes acc))
|
||||
((or ('define name . _)
|
||||
@@ -299,7 +312,7 @@
|
||||
(add-name-type! (sex-fn-name expanded) (fn-type-of expanded))
|
||||
(let* ((env (make-fn-env expanded))
|
||||
;; the parameters are the body's outermost scope
|
||||
(header (take expanded boundary))
|
||||
(header (map resolve-closure-types (take expanded boundary)))
|
||||
(body (parameterize ((operand-position? #f))
|
||||
(walk-body (drop expanded boundary) env)))
|
||||
;; A function is header and body stitched together, so the
|
||||
@@ -310,6 +323,141 @@
|
||||
(with-docstring doc processed
|
||||
(append (hash-table-ref env :lambda-aux-code) acc))))))
|
||||
|
||||
;;; (spec (printable T) (fn show ((self (* const T))) void))
|
||||
;;;
|
||||
;;; declares a contract and emits nothing: a spec method only exists
|
||||
;;; once some type realizes it, and then once per type.
|
||||
(define (process-spec form acc)
|
||||
(let* ((core (if (eq? (car form) 'pub) (cdr form) form))
|
||||
(head (and (pair? (cdr core)) (cadr core)))
|
||||
(methods (remove comment-form? (cddr core))))
|
||||
(unless (and (list? head) (= 2 (length head))
|
||||
(symbol? (car head)) (symbol? (cadr head)))
|
||||
(sex-error form "a spec is (spec (name T) methods ...)" form))
|
||||
(let ((name (car head)))
|
||||
(when (get-spec name)
|
||||
(sex-error form "spec is already declared" name))
|
||||
(for-each (lambda (m)
|
||||
(unless (and (pair? m) (eq? (car m) 'fn)
|
||||
(pair? (cdr m)) (symbol? (second m)))
|
||||
(sex-error form "a spec takes fn forms" m)))
|
||||
methods)
|
||||
(add-spec! name (cadr head) methods)
|
||||
acc)))
|
||||
|
||||
;;; (realize (printable expr) (fn show ((self (* const expr))) void ...))
|
||||
;;;
|
||||
;;; is the spec's methods for one type: the ones written here, plus a
|
||||
;;; copy of every default the spec carries, each with the parameter
|
||||
;;; substituted and the name mangled to exprːprintableːshow. They land
|
||||
;;; in the ops registry beside inherent methods, so (.show e) finds
|
||||
;;; them and a name used twice on one type is caught either way.
|
||||
(define (process-realize form acc)
|
||||
(let* ((pub? (eq? (car form) 'pub))
|
||||
(core (if pub? (cdr form) form))
|
||||
(head (and (pair? (cdr core)) (cadr core)))
|
||||
(given (remove comment-form? (cddr core))))
|
||||
(unless (and (list? head) (= 2 (length head))
|
||||
(symbol? (car head)) (symbol? (cadr head)))
|
||||
(sex-error form "a realization is (realize (spec type) methods ...)" form))
|
||||
(let* ((name (car head))
|
||||
(type (cadr head))
|
||||
(spec (or (get-spec name)
|
||||
(sex-error form "no such spec" name))))
|
||||
(when (realizes? name type)
|
||||
(sex-error form "spec is already realized for" name type))
|
||||
(add-realization! name type)
|
||||
(let ((wanted (spec-methods spec))
|
||||
(parameter (spec-parameter spec)))
|
||||
(check-realization form name type parameter wanted given)
|
||||
;; every method is registered before any body is walked, so they
|
||||
;; may call one another in any order, as an ops block's may; one
|
||||
;; called above its definition is declared ahead of them all
|
||||
(let* ((methods (map (lambda (entry)
|
||||
(register-realized-method form name type
|
||||
(and pub? (cdr entry))
|
||||
(car entry)))
|
||||
(realization-methods type parameter wanted given)))
|
||||
(bodies (map (lambda (m) (process-fn m (list))) methods))
|
||||
(early (filter (lambda (m) (called-before? m methods bodies))
|
||||
methods)))
|
||||
(append (append-map identity (reverse bodies))
|
||||
(fold (lambda (m acc) (process-fn (sex-fn-prototype m) acc))
|
||||
acc
|
||||
early)))))))
|
||||
|
||||
;;; What is written here, which a pub realization exports, and then
|
||||
;;; every default nobody overrode, which it does not: a default is
|
||||
;;; synthesized again in every unit that imports the realization, so
|
||||
;;; exporting one too would be a second definition of one symbol.
|
||||
(define (realization-methods type parameter wanted given)
|
||||
(append (map (lambda (g) (cons g #t)) given)
|
||||
(filter-map
|
||||
(lambda (w)
|
||||
(and (spec-default? w)
|
||||
(not (find (lambda (g) (eq? (second g) (second w))) given))
|
||||
(cons (substitute-parameter parameter type w) #f)))
|
||||
wanted)))
|
||||
|
||||
;;; A docstring or a comment is not a body, so
|
||||
;;;
|
||||
;;; (fn s ((self (* const T))) void "what s is for")
|
||||
;;;
|
||||
;;; is still a method every realization has to write.
|
||||
(define (spec-default? method)
|
||||
(let-values (((doc fn) (extract-fn-docstring (strip-fn-header-comments method))))
|
||||
(any (lambda (form) (not (comment-form? form)))
|
||||
(drop fn (fn-header-length fn)))))
|
||||
|
||||
(define (check-realization form name type parameter wanted given)
|
||||
(for-each
|
||||
(lambda (g)
|
||||
(unless (and (pair? g) (eq? (car g) 'fn) (pair? (cdr g)) (symbol? (second g)))
|
||||
(sex-error form "a realization takes fn forms" g))
|
||||
(let ((w (find (lambda (w) (eq? (second w) (second g))) wanted)))
|
||||
(unless w
|
||||
(sex-error form "spec has no such method" name (second g)))
|
||||
(let ((expected (substitute-parameter parameter type w)))
|
||||
(unless (equal? (arglist-types (sex-fn-arglist expected))
|
||||
(arglist-types (sex-fn-arglist g)))
|
||||
(sex-error form "method's arguments do not match the spec" (second g)))
|
||||
(unless (equal? (sex-fn-return-type expected) (sex-fn-return-type g))
|
||||
(sex-error form "method's return type does not match the spec"
|
||||
(second g))))))
|
||||
given)
|
||||
(let ((missing (filter-map
|
||||
(lambda (w)
|
||||
(and (not (spec-default? w))
|
||||
(not (find (lambda (g) (eq? (second g) (second w))) given))
|
||||
(second w)))
|
||||
wanted)))
|
||||
(when (pair? missing)
|
||||
(apply sex-error form "realization is missing a method of" name missing))))
|
||||
|
||||
;;; A realization is public or private as a unit -- its methods do
|
||||
;;; not carry `pub' of their own, the way an ops block's do, because
|
||||
;;; the spec already says which of them there are. The method's fn
|
||||
;;; form, renamed to pointːsizedːtotal, once it is registered under
|
||||
;;; `total' and its signature known.
|
||||
(define (register-realized-method form spec type pub? method)
|
||||
(let* ((name (second method))
|
||||
(qualified (qualify-op (qualify-op type spec) name))
|
||||
(renamed (copy-form-source! form (rename-fn method qualified)))
|
||||
(fn (if pub? (copy-form-source! form (cons 'pub renamed)) renamed)))
|
||||
(when (get-method type name)
|
||||
(sex-error form "method is already defined on" type name))
|
||||
(add-method! type name qualified)
|
||||
(process-fn (sex-fn-prototype fn) (list))
|
||||
fn))
|
||||
|
||||
;;; T in a spec's method stands for whatever realizes it
|
||||
(define (substitute-parameter parameter type form)
|
||||
(cond ((eq? form parameter) type)
|
||||
((pair? form) (recons form
|
||||
(substitute-parameter parameter type (car form))
|
||||
(substitute-parameter parameter type (cdr form))))
|
||||
(else form)))
|
||||
|
||||
;;; (ops vec2
|
||||
;;; (pub fn length ((self (* const vec2))) float ...))
|
||||
;;;
|
||||
@@ -405,8 +553,8 @@
|
||||
;;; The scope chain
|
||||
;;;
|
||||
;;; `(do (var c int 9) ...)' declares a `c' that ends with the block, so
|
||||
;;; an outer `c' is in scope after it. Every form whose body C brackets
|
||||
;;; opens a frame; innermost first:
|
||||
;;; a closure-typed `c' outside it is still a closure after it. Every
|
||||
;;; form whose body C brackets opens a frame; innermost first:
|
||||
;;;
|
||||
;;; (var v double 3.75)
|
||||
;;; (while (< v 0) (var v char 1) ...)
|
||||
@@ -433,9 +581,10 @@
|
||||
|
||||
;;; The body walk
|
||||
;;;
|
||||
;;; One pass in statement order: lifts lambdas out, records what each
|
||||
;;; declaration binds, and rewrites a call whose head is a function
|
||||
;;; value.
|
||||
;;; One pass in statement order: lifts lambdas and closures out,
|
||||
;;; resolves closure types to the struct that stands for them, records
|
||||
;;; what each declaration binds, and rewrites a call whose head is a
|
||||
;;; closure.
|
||||
;;;
|
||||
;;; Not `walk-form': it has no event for leaving a scope, and it hands
|
||||
;;; the walk function every cdr-tail as well, so the `f' in `(g f)'
|
||||
@@ -506,15 +655,31 @@
|
||||
(add-aux-code! env (lift-lambda name form))
|
||||
name))
|
||||
|
||||
((closure)
|
||||
(if (closure-type? form)
|
||||
;; a type, not an expression: the struct for its signature
|
||||
(copy-form-source! form `(struct ,(register-closure-type! form form)))
|
||||
(let ((base (aux-name! env make-closure-name)))
|
||||
(let-values (((construct lifted) (lift-closure base form env)))
|
||||
(add-aux-code! env (fold match-sex-form (list) lifted))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,construct ,@(map (lambda (capture)
|
||||
(walk-operand (capture-argument capture)
|
||||
env))
|
||||
(fourth form))))))))
|
||||
|
||||
((var)
|
||||
;; the initializer is walked before the name it binds is in
|
||||
;; scope; the type is resolved rather than walked, a parameter
|
||||
;; list being shaped like a call:
|
||||
;;
|
||||
;; (var c (closure ((int)) int) ...)
|
||||
;; (var fp (fn ((c int)) int) ...) ; int (*fp)(int)
|
||||
(let* ((prefix (if (>= (length form) 3)
|
||||
(append (take form 2)
|
||||
(list (expand-type (third form) env)))
|
||||
(list (resolve-closure-types
|
||||
(expand-type (third form) env))))
|
||||
form))
|
||||
(walked (resolve-wildcard
|
||||
(copy-form-source!
|
||||
@@ -523,15 +688,29 @@
|
||||
(if (> (length form) 3)
|
||||
(walk-operands form (drop form 3) env)
|
||||
(list))))
|
||||
env)))
|
||||
(when (>= (length walked) 3)
|
||||
(declare-name! env (second walked) (third walked)))
|
||||
walked))
|
||||
env))
|
||||
(bound (if (>= (length walked) 4)
|
||||
(copy-form-source!
|
||||
walked
|
||||
(append (take walked 3)
|
||||
(cons (convert-to-closure (third walked)
|
||||
(fourth walked)
|
||||
env walked)
|
||||
(drop walked 4))))
|
||||
walked)))
|
||||
(when (>= (length bound) 3)
|
||||
(declare-name! env (second bound) (third bound)))
|
||||
bound))
|
||||
|
||||
((return)
|
||||
(let ((walked (copy-form-source! form (walk-operands form form env))))
|
||||
(if (>= (length walked) 2)
|
||||
(copy-form-source! walked (cons 'return (cdr walked)))
|
||||
(copy-form-source!
|
||||
walked
|
||||
(cons 'return
|
||||
(cons (convert-to-closure (hash-table-ref env :returns)
|
||||
(second walked) env walked)
|
||||
(cddr walked))))
|
||||
walked)))
|
||||
|
||||
((match)
|
||||
@@ -555,7 +734,8 @@
|
||||
(if (and (= 2 (length form)) (written-type? (second form) env))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(sizeof (%type ,(expand-type (second form) env))))
|
||||
`(sizeof (%type ,(resolve-closure-types
|
||||
(expand-type (second form) env)))))
|
||||
(walk-parts form env)))
|
||||
|
||||
(else
|
||||
@@ -563,11 +743,23 @@
|
||||
((method-head? (car form)) (walk-method-call form env))
|
||||
((get-constructor (car form))
|
||||
=> (lambda (constructor) (walk-construction form constructor env)))
|
||||
((receiver-closure-type (car form) env)
|
||||
=> (lambda (closure)
|
||||
;; the receiver is walked first: `((closure ((x int))
|
||||
;; int () ...) 5)' registers `struct ƛint_int' on the
|
||||
;; way, and the call helper's signature names it
|
||||
(let ((receiver (walk-operand (car form) env)))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(,(register-closure-call! closure form)
|
||||
,receiver
|
||||
,@(walk-operands form (cdr form) env))))))
|
||||
(else
|
||||
(when (and (symbol? (car form)) (form-source form)
|
||||
(not (hash-table-exists? +called-as-functions+ (car form))))
|
||||
(hash-table-set! +called-as-functions+ (car form) form))
|
||||
(copy-form-source! form (walk-operands form form env)))))))))
|
||||
(convert-arguments (copy-form-source! form (walk-operands form form env))
|
||||
env))))))))
|
||||
|
||||
;;; How many operands each of these takes, and how it is written: one
|
||||
;;; with any other number died in the writer, in CHICKEN's words about a
|
||||
@@ -620,7 +812,7 @@
|
||||
(define (field-argument field arg env form)
|
||||
(let ((type (second field)))
|
||||
(if (not (array-form? type))
|
||||
arg
|
||||
(convert-to-closure type arg env form)
|
||||
(let ((given (expression-type arg env)))
|
||||
(cond
|
||||
((brace-initializer? arg)
|
||||
@@ -668,7 +860,7 @@
|
||||
(define (expand-call form env)
|
||||
(parameterize ((current-type-of
|
||||
(lambda (queried)
|
||||
(expression-type queried env))))
|
||||
(unresolve-closure-types (expression-type queried env)))))
|
||||
(macroexpand form (list))))
|
||||
|
||||
;;; #(struct point : (. p x) 2) -- the values are expressions, and the
|
||||
@@ -739,15 +931,16 @@
|
||||
(let ((type (expression-type written env)))
|
||||
(when type
|
||||
(unify element
|
||||
(parse-type type)
|
||||
(parse-type (resolve-closure-types type))
|
||||
form))))
|
||||
(vector->list initializer))))
|
||||
(else
|
||||
(let ((type (expression-type initializer env)))
|
||||
(unless type
|
||||
(sex-error form "cannot infer the type of" (second form)))
|
||||
;; a type is what `parse-type' knows
|
||||
(let ((given (parse-type type)))
|
||||
;; `(closure ((int)) int)' is spelled `(struct ƛint_int)'
|
||||
;; everywhere past this point, and is what `parse-type' knows
|
||||
(let ((given (parse-type (resolve-closure-types type))))
|
||||
;; an array as a value is a pointer to its first element, which
|
||||
;; is what a `_' standing alone takes; `[_ 3]' asks for an array
|
||||
(unify declared
|
||||
@@ -771,8 +964,34 @@
|
||||
((vector? form) (mentions? (vector->list form) word))
|
||||
(else #f)))
|
||||
|
||||
;;; What a `fn' header gets, a `var' type gets -- macro expansion, no
|
||||
;;; walk:
|
||||
;;; `(each xs compare)' where `each' takes a closure: the argument is
|
||||
;;; checked against the parameter that signature wrote.
|
||||
(define (convert-arguments form env)
|
||||
(let ((signature (and (symbol? (car form)) (get-name-type (car form)))))
|
||||
(if (and (list? signature) (= 3 (length signature)) (eq? 'fn (car signature)))
|
||||
(copy-form-source!
|
||||
form
|
||||
(cons (car form)
|
||||
(map (lambda (argument expected)
|
||||
(if expected
|
||||
(convert-to-closure expected argument env form)
|
||||
argument))
|
||||
(cdr form)
|
||||
(parameter-types signature (length (cdr form))))))
|
||||
form)))
|
||||
|
||||
;;; One per argument, #f past the end of the parameter list -- a
|
||||
;;; variadic tail has nothing written to check against
|
||||
(define (parameter-types signature count)
|
||||
(let pair ((params (second signature)) (remaining count) (acc (list)))
|
||||
(cond
|
||||
((zero? remaining) (reverse acc))
|
||||
((null? params) (pair params (- remaining 1) (cons #f acc)))
|
||||
(else (pair (cdr params) (- remaining 1)
|
||||
(cons (unwrap-type (car params)) acc))))))
|
||||
|
||||
;;; What a `fn' header gets, a `var' type gets -- macro expansion and
|
||||
;;; closure resolution, no walk:
|
||||
;;;
|
||||
;;; (defmacro (ty) 'int) (var x (ty) 0) -> int x = 0;
|
||||
;;;
|
||||
@@ -781,7 +1000,8 @@
|
||||
(let ((expanded
|
||||
(parameterize ((current-type-of
|
||||
(lambda (queried)
|
||||
(expression-type queried env))))
|
||||
(unresolve-closure-types
|
||||
(expression-type queried env)))))
|
||||
(macro-expand (list type)))))
|
||||
(if (and (pair? expanded) (null? (cdr expanded)))
|
||||
(car expanded)
|
||||
@@ -860,7 +1080,7 @@
|
||||
arms))
|
||||
|
||||
(define (make-match-name fn-name counter)
|
||||
(string->symbol (string-append "λm" (number->string counter))))
|
||||
(string->symbol (string-append "ƛm" (number->string counter))))
|
||||
|
||||
;;; A path of names reads the same however often it is written; a call
|
||||
;;; in there does not
|
||||
@@ -1096,12 +1316,23 @@
|
||||
(and (pair? type) (eq? 'const (car type))))
|
||||
|
||||
|
||||
(define (as-closure-type type)
|
||||
(cond
|
||||
((closure-type? type) type)
|
||||
((and (list? type) (= 2 (length type)) (eq? 'struct (car type)))
|
||||
(hash-table-ref/default +closure-structs+ (second type) #f))
|
||||
(else #f)))
|
||||
|
||||
(define (receiver-closure-type expr env)
|
||||
(as-closure-type (expression-type expr env)))
|
||||
|
||||
;;; The type of an lvalue path, from known declarations -- a name, and
|
||||
;;; what can be reached from one by subscripting, dereferencing and
|
||||
;;; member access.
|
||||
|
||||
;;; The type of an expression as a surface type, or #f when nothing
|
||||
;;; here can say.
|
||||
;;; here can say. Every form it visits is recorded in `form-type', so
|
||||
;;; asking once types the whole subtree.
|
||||
;;;
|
||||
;;; 42 -> int (. p x) -> that field's type
|
||||
;;; "hi" -> (* const char) (& p) -> (* (struct point))
|
||||
@@ -1132,6 +1363,9 @@
|
||||
(and rank (first rank)))))
|
||||
|
||||
(define (expression-type expr env)
|
||||
(set-form-type! expr (compute-expression-type expr env)))
|
||||
|
||||
(define (compute-expression-type expr env)
|
||||
(cond
|
||||
((number-literal? expr) (number-literal-type expr))
|
||||
((and (number? expr) (exact? expr)) (integer-literal-type expr '()))
|
||||
@@ -1182,6 +1416,10 @@
|
||||
(cddr expr)))
|
||||
((cast) (and (= 3 (length expr)) (third expr)))
|
||||
((sizeof) 'size-t)
|
||||
;; `(closure ((x int)) int () ...)' is a `(closure ((int)) int)',
|
||||
;; so `((closure ((x int)) int () (return x)) 5)' is a call
|
||||
((closure) (and (closure-expression? expr)
|
||||
`(closure ,(arglist-types (second expr)) ,(third expr))))
|
||||
;; `c-and' and `c-or' are the names from before `&&' and `||'
|
||||
((== != < > <= >= && |\|\|| ! c-and c-or) 'bool)
|
||||
;; one pointer from another is how far apart they are
|
||||
@@ -1209,10 +1447,12 @@
|
||||
;; (++ c), c : char -> char
|
||||
((++ --) (expression-type (second expr) env))
|
||||
;; otherwise a call: a method answers for the name it resolves
|
||||
;; to, anything else with what its signature says
|
||||
;; to, a closure with its own return type, anything else with
|
||||
;; what its signature says
|
||||
(else
|
||||
(cond
|
||||
((method-head? (car expr)) (method-call-type expr env))
|
||||
((receiver-closure-type (car expr) env) => third)
|
||||
;; a function's name, unless a local hides it
|
||||
((and (symbol? (car expr))
|
||||
(not (lookup-name env (car expr)))
|
||||
@@ -1413,31 +1653,450 @@
|
||||
(list)))
|
||||
(else (sex-error form "malformed lambda" form))))
|
||||
|
||||
;;; Closures
|
||||
;;;
|
||||
;;; A closure is a function pointer and an inline environment, so the
|
||||
;;; value owns its captures and nothing is allocated. The type
|
||||
;;; `(closure ((int)) int)' becomes one struct per signature, shared by
|
||||
;;; every closure with that signature. The captures live in `env' as a record
|
||||
;;; only the lifted body knows the shape of, which is why `env' is
|
||||
;;; max_align_t rather than char -- it has to be aligned for whatever
|
||||
;;; ends up in it.
|
||||
;;;
|
||||
;;; The expression becomes three hoisted definitions -- the capture
|
||||
;;; struct, the lifted body, and a constructor -- and is replaced by a
|
||||
;;; call to the constructor, so the captures are evaluated as ordinary
|
||||
;;; arguments at the point the closure is written.
|
||||
|
||||
;;; How much of a closure is environment, in bytes. Counted in bytes
|
||||
;;; so a closure that fits where it was written will also fit
|
||||
;;; elsewhere. Captures are only by value, and never allocated on
|
||||
;;; heap. Anything that is more than 16 bytes should be stored as a
|
||||
;;; pointer, and memory management is entirely up to caller
|
||||
|
||||
(define +closure-env-bytes+ 16)
|
||||
|
||||
;;; +closure-env-bytes+ for capacity, max_align_t for alignment, hence
|
||||
;;; union -- a union takes the strictest alignment of its members.
|
||||
(define +closure-env-type+ 'ƛenv)
|
||||
|
||||
(define (closure-env-declaration)
|
||||
`(union ,+closure-env-type+ ((align max-align-t)
|
||||
(bytes (¤ char ,+closure-env-bytes+)))))
|
||||
|
||||
(define +closure-structs+ (make-hash-table))
|
||||
(define +closure-forwards+ (make-hash-table))
|
||||
(define *pending-closure-structs* (list))
|
||||
|
||||
(define (closure-expression? form)
|
||||
(and (list? form)
|
||||
(pair? form)
|
||||
(eq? 'closure (car form))
|
||||
(>= (length form) 4)))
|
||||
|
||||
(define (closure-type? form)
|
||||
(and (pair? form)
|
||||
(eq? 'closure (car form))
|
||||
(= 3 (length form))))
|
||||
|
||||
;;; A type spelling becomes an identifier deterministically, so two
|
||||
;;; translation units have the same signatures for the same closure
|
||||
;;; types: (* const char) -> p_const_char, (closure ((int)) int) ->
|
||||
;;; closure_int_int.
|
||||
(define (mangle-type type)
|
||||
(cond
|
||||
((symbol? type) (mangle-word (symbol->string type)))
|
||||
((number? type) (number->string type))
|
||||
((null? type) "void")
|
||||
((pair? type) (string-intersperse (map mangle-type (mangle-head type)) "_"))
|
||||
(else (sex-error type "cannot mangle type" type))))
|
||||
|
||||
(define (mangle-head type)
|
||||
(case (car type)
|
||||
((*) (cons 'p (cdr type)))
|
||||
((¤) (cons 'a (cdr type)))
|
||||
(else type)))
|
||||
|
||||
(define (mangle-word word)
|
||||
(list->string
|
||||
(map (lambda (c)
|
||||
(if (or (char-alphabetic? c) (char-numeric? c)) c #\_))
|
||||
(string->list word))))
|
||||
|
||||
(define (aggregates-in type)
|
||||
(cond
|
||||
((not (list? type)) (list))
|
||||
((and (= 2 (length type))
|
||||
(memq (car type) '(struct union))
|
||||
(symbol? (second type)))
|
||||
(list type))
|
||||
(else (append-map aggregates-in type))))
|
||||
|
||||
;;; Extract aggregate types from the closure's signature to forward
|
||||
;;; declare them before the closure, so they can be referenced in the
|
||||
;;; closure. Particularly useful for complex cases like fixed point
|
||||
;;; combinator, etc.
|
||||
(define (forward-declare-aggregates! type src-form)
|
||||
(for-each
|
||||
(lambda (aggregate)
|
||||
(let ((name (second aggregate)))
|
||||
(unless (or (hash-table-exists? +closure-forwards+ name)
|
||||
(get-tag-info name))
|
||||
(hash-table-set! +closure-forwards+ name #t)
|
||||
(set! *pending-closure-structs*
|
||||
(cons (copy-form-source! src-form aggregate)
|
||||
*pending-closure-structs*)))))
|
||||
(delete-duplicates (aggregates-in type))))
|
||||
|
||||
;;; The words inside an argument take the single separator, the
|
||||
;;; arguments a doubled one:
|
||||
;;;
|
||||
;;; (closure ((long long)) int) -> ƛlong_long_int
|
||||
;;; (closure ((long) (long)) int) -> ƛlong__long_int
|
||||
;;;
|
||||
;;; A word whose first character mangles to `_' still aliases the
|
||||
;;; doubled separator: `((a -b))' and `((a) (b))' are both `a__b'.
|
||||
(define (mangle-arglist args)
|
||||
(if (null? args)
|
||||
"void"
|
||||
(string-intersperse (map mangle-type args) "__")))
|
||||
|
||||
(define (closure-struct-name type)
|
||||
;; the glyph says `closure' already, so the tag is just the signature
|
||||
(string->symbol (string-append "ƛ"
|
||||
(mangle-arglist (second type))
|
||||
"_"
|
||||
(mangle-type (third type)))))
|
||||
|
||||
;;; The code pointer takes the environment first; everything else is
|
||||
;;; the closure's own signature.
|
||||
(define (closure-code-type type)
|
||||
(let ((type (signature-resolved type)))
|
||||
`(fn (((* void)) ,@(second type)) ,(third type))))
|
||||
|
||||
;;; TYPE with the closure types of its signature made their structs: the
|
||||
;;; code generated for it goes out as it is, and C has no `closure'.
|
||||
;;;
|
||||
;;; (closure ((int)) (closure ((int)) int))
|
||||
;;; -> (closure ((int)) (struct ƛint_int))
|
||||
(define (signature-resolved type)
|
||||
`(closure ,(map resolve-closure-types (second type))
|
||||
,(resolve-closure-types (third type))))
|
||||
|
||||
;;; Emitted once per signature, before the toplevel form that first
|
||||
;;; needed it.
|
||||
(define (register-closure-type! type src-form)
|
||||
(let ((name (closure-struct-name type)))
|
||||
(unless (hash-table-exists? +closure-structs+ name)
|
||||
(forward-declare-aggregates! type src-form)
|
||||
(hash-table-set! +closure-structs+ name type)
|
||||
(let ((form (copy-form-source!
|
||||
src-form
|
||||
`(struct ,name ((code ,(closure-code-type type))
|
||||
(env (union ,+closure-env-type+)))))))
|
||||
(register-aggregate! form)
|
||||
(set! *pending-closure-structs*
|
||||
(cons form *pending-closure-structs*))))
|
||||
name))
|
||||
|
||||
;;; Every closure type in FORM becomes the struct for its signature,
|
||||
;;; registering it on the way. The walker does this for function bodies
|
||||
;;; and headers; globals come through here instead.
|
||||
;;; The inverse of `resolve-closure-types', for what a macro is shown:
|
||||
;;; `(struct ƛint_int)' is a generated name, and `(closure ((int)) int)'
|
||||
;;; is what was written and what a `type-match' pattern says.
|
||||
(define (unresolve-closure-types type)
|
||||
(or (as-closure-type type)
|
||||
(if (list? type)
|
||||
(map unresolve-closure-types type)
|
||||
type)))
|
||||
|
||||
(define (resolve-closure-types form)
|
||||
(cond
|
||||
;; `(closure args ret captures . body)' is an expression, and one is
|
||||
;; lifted into the function it was written in. At toplevel, or in a
|
||||
;; struct field, there is none
|
||||
((closure-expression? form)
|
||||
(sex-error form "a closure can only be written inside a function" form))
|
||||
((closure-type? form)
|
||||
(copy-form-source! form `(struct ,(register-closure-type! form form))))
|
||||
((list? form)
|
||||
(copy-form-source! form (map resolve-closure-types form)))
|
||||
(else form)))
|
||||
|
||||
(define +closure-conversions+ (make-hash-table))
|
||||
|
||||
;;; `(var c (closure ((int)) int) sum)' becomes `ƛint_int_fromfn(sum)'.
|
||||
;;; The function pointer goes in the environment and a thunk reads it
|
||||
;;; back out, so one thunk serves every function of that signature:
|
||||
;;;
|
||||
;;; struct ƛint_int_fnptr { int (*f)(int); };
|
||||
;;; static int ƛint_int_fnthunk (void *ƛe, int ƛa0) {
|
||||
;;; struct ƛint_int_fnptr *ƛcaptures = ƛe;
|
||||
;;; return ƛcaptures->f(ƛa0);
|
||||
;;; }
|
||||
(define (register-fn-conversion! type src-form)
|
||||
(let* ((closure (closure-struct-name type))
|
||||
(type (signature-resolved type))
|
||||
(convert (suffixed closure "_fromfn"))
|
||||
(record (suffixed closure "_fnptr"))
|
||||
(thunk (suffixed closure "_fnthunk"))
|
||||
(returns (third type))
|
||||
(pointer `(fn ,(second type) ,returns))
|
||||
(params (map (lambda (argument index)
|
||||
(list (string->symbol (fmt #f "ƛa" index))
|
||||
(unwrap-type argument)))
|
||||
(second type)
|
||||
(iota (length (second type))))))
|
||||
(unless (hash-table-exists? +closure-conversions+ convert)
|
||||
(hash-table-set! +closure-conversions+ convert #t)
|
||||
(let ((call `((%-> ƛcaptures f) ,@(map first params))))
|
||||
(for-each
|
||||
(lambda (emitted)
|
||||
(set! *pending-closure-structs*
|
||||
(cons (copy-form-source! src-form emitted)
|
||||
*pending-closure-structs*)))
|
||||
(list
|
||||
`(struct ,record ((f ,pointer)))
|
||||
|
||||
`(fn ,thunk ((ƛe (* void)) ,@params) ,returns
|
||||
(var ƛcaptures (* (struct ,record)) ƛe)
|
||||
,(if (eq? 'void returns) call `(return ,call)))
|
||||
|
||||
`(fn ,convert ((f ,pointer)) (struct ,closure)
|
||||
(var ƛc (struct ,closure))
|
||||
(= (dot-access ƛc code) ,thunk)
|
||||
(var ƛcaptures (* (struct ,record))
|
||||
(cast (& (dot-access ƛc env)) (* (struct ,record))))
|
||||
(= (%-> ƛcaptures f) f)
|
||||
(return ƛc))))))
|
||||
convert))
|
||||
|
||||
;;; A bare function is a closure that captures nothing, so it converts
|
||||
;;; wherever one is expected. The reverse cannot: a closure has an
|
||||
;;; environment and a function pointer has nowhere to put it.
|
||||
(define (convert-to-closure expected value env form)
|
||||
(let ((closure (as-closure-type expected))
|
||||
(actual (expression-type value env)))
|
||||
(if (and closure
|
||||
(list? actual)
|
||||
(= 3 (length actual))
|
||||
(eq? 'fn (car actual))
|
||||
(equal? (cdr actual) (cdr closure)))
|
||||
(copy-form-source! form
|
||||
(list (register-fn-conversion! closure form) value))
|
||||
value)))
|
||||
|
||||
(define +closure-calls+ (make-hash-table))
|
||||
|
||||
;;; The helper a closure call is routed through: `(f 1)' becomes
|
||||
;;; `ƛint_int_call(f, 1)', which unpacks the receiver into
|
||||
;;; `ƛc.code(&ƛc.env, ƛa0)' inside. The receiver arrives as an argument,
|
||||
;;; so it is evaluated once: unpacked at the call site instead,
|
||||
;;; `([table (++ i)] 10)' would read
|
||||
;;; `table[++i].code(&table[++i].env, 10)' and bump `i' twice.
|
||||
(define (register-closure-call! type src-form)
|
||||
(let* ((closure (closure-struct-name type))
|
||||
(type (signature-resolved type))
|
||||
(helper (suffixed closure "_call"))
|
||||
(returns (third type))
|
||||
(params (map (lambda (arg index)
|
||||
(list (string->symbol (fmt #f "ƛa" index))
|
||||
(unwrap-type arg)))
|
||||
(second type)
|
||||
(iota (length (second type))))))
|
||||
;; what it returns, for `_' to read: it goes out as written, and
|
||||
;; nothing else registers it
|
||||
(add-name-type! helper
|
||||
`(fn (((struct ,closure))
|
||||
,@(map (lambda (p) (list (second p))) params))
|
||||
,returns))
|
||||
(unless (hash-table-ref/default +closure-calls+ helper #f)
|
||||
(hash-table-set! +closure-calls+ helper #t)
|
||||
(let ((call `((dot-access ƛc code)
|
||||
(& (dot-access ƛc env))
|
||||
,@(map first params))))
|
||||
(set! *pending-closure-structs*
|
||||
(cons (copy-form-source!
|
||||
src-form
|
||||
`(fn ,helper ((ƛc (struct ,closure)) ,@params) ,returns
|
||||
,(if (eq? 'void returns) call `(return ,call))))
|
||||
*pending-closure-structs*))))
|
||||
helper))
|
||||
|
||||
;;; An argument type is written wrapped: `(int)' in `((int) (float))'
|
||||
(define (unwrap-type type)
|
||||
(if (and (list? type) (= 1 (length type)))
|
||||
(car type)
|
||||
type))
|
||||
|
||||
(define (flush-closure-structs!)
|
||||
(let ((pending *pending-closure-structs*))
|
||||
(set! *pending-closure-structs* (list))
|
||||
pending))
|
||||
|
||||
;;; Lowering
|
||||
|
||||
(define (make-closure-name enclosing-fn-name counter)
|
||||
(string->symbol (fmt #f "ƛ" counter "_" enclosing-fn-name)))
|
||||
|
||||
(define (suffixed name suffix)
|
||||
(string->symbol (string-append (symbol->string name) suffix)))
|
||||
|
||||
;;; `(closure ((b int)) int (n) ...)' captures `n' under its own name
|
||||
;;; and takes its type from wherever it was declared. `((pa (& a)))'
|
||||
;;; names the capture and gives the expression it holds, so `pa' is a
|
||||
;;; `(* int)' inside the body and `a' is never mentioned there.
|
||||
(define (capture-binding capture form env)
|
||||
(let ((name (capture-name capture)))
|
||||
;; ((+ a 1)) was a capture named `+' holding a
|
||||
(unless (and (symbol? name) (or (symbol? capture) (= 2 (length capture))))
|
||||
(sex-error form "a capture is a name, or (name value)" capture))
|
||||
;; the same lookup either way, so `(closure ((x int)) int (scale)
|
||||
;; ...)' borrows a global's `scale' as readily as a local's
|
||||
(let ((type (expression-type (capture-argument capture) env)))
|
||||
(unless type
|
||||
(sex-error form "cannot infer what is captured as" name))
|
||||
(list name type))))
|
||||
|
||||
(define (capture-name capture)
|
||||
(if (pair? capture) (first capture) capture))
|
||||
|
||||
;;; What the constructor is handed: the name itself, or the expression
|
||||
;;; written beside it
|
||||
(define (capture-argument capture)
|
||||
(if (pair? capture) (second capture) capture))
|
||||
|
||||
(define (lift-closure base form env)
|
||||
(match form
|
||||
(('closure arglist ret-type captures . body)
|
||||
;; its call helper would have to forward the rest, which C cannot
|
||||
(when (any (lambda (arg) (or (eq? arg '...) (equal? arg '(...)))) arglist)
|
||||
(sex-error form "a closure cannot be variadic; a lambda can"))
|
||||
(check-capture-names form arglist (map capture-name captures) body)
|
||||
(let* ((caps (map (lambda (c) (capture-binding c form env)) captures))
|
||||
(record (suffixed base "_captures"))
|
||||
(code (suffixed base "_code"))
|
||||
(construct (suffixed base "_make"))
|
||||
(type `(closure ,(arglist-types arglist) ,ret-type))
|
||||
(closure (register-closure-type! type form)))
|
||||
(values
|
||||
construct
|
||||
(map (lambda (f) (copy-form-source! form f))
|
||||
;; C has no empty struct, and a closure over nothing needs
|
||||
;; no record to point at
|
||||
(append
|
||||
(if (null? caps)
|
||||
(list)
|
||||
(list `(struct ,record ,(map capture-field caps))))
|
||||
|
||||
(list
|
||||
`(fn ,code ((ƛe (* void)) ,@(named-parameters arglist)) ,ret-type
|
||||
,@(defining
|
||||
(append
|
||||
(if (null? caps)
|
||||
(list)
|
||||
`((var ƛcaptures (* (struct ,record)) ƛe)
|
||||
,@(append-map (cut capture-local <> form) caps)))
|
||||
body)))
|
||||
|
||||
`(fn ,construct ,caps (struct ,closure)
|
||||
(var ƛc (struct ,closure))
|
||||
,@(if (null? caps)
|
||||
(list)
|
||||
`((static-assert
|
||||
(<= (sizeof (struct ,record))
|
||||
(sizeof (dot-access ƛc env)))
|
||||
"closure captures do not fit the inline environment")))
|
||||
(= (dot-access ƛc code) ,code)
|
||||
,@(if (null? caps)
|
||||
(list)
|
||||
`((var ƛcaptures (* (struct ,record))
|
||||
(cast (& (dot-access ƛc env)) (* (struct ,record))))
|
||||
,@(map (cut capture-store <> form) caps)))
|
||||
(return ƛc))))))))
|
||||
(else (sex-error form "malformed closure" form))))
|
||||
|
||||
;;; A definition names every parameter before C23, so one written as a
|
||||
;;; type alone gets a name nothing reads: ((int) (b int)) -> ((λu0 int) (b int))
|
||||
;;; type alone gets a name nothing reads: ((int) (b int)) -> ((ƛu0 int) (b int))
|
||||
(define (named-parameters arglist)
|
||||
(map (lambda (arg index)
|
||||
(if (or (named-arg? arg) (comment-form? arg)
|
||||
(eq? arg '...) (equal? arg '(...)))
|
||||
arg
|
||||
(list (string->symbol (string-append "λu" (number->string index)))
|
||||
(list (string->symbol (string-append "ƛu" (number->string index)))
|
||||
(unwrap-type arg))))
|
||||
arglist
|
||||
(iota (length arglist))))
|
||||
|
||||
;;; Captures are a closure's other parameters, and C's rule for those
|
||||
;;; holds of them: no two alike, and none redeclared at the top of the
|
||||
;;; body. A block inside may shadow one, as it may a parameter.
|
||||
(define (check-capture-names form arglist names body)
|
||||
(let ((parameters (filter-map (lambda (arg) (and (named-arg? arg) (car arg)))
|
||||
(remove comment-form? arglist))))
|
||||
(for-each (lambda (name)
|
||||
(when (memq name parameters)
|
||||
(sex-error form "a capture and a parameter share a name" name)))
|
||||
names)
|
||||
(for-each (lambda (statement)
|
||||
(match statement
|
||||
(('var (? symbol? name) . _)
|
||||
(when (memq name names)
|
||||
(sex-error statement "the body redeclares a capture" name)))
|
||||
(_ #f)))
|
||||
body)))
|
||||
|
||||
;;; A capture's field is assigned to, so it drops what qualifies the
|
||||
;;; capture itself: (const int) is held as an int, and read back into a
|
||||
;;; const one. (* const char) points at const, and is left alone.
|
||||
(define (capture-field cap)
|
||||
(let ((type (second cap)))
|
||||
(list (first cap)
|
||||
(if (and (pair? type) (memq (car type) '(const volatile)))
|
||||
(let ((rest (drop-while (cut memq <> '(const volatile)) type)))
|
||||
(if (null? (cdr rest)) (car rest) rest))
|
||||
type))))
|
||||
|
||||
;;; The code's local for a capture, read back out of the record
|
||||
(define (capture-local cap form)
|
||||
(let ((name (first cap)) (type (second cap)))
|
||||
(if (array-form? type)
|
||||
`((var ,name ,type) ,(array-copy type name `(%-> ƛcaptures ,name) form))
|
||||
`((var ,name ,type (%-> ƛcaptures ,name))))))
|
||||
|
||||
;;; The constructor's filling of a capture's field
|
||||
(define (capture-store cap form)
|
||||
(let ((name (first cap)) (type (second cap)))
|
||||
(if (array-form? type)
|
||||
(array-copy type `(%-> ƛcaptures ,name) name form)
|
||||
`(= (%-> ƛcaptures ,name) ,name))))
|
||||
|
||||
;;; DEST, an array of TYPE, given SRC's elements one at a time: C copies
|
||||
;;; an array neither by = nor through an initializer of another
|
||||
;;;
|
||||
;;; (for (var ƛi0 int 0) (< ƛi0 3) (++ ƛi0) (= [dest ƛi0] [src ƛi0]))
|
||||
(define (array-copy type dest src form #!optional (depth 0))
|
||||
(unless (array-bound? type)
|
||||
(sex-error form "a captured array needs its length written" dest))
|
||||
(let ((i (string->symbol (string-append "ƛi" (number->string depth))))
|
||||
(element (array-element-type type)))
|
||||
`(for (var ,i int 0) (< ,i ,(array-bound type)) (++ ,i)
|
||||
,(if (array-form? element)
|
||||
(array-copy element `(¤ ,dest ,i) `(¤ ,src ,i) form (+ depth 1))
|
||||
`(= (¤ ,dest ,i) (¤ ,src ,i))))))
|
||||
|
||||
;;; Structs
|
||||
|
||||
;;; Record the named structs, unions and enums in the type database
|
||||
(define (process-struct sex-struct acc)
|
||||
(let-values (((doc form) (extract-aggregate-docstring sex-struct)))
|
||||
;; Resolve before registering: a field of closure type has to reach
|
||||
;; the type database as the struct it becomes, or member access
|
||||
;; through it finds nothing
|
||||
(let ((form (resolve-closure-types form)))
|
||||
(register-aggregate! form)
|
||||
(with-docstring doc form acc)))
|
||||
(with-docstring doc form acc))))
|
||||
|
||||
;;; (sum shape ((circle ((r float))) (rect ((w float) (h float)))))
|
||||
;;; is the tag enum, a payload struct per variant that has fields, the
|
||||
@@ -1617,15 +2276,16 @@
|
||||
(set! (hash-table-ref env :scopes) (list))
|
||||
env))
|
||||
|
||||
;;; The writer spells no `_', and an initializer is an expression like
|
||||
;;; any other:
|
||||
;;; The writer spells neither `closure' nor `_', and an initializer is
|
||||
;;; an expression like any other:
|
||||
;;;
|
||||
;;; (var n _ 1) -> int n = 1
|
||||
;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)}
|
||||
(define (process-global-var sex-var acc)
|
||||
(check-shape (if (memq (car sex-var) '(pub extern)) (cdr sex-var) sex-var))
|
||||
(let* ((qualifier (and (memq (car sex-var) '(pub extern)) (car sex-var)))
|
||||
(core (if qualifier (cdr sex-var) sex-var))
|
||||
(let* ((resolved (resolve-closure-types sex-var))
|
||||
(qualifier (and (memq (car resolved) '(pub extern)) (car resolved)))
|
||||
(core (if qualifier (cdr resolved) resolved))
|
||||
(env (make-toplevel-env (and (pair? (cdr core)) (second core))))
|
||||
;; `(extern var n int)' has no initializer to work a `_' out
|
||||
;; from
|
||||
@@ -1647,7 +2307,7 @@
|
||||
(drop solved 3))))
|
||||
solved))))
|
||||
(form (if qualifier
|
||||
(copy-form-source! sex-var (cons qualifier core))
|
||||
(copy-form-source! resolved (cons qualifier core))
|
||||
core)))
|
||||
(when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core)))
|
||||
(add-name-type! (second core) (third core)))
|
||||
@@ -1704,6 +2364,9 @@
|
||||
(string->symbol (substring s 1))))))
|
||||
|
||||
;;; Utils
|
||||
(define (non-empty-list? form)
|
||||
(and (list? form)
|
||||
(not (null? form))))
|
||||
|
||||
(define (sex-fn? form)
|
||||
"The `form` must be toplevel.
|
||||
@@ -1714,6 +2377,9 @@ Returns #f if the form is not a function, returns the form otherwise"
|
||||
('extern 'fn . _)) form)
|
||||
(else #f)))
|
||||
|
||||
(define (sex-fn-public? fn-form)
|
||||
(eq? (first fn-form) 'pub))
|
||||
|
||||
(define (sex-fn-name fn-form)
|
||||
(assert (sex-fn? fn-form)
|
||||
(fmt #f "Form " fn-form " is not a function"))
|
||||
@@ -1728,3 +2394,8 @@ Returns #f if the form is not a function, returns the form otherwise"
|
||||
(assert (sex-fn? fn-form)
|
||||
(fmt #f "Form " fn-form " is not a function"))
|
||||
(fourth (fn-core fn-form)))
|
||||
|
||||
(define (sex-fn-body fn-form)
|
||||
(assert (sex-fn? fn-form)
|
||||
(fmt #f "Form " fn-form " is not a function"))
|
||||
(drop fn-form (fn-header-length fn-form)))
|
||||
|
||||
@@ -668,6 +668,9 @@
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; data structures
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: behind a pointer, the rest of the
|
||||
;; chain is O -- `struct p * * q' is body `*' and O (*) -- and it was
|
||||
;; dropped, so the declaration lost all but its first star.
|
||||
(define (c-struct/aux type x . o)
|
||||
;; can be just pointer to SUC, need to support such case:
|
||||
;; struct whatever * - body is just '*'
|
||||
@@ -692,14 +695,8 @@
|
||||
(cat " " name)
|
||||
"")
|
||||
(if (not (null? body))
|
||||
(cat body)
|
||||
"")
|
||||
(c-type-words o))))))
|
||||
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: what follows the first star of a
|
||||
;; tagged type, `* const' in (struct what * const), was dropped
|
||||
(define (c-type-words words)
|
||||
(fmt-join (lambda (word) (cat " " word)) words ""))
|
||||
(apply cat body (map (lambda (t) (cat " " t)) o))
|
||||
""))))))
|
||||
|
||||
(define (c-struct . args) (apply c-struct/aux "struct" args))
|
||||
(define (c-union . args) (apply c-struct/aux "union" args))
|
||||
@@ -714,15 +711,13 @@
|
||||
(if (pair? x) (cat (car x) " = " (c-expr (cadr x))) (dsp x)))
|
||||
(let* ((name (if (null? o) (if (or (symbol? x) (string? x)) x #f) x))
|
||||
(vals (if name (if (null? o) #f (car o)) x)))
|
||||
;; MODIFIED FROM UPSTREAM fmt-c: (enum mood * const) is a
|
||||
;; pointer, and its star was taken for the list of values
|
||||
(if (pair? vals)
|
||||
(if vals
|
||||
(c-wrap-stmt
|
||||
(cat
|
||||
(c-braced-block
|
||||
(if name (cat "enum " name) (dsp "enum"))
|
||||
(c-in-expr (apply c-begin (map c-enum-one vals))))))
|
||||
(c-wrap-stmt (cat "enum " name (or vals "") (c-type-words (if vals (cdr o) '())))))))
|
||||
(c-wrap-stmt (cat "enum " name)))))
|
||||
|
||||
(define (c-attribute . args)
|
||||
(cat "__attribute__ ((" (fmt-join c-expr args ", ") "))"))
|
||||
|
||||
@@ -10,8 +10,10 @@
|
||||
utils)
|
||||
|
||||
(export
|
||||
register-macro
|
||||
cat
|
||||
comment
|
||||
get-macro
|
||||
macro?
|
||||
apply-macro
|
||||
defmacro
|
||||
@@ -46,7 +48,10 @@
|
||||
get-underlying-type type-match type-pattern-matches?
|
||||
map-fields
|
||||
get-name-type get-return-type type-of
|
||||
get-method))
|
||||
;; what a generic asks before it expands:
|
||||
;; (realizes? 'ord type) beats a wall of C
|
||||
;; errors two stages downstream
|
||||
realizes? get-method))
|
||||
,@body)))
|
||||
|
||||
(define (get-macro name)
|
||||
|
||||
114
sex-mode.el
114
sex-mode.el
@@ -1,40 +1,8 @@
|
||||
;;; sex-mode.el --- Major mode for Sex code -*- lexical-binding: t -*-
|
||||
|
||||
;; Copyright (C) 2025-2026 alex-eg
|
||||
|
||||
;; Author: alex-eg <alexey.e.egorov@gmail.com>
|
||||
;; Version: 0.1.0
|
||||
;; Package-Requires: ((emacs "28.1"))
|
||||
;; Keywords: languages
|
||||
;; URL: https://git.kotobank.ch/alex-eg/sex
|
||||
;; This file is not part of GNU Emacs.
|
||||
|
||||
;;; Commentary:
|
||||
|
||||
;; Major mode for Sex, a compiled language with S-expression syntax.
|
||||
;; The mode derives from `lisp-data-mode' and fontifies Sex
|
||||
;; declarations and keywords.
|
||||
;;
|
||||
;; `sex-mode' is one file in the Sex repository. Quelpa installs it
|
||||
;; from that git remote:
|
||||
;;
|
||||
;; (use-package sex-mode
|
||||
;; :ensure nil
|
||||
;; :quelpa
|
||||
;; (sex-mode :fetcher git
|
||||
;; :url "https://git.kotobank.ch/alex-eg/sex.git"
|
||||
;; :files ("sex-mode.el")
|
||||
;; :upgrade t))
|
||||
;;
|
||||
;; Visiting a .sex file turns the mode on.
|
||||
|
||||
;;; Code:
|
||||
|
||||
(require 'scheme)
|
||||
|
||||
(defgroup sex-mode nil
|
||||
"Major mode for Sex code."
|
||||
:prefix "sex-"
|
||||
:prefix 'sex-
|
||||
:group 'languages)
|
||||
|
||||
(define-abbrev-table 'sex-mode-abbrev-table ()
|
||||
@@ -43,8 +11,8 @@ It has `scheme-mode-abbrev-table' as its parent."
|
||||
:parents (list scheme-mode-abbrev-table))
|
||||
|
||||
(defvar sex-mode-syntax-table
|
||||
(make-syntax-table lisp-data-mode-syntax-table)
|
||||
"Syntax table used in Sex mode.")
|
||||
(let ((table (make-syntax-table lisp-data-mode-syntax-table)))
|
||||
table))
|
||||
|
||||
(defvar sex-mode-map
|
||||
(let ((map (make-sparse-keymap)))
|
||||
@@ -53,72 +21,58 @@ It has `scheme-mode-abbrev-table' as its parent."
|
||||
"Keymap for Sex mode.
|
||||
All commands in `lisp-mode-shared-map' are inherited by this map.")
|
||||
|
||||
(defvar sex-mode-line-process ""
|
||||
"Mode-line process string for Sex mode.")
|
||||
(defvar sex-mode-line-process "")
|
||||
|
||||
(defconst sex-font-lock-keywords
|
||||
(eval-when-compile
|
||||
(list
|
||||
;; Declarations. `pub' and `extern' are optional prefixes, so
|
||||
;; `(pub fn main' highlights both keywords and the name.
|
||||
;; Declarations
|
||||
(list (concat "("
|
||||
"\\(?:\\(pub\\|extern\\)[[:space:]]+\\)?"
|
||||
(regexp-opt '("define"
|
||||
(regexp-opt '("chicken-define"
|
||||
"chicken-define-syntax"
|
||||
"chicken-import"
|
||||
"chicken-load"
|
||||
"define"
|
||||
"defmacro"
|
||||
"enum"
|
||||
"fn"
|
||||
"extern"
|
||||
"import"
|
||||
"include"
|
||||
"fn"
|
||||
"ops"
|
||||
"pub"
|
||||
"record"
|
||||
"realize"
|
||||
"spec"
|
||||
"struct"
|
||||
"sum"
|
||||
"typedef"
|
||||
"union"
|
||||
"var")
|
||||
'words)
|
||||
"var"
|
||||
"union")
|
||||
'word)
|
||||
"\\>"
|
||||
"[[:space:]]*"
|
||||
"\\([[:word:]]*\\)")
|
||||
'(1 font-lock-keyword-face nil t)
|
||||
'(2 font-lock-keyword-face)
|
||||
'(3 font-lock-function-name-face nil t))
|
||||
;; Statement and expression heads, plus the macro-language forms
|
||||
;; that appear in `defmacro' bodies.
|
||||
'(1 font-lock-keyword-face)
|
||||
'(2 font-lock-function-name-face))
|
||||
;; Keywords
|
||||
(list (concat "("
|
||||
(regexp-opt '("break"
|
||||
"c-bit-or"
|
||||
"c-bit-or="
|
||||
"c-or"
|
||||
(regexp-opt '(
|
||||
"do"
|
||||
"case"
|
||||
"case/fallthrough"
|
||||
"cast"
|
||||
"continue"
|
||||
"default"
|
||||
"do"
|
||||
"else"
|
||||
"for"
|
||||
"get-method"
|
||||
"goto"
|
||||
"if"
|
||||
"lambda"
|
||||
"map-fields"
|
||||
"for"
|
||||
"goto"
|
||||
"match"
|
||||
"return"
|
||||
"sizeof"
|
||||
"static-assert"
|
||||
"switch"
|
||||
"type-match"
|
||||
"type-of"
|
||||
"while"
|
||||
"$"
|
||||
"."
|
||||
":")
|
||||
'words))
|
||||
'(1 font-lock-builtin-face))))
|
||||
"Font-lock keywords for Sex mode.")
|
||||
"var"
|
||||
"while")
|
||||
'word)
|
||||
"\\>")
|
||||
'(1 'font-lock-builtin-face)))))
|
||||
|
||||
(defun sex-mode-set-variables ()
|
||||
"Set up buffer-local variables for Sex mode."
|
||||
(set-syntax-table sex-mode-syntax-table)
|
||||
(setq local-abbrev-table sex-mode-abbrev-table)
|
||||
(setq mode-line-process '("" sex-mode-line-process))
|
||||
@@ -135,6 +89,8 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
|
||||
(put 'defmacro 'lisp-indent-function 'defun)
|
||||
(put 'record 'lisp-indent-function 'defun)
|
||||
(put 'sum 'lisp-indent-function 'defun)
|
||||
(put 'spec 'lisp-indent-function 'defun)
|
||||
(put 'realize 'lisp-indent-function 'defun)
|
||||
(put 'ops 'lisp-indent-function 'defun)
|
||||
(put 'match 'lisp-indent-function 1)
|
||||
(put 'struct 'lisp-indent-function 'defun)
|
||||
@@ -157,8 +113,6 @@ Blank lines separate paragraphs. Semicolons start comments.
|
||||
(sex-mode-set-variables))
|
||||
|
||||
;;;###autoload
|
||||
(add-to-list 'auto-mode-alist '("\\.sex\\'" . sex-mode))
|
||||
(add-to-list 'auto-mode-alist '("\\.\\(sex\\|hsex\\)\\'" . sex-mode))
|
||||
|
||||
(provide 'sex-mode)
|
||||
|
||||
;;; sex-mode.el ends here
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
load-persistent-module-paths
|
||||
check-public-interface
|
||||
module-dependencies
|
||||
read-public-interface)
|
||||
read-public-interface
|
||||
|
||||
;; for the tests
|
||||
get-module-paths)
|
||||
|
||||
(define +persistent-module-paths+ (list))
|
||||
|
||||
@@ -130,11 +133,10 @@
|
||||
;;; macros are the module's own and those its imports give it, lent for
|
||||
;;; the expanding and taken back after, so the importer is left with the
|
||||
;;; pub ones alone. One that reads the type database sees what the
|
||||
;;; importer knows, which no declaration of the module's is yet; a call
|
||||
;;; that fails after asking for one -- (field-count box), box being the
|
||||
;;; module's record -- gives importers nothing, as before, and is the
|
||||
;;; module's own compile's to check. Any other failure is the importer's
|
||||
;;; too: (boom) raising "nope" says so wherever it is read
|
||||
;;; importer knows, which a type private to the module is not; a call
|
||||
;;; that cannot expand for that -- (print-struct box), box being the
|
||||
;;; module's -- gives importers nothing, as before, and is the module's
|
||||
;;; own compile's to check
|
||||
(define +modules-expanded+ (list))
|
||||
|
||||
(define (module-forms raw-forms)
|
||||
@@ -145,8 +147,7 @@
|
||||
forms))))
|
||||
|
||||
(define (expanded raw-forms)
|
||||
(let ((lent (list))
|
||||
(declared (declared-names raw-forms)))
|
||||
(let ((lent (list)))
|
||||
(define (lend! form)
|
||||
(let ((name (macro-name form)))
|
||||
(unless (assq name lent)
|
||||
@@ -156,36 +157,14 @@
|
||||
(cond ((macro-name form) (lend! form) (list form))
|
||||
((splice? form) (append-map expand (cdr form)))
|
||||
((macro? form)
|
||||
(let ((result (expand-call form declared)))
|
||||
(let ((result (handle-exceptions exn #f (apply-macro form))))
|
||||
(cond ((or (not result) (null? result)) (list))
|
||||
(else (stamp-form-source! result (form-source form))
|
||||
(expand result)))))
|
||||
(else (list form))))
|
||||
(dynamic-wind
|
||||
void
|
||||
(lambda ()
|
||||
(for-each lend! (imported-macro-forms raw-forms))
|
||||
(append-map expand raw-forms))
|
||||
(lambda ()
|
||||
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry)))
|
||||
lent)))))
|
||||
|
||||
(define (expand-call form declared)
|
||||
(let ((unknown (list)))
|
||||
(handle-exceptions exn
|
||||
(if (any (lambda (name) (memq name declared)) unknown) #f (abort exn))
|
||||
(parameterize ((unknown-name (lambda (name) (set! unknown (cons name unknown)))))
|
||||
(apply-macro form)))))
|
||||
|
||||
;;; The names FORMS declare, types and all
|
||||
(define (declared-names forms)
|
||||
(append (map car (declared-types forms))
|
||||
(filter-map (lambda (form)
|
||||
(match form
|
||||
((or ('pub (or 'fn 'var) (? symbol? name) . _)
|
||||
((or 'fn 'var) (? symbol? name) . _))
|
||||
name)
|
||||
(_ #f)))
|
||||
(let ((forms (append-map expand raw-forms)))
|
||||
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry))) lent)
|
||||
forms)))
|
||||
|
||||
(define (splice? form)
|
||||
@@ -270,6 +249,7 @@
|
||||
(fold
|
||||
(lambda (form acc)
|
||||
(check-written-out form)
|
||||
(check-realized-spec form visible hidden)
|
||||
(fold (lambda (use acc) (check-type-use form use visible hidden acc))
|
||||
acc
|
||||
(append-map (lambda (type) (type-uses type #f))
|
||||
@@ -291,6 +271,22 @@
|
||||
(_ #f)))
|
||||
(_ #f)))
|
||||
|
||||
;;; A pub realization goes to importers, who look its spec up; one they
|
||||
;;; cannot see failed there, in whichever named this module before the
|
||||
;;; spec's, and said nothing of where it was written
|
||||
(define (check-realized-spec form visible hidden)
|
||||
(match form
|
||||
(('pub 'realize ((? symbol? spec) _) . _)
|
||||
(let ((kept (assq spec hidden)))
|
||||
(when (and kept (not (assq spec visible)))
|
||||
(sex-error form
|
||||
(string-append "importers cannot see this spec; "
|
||||
(if (fourth kept)
|
||||
"import its module with pub"
|
||||
"make it pub"))
|
||||
spec))))
|
||||
(_ #f)))
|
||||
|
||||
;;; USE is (name . behind-a-pointer?)
|
||||
(define (check-type-use form use visible hidden acc)
|
||||
(let* ((name (car use))
|
||||
@@ -346,6 +342,9 @@
|
||||
(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)
|
||||
@@ -372,7 +371,7 @@
|
||||
((¤) (let ((element (array-element-type type)))
|
||||
(append (if element (type-uses element behind?) (list))
|
||||
(if (array-bound? type) (bound-uses (array-bound type)) (list)))))
|
||||
((fn)
|
||||
((fn closure)
|
||||
(if (and (pair? (cdr type)) (list? (second type)))
|
||||
(append-map (lambda (t) (type-uses t #f))
|
||||
(signature-types (second type) (last type)))
|
||||
@@ -389,23 +388,24 @@
|
||||
((pair? bound) (append-map bound-uses (cdr bound)))
|
||||
(else (list))))
|
||||
|
||||
;;; The types and constants FORMS declare, as (name kind body?):
|
||||
;;; The types, constants and specs 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)
|
||||
;;; (spec (shown T) ...) -> (shown spec #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)
|
||||
(if (and (memq (car core) '(define spec))
|
||||
(pair? (second core)))
|
||||
(car (second core))
|
||||
(second core)))))
|
||||
(and (memq (car core)
|
||||
'(record struct union enum sum typedef define))
|
||||
'(record struct union enum sum typedef define spec))
|
||||
(symbol? name)
|
||||
(list name
|
||||
(car core)
|
||||
@@ -499,6 +499,19 @@
|
||||
(copy-form-source! form
|
||||
`(ops ,type ,@(map public-fn-interface methods))))))
|
||||
|
||||
;;; A realization leaves with the methods written in it, reduced to
|
||||
;;; prototypes. Its defaults do not travel: the importer synthesizes
|
||||
;;; its own static copies from the spec, which is why a default is
|
||||
;;; static even when the realization is pub.
|
||||
(define (realize-public-interface form)
|
||||
(let ((core (cdr form)))
|
||||
(copy-form-source!
|
||||
form
|
||||
`(pub realize ,(second core)
|
||||
;; pub goes back on at the realize, not on its methods
|
||||
,@(map (lambda (m) (cdr (public-fn-interface (cons 'pub m))))
|
||||
(remove comment-form? (cddr core)))))))
|
||||
|
||||
;;; TODO: use semen facilities to analyze modules
|
||||
(define (process-public-interface-form form acc)
|
||||
(match form
|
||||
@@ -509,11 +522,13 @@
|
||||
(('pub 'var . _)
|
||||
(match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
|
||||
(cons (copy-form-source! form `(extern var ,name ,type)) acc)))
|
||||
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
|
||||
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'spec 'struct 'sum 'typedef 'union) . _)
|
||||
(cons (copy-form-source! form (cdr form)) acc))
|
||||
(('ops . _)
|
||||
(let ((exported (ops-public-interface form)))
|
||||
(if exported (cons exported acc) acc)))
|
||||
(('pub 'realize . _)
|
||||
(cons (realize-public-interface form) acc))
|
||||
(('pub . _)
|
||||
(sex-error form "pub must be followed by a definition" form))
|
||||
(_ acc)))
|
||||
|
||||
15
sexc.scm
15
sexc.scm
@@ -23,7 +23,11 @@
|
||||
utils)
|
||||
|
||||
(export
|
||||
main)
|
||||
main
|
||||
|
||||
;; for the tests
|
||||
args-before-separator args-after-separator
|
||||
dependency-rule spell-stdout-output)
|
||||
|
||||
;;; Main function facilities
|
||||
|
||||
@@ -257,9 +261,10 @@ status, which is ours to pass on."
|
||||
(with-directory input-source (process)))))
|
||||
|
||||
(define prelude
|
||||
(append
|
||||
'((include inttypes.h)
|
||||
(include stdbool.h)
|
||||
(include stddef.h)
|
||||
(include stddef.h) ; max_align_t, for closure environments
|
||||
(typedef u8 uint8-t)
|
||||
(typedef i8 int8-t)
|
||||
(typedef u16 uint16-t)
|
||||
@@ -267,7 +272,11 @@ status, which is ours to pass on."
|
||||
(typedef u32 uint32-t)
|
||||
(typedef i32 int32-t)
|
||||
(typedef u64 uint64-t)
|
||||
(typedef i64 int64-t)))
|
||||
(typedef i64 int64-t))
|
||||
|
||||
;; The closure environment is the part of the ABI, so include it in
|
||||
;; every module
|
||||
(list (closure-env-declaration))))
|
||||
|
||||
;;; An error is told by its message, file:line first where it has one.
|
||||
;;; CHICKEN's call history after it is for working on sexc itself, and
|
||||
|
||||
83
tests/args.scm
Normal file
83
tests/args.scm
Normal file
@@ -0,0 +1,83 @@
|
||||
;;; Splitting the command line at `--'.
|
||||
;;;
|
||||
;;; getopt-long cannot do this: it consumes the separator and merges
|
||||
;;; everything after it into `@' alongside the input file. So sexc
|
||||
;;; splits the raw argv first, and only the head is parsed as options.
|
||||
;;; Everything else reaches the C compiler exactly as written --
|
||||
;;; including the words that do not start with a dash, which a previous
|
||||
;;; leading-dash heuristic used to drop.
|
||||
|
||||
(import sexc)
|
||||
|
||||
(define full '("foo.sex" "-o" "bar" "--" "-framework" "OpenGL" "-Wall"))
|
||||
|
||||
(test-group "argument separator"
|
||||
|
||||
(test "options and input file stay with sexc"
|
||||
'("foo.sex" "-o" "bar")
|
||||
(args-before-separator full))
|
||||
|
||||
(test "the tail reaches the compiler verbatim"
|
||||
'("-framework" "OpenGL" "-Wall")
|
||||
(args-after-separator full))
|
||||
|
||||
;; The case that motivated this: `OpenGL' has no leading dash and was
|
||||
;; silently dropped, leaving `-framework' to swallow whatever flag
|
||||
;; came next.
|
||||
(test "a word without a dash survives"
|
||||
'("-framework" "OpenGL")
|
||||
(args-after-separator '("x.sex" "--" "-framework" "OpenGL")))
|
||||
|
||||
(test "no separator means nothing for the compiler"
|
||||
'()
|
||||
(args-after-separator '("foo.sex" "-o" "bar")))
|
||||
|
||||
(test "no separator leaves every argument with sexc"
|
||||
'("foo.sex" "-o" "bar")
|
||||
(args-before-separator '("foo.sex" "-o" "bar")))
|
||||
|
||||
(test "a trailing separator is allowed"
|
||||
'()
|
||||
(args-after-separator '("foo.sex" "--")))
|
||||
|
||||
(test "a leading separator leaves no input file"
|
||||
'()
|
||||
(args-before-separator '("--" "-lm")))
|
||||
|
||||
;; Only the first `--' separates; a later one is an ordinary compiler
|
||||
;; argument (ld takes several).
|
||||
(test "only the first separator counts"
|
||||
'("-Wl,--as-needed" "--" "-lm")
|
||||
(args-after-separator '("x.sex" "--" "-Wl,--as-needed" "--" "-lm")))
|
||||
|
||||
(test "an empty command line is handled"
|
||||
'()
|
||||
(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"))))
|
||||
58
tests/basic.scm
Normal file
58
tests/basic.scm
Normal file
@@ -0,0 +1,58 @@
|
||||
(import fmt-c-writer)
|
||||
|
||||
(test-group "basic"
|
||||
|
||||
;; unkebabify
|
||||
(test '- (unkebabify '-))
|
||||
(test '-- (unkebabify '--))
|
||||
(test '-> (unkebabify '->))
|
||||
(test '-= (unkebabify '-=))
|
||||
(test 'kebab_case (unkebabify 'kebab-case))
|
||||
(test '_what_ (unkebabify '-what-))
|
||||
(test 'this->member (unkebabify 'this->member))
|
||||
(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,
|
||||
;; just under a different name than was written.
|
||||
(test 'naïve_count (unkebabify 'naïve-count))
|
||||
(test 'aï_b (unkebabify 'aï-b))
|
||||
(test 'ïï (unkebabify 'ïï))
|
||||
|
||||
;; atom-to-fmt-c
|
||||
(test '%fun (atom-to-fmt-c 'fn))
|
||||
(test '%prototype (atom-to-fmt-c 'prototype))
|
||||
(test '%block-begin (atom-to-fmt-c 'do))
|
||||
(test '%define (atom-to-fmt-c 'define))
|
||||
(test '%pointer (atom-to-fmt-c 'pointer))
|
||||
(test '%array (atom-to-fmt-c 'array))
|
||||
(test 'vector-ref (atom-to-fmt-c '¤))
|
||||
(test '%include (atom-to-fmt-c 'include))
|
||||
|
||||
;; C99 onwards, true C spellings for bool
|
||||
(test 'bool (atom-to-fmt-c 'bool))
|
||||
(test 'true (atom-to-fmt-c 'true))
|
||||
(test 'false (atom-to-fmt-c 'false))
|
||||
|
||||
;; dot-access -> %. member-access directive (kebab-converted operands)
|
||||
(test '(%. a b) (walk-expr '(dot-access a b)))
|
||||
(test '(%. a b c) (walk-expr '(dot-access a b c)))
|
||||
(test '(%. a_b c) (walk-expr '(dot-access a-b c)))
|
||||
|
||||
;; comment -> %comment directive (rendered as /* ... */)
|
||||
;; The reader eats only the `;' that introduced the line, so ";;; Foo"
|
||||
;; arrives as ";; Foo"; and c-comment puts nothing between /* */ and
|
||||
;; the text. Both are handled on the way out.
|
||||
(test '(%comment " hi ") (walk-expr '(comment " hi")))
|
||||
(test '(%comment " hi ") (process-toplevel-form '(comment " hi")))
|
||||
(test '(%comment " Foo ") (walk-expr '(comment ";; Foo")))
|
||||
(test '(%comment " Foo ") (walk-expr '(comment ";;; Foo "))))
|
||||
@@ -1,8 +1,71 @@
|
||||
;;; Codegen details that are easy to get subtly wrong: precedence,
|
||||
;;; scopes, comments in odd places, and the shapes no earlier test
|
||||
;;; program happened to use.
|
||||
;;; Codegen details that are easy to get subtly wrong, and that the
|
||||
;;; walk-* unit tests cannot see: they check the intermediate form we
|
||||
;;; hand to fmt-c, not the C that fmt-c renders from it.
|
||||
;;;
|
||||
;;; Both cases below were found by writing an OpenGL example, not by
|
||||
;;; the existing suite, because both need an operand shape that no
|
||||
;;; earlier test program happened to use.
|
||||
|
||||
(import srfi-13)
|
||||
(import (chicken condition)
|
||||
(chicken port)
|
||||
(chicken string)
|
||||
srfi-13
|
||||
fmt-c-writer
|
||||
reader
|
||||
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 (read-source source)))
|
||||
(with-output-to-string
|
||||
(lambda ()
|
||||
(parameterize ((sex-line-directives 'none))
|
||||
(emit-c (semen-process forms)))))))
|
||||
|
||||
;;; Warnings are what `warns?' is for; a test that happens to trip one
|
||||
;;; should not print it
|
||||
(define (silently thunk)
|
||||
"THUNK's value, with whatever it wrote to stderr dropped."
|
||||
(let ((value #f))
|
||||
(with-error-output-to-string (lambda () (set! value (thunk))))
|
||||
value))
|
||||
|
||||
(define (emits? source fragment)
|
||||
(and (string-contains (silently (lambda () (sex->c source))) fragment) #t))
|
||||
|
||||
(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 (thunk) #f)))
|
||||
|
||||
(define (fails-with? thunk fragment)
|
||||
(let ((m (failure-message thunk)))
|
||||
(and m (string-contains m fragment) #t)))
|
||||
|
||||
(define (reports? source fragment)
|
||||
(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)))))))
|
||||
|
||||
;;; A record reached through a typedef of a pointer to it
|
||||
(define pt-ref-src
|
||||
@@ -33,6 +96,13 @@
|
||||
" (var p (struct point)) (var pp (* struct point) (& p))"
|
||||
" (var l (struct line)) " body ")"))
|
||||
|
||||
(define (warnings source)
|
||||
"What compiling SOURCE writes to stderr."
|
||||
(with-error-output-to-string (lambda () (sex->c source))))
|
||||
|
||||
(define (warns? source fragment)
|
||||
(and (string-contains (warnings source) fragment) #t))
|
||||
|
||||
(test-group "codegen"
|
||||
|
||||
;; A case body shared the switch's scope, so two cases could not
|
||||
@@ -342,7 +412,7 @@
|
||||
"codegen.sex:2: a macro defined after a call to it"))
|
||||
(test-assert "naming where the call is"
|
||||
(reports? "(fn f () int\n (return (later 1)))\n(defmacro (later x) x)"
|
||||
"/codegen.sex:2\""))
|
||||
"called at codegen.sex:2"))
|
||||
(test-assert "an error in a macro's body names the call"
|
||||
(reports? "(defmacro (boom x) (error \"no good\" x))\n(fn f () int (return (boom 1)))"
|
||||
"codegen.sex:2: expanding boom: no good")))
|
||||
@@ -474,12 +544,49 @@
|
||||
(not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")")
|
||||
"static_assert("))))
|
||||
|
||||
(test-group "lambdas"
|
||||
;; a definition names every parameter before C23, so one written as a
|
||||
;; type alone gets a name nothing reads
|
||||
;; A closure is a code pointer beside its captures. The struct is
|
||||
;; named from the signature, so separate translation units agree on
|
||||
;; it, and calling one goes through `code' with `env' passed first.
|
||||
;;
|
||||
;; A closure struct, and the helper its calls go through, are each
|
||||
;; emitted once per signature; the registries deciding that are
|
||||
;; compile-time state like the type databases, and outlive a single
|
||||
;; `sex->c' here. So every case below that looks for a *definition*
|
||||
;; uses a signature of its own -- cases looking at a call site can
|
||||
;; share one.
|
||||
(test-group "closures"
|
||||
(test-assert "the type becomes a struct named for its signature"
|
||||
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
|
||||
"struct ƛint_int"))
|
||||
;; captures are a closure's other parameters, under C's rule for
|
||||
;; those: no two alike, and none redeclared at the body's top level.
|
||||
;; Both were C's redefinition errors
|
||||
;; ((+ a 1)) was a capture named `+', holding a
|
||||
(test-assert "a capture is a name, or a name and a value"
|
||||
(reports? (in-fn "(var c (closure () int) (closure () int ((+ a 1)) (return 1)))")
|
||||
"a capture is a name, or (name value)"))
|
||||
(test-assert "a capture named like a parameter is refused"
|
||||
(reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))")
|
||||
"a capture and a parameter share a name"))
|
||||
(test-assert "so is one redeclared at the top of the body"
|
||||
(reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))")
|
||||
"the body redeclares a capture"))
|
||||
(test-assert "while a block inside may shadow it"
|
||||
(emits? (in-fn "(var c (closure () int) (closure () int (a) (do (var a int 5) (g a)) (return a)))")
|
||||
"int a = 5;"))
|
||||
;; the closure's type was built from each parameter's second element,
|
||||
;; which a type alone has none of
|
||||
(test-assert "a parameter may name nothing"
|
||||
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
|
||||
"struct ƛint__int"))
|
||||
(test-assert "and its code names it, a definition needing one before C23"
|
||||
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
|
||||
"int ƛu0, int b)"))
|
||||
;; a definition names every parameter before C23, a lambda's as a
|
||||
;; closure's code does
|
||||
(test-assert "a lambda's unnamed parameter is named in its definition"
|
||||
(emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))"
|
||||
"λ0_f (int λu0, int b)"))
|
||||
"λ0_f (int ƛu0, int b)"))
|
||||
(test-assert "and a variadic one keeps its ..."
|
||||
(emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))"
|
||||
"λ0_f (int n, ...)"))
|
||||
@@ -487,7 +594,120 @@
|
||||
;; nothing defined it
|
||||
(test-assert "an empty lambda is an empty function"
|
||||
(emits? "(fn f () void (var g (fn () void) (lambda () void)))"
|
||||
"static void λ0_f (void) {}")))
|
||||
"static void λ0_f (void) {}"))
|
||||
(test-assert "so is an empty closure's code"
|
||||
(emits? (in-fn "(var c (closure () void) (closure () void ()))") "(void * ƛe) {}"))
|
||||
;; the call helper would have to forward the rest, which C cannot
|
||||
(test-assert "a closure cannot be variadic"
|
||||
(reports? (in-fn "(var c _ (closure ((n int) ...) int () (return n)))")
|
||||
"a closure cannot be variadic; a lambda can"))
|
||||
;; The environment is one shared union, declared in the prelude --
|
||||
;; its layout is part of the ABI two units agree on, so it cannot
|
||||
;; depend on what either file contains. `sex->c' has no prelude, so
|
||||
;; what is visible here is the member
|
||||
(test-assert "whose environment is the shared union"
|
||||
(emits? "(fn f ((c (closure ((float)) int))) int (return (c 1.0)))"
|
||||
"union ƛenv env;"))
|
||||
;; The receiver goes through a helper rather than being written
|
||||
;; out twice, so that `[table (++ i)]' evaluates its index once,
|
||||
;; exactly as it would for an array of function pointers
|
||||
(test-assert "a call passes the receiver to a helper"
|
||||
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
|
||||
"ƛint_int_call(c, 1)"))
|
||||
(test-assert "and the helper is what dereferences it"
|
||||
(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)))"
|
||||
"ƛint_int_call(t[++i], 1)"))
|
||||
(test-assert "so is a member receiver"
|
||||
(emits? "(struct h ((cb (closure ((int)) int))))
|
||||
(fn f ((s (struct h))) int (return ((. s cb) 1)))"
|
||||
"ƛint_int_call(s.cb, 1)"))
|
||||
(test-assert "a captured name is rebound in the lifted body"
|
||||
(emits? "(fn f ((n int)) (closure ((char)) int) (return (closure ((x char)) int (n) (return n))))"
|
||||
"int n = ƛcaptures->n;"))
|
||||
(test-assert "captures are checked against the environment"
|
||||
(emits? "(fn f ((n int)) (closure ((short)) int) (return (closure ((x short)) int (n) (return n))))"
|
||||
"_Static_assert(sizeof(struct"))
|
||||
;; A closure over nothing has no record to point at, and C has no
|
||||
;; empty struct to declare for it
|
||||
(test-assert "no captures means no capture record"
|
||||
(not (emits? "(fn f () (closure () int) (return (closure () int () (return 7))))"
|
||||
"_captures {")))
|
||||
;; `(name expr)' names a capture and gives what it holds, so the
|
||||
;; expression is evaluated once, where the closure is written
|
||||
(test-assert "a named capture takes its type from the expression"
|
||||
(emits? "(struct p ((x int) (y int)))
|
||||
(fn f ((s (struct p))) (closure () int)
|
||||
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
|
||||
"int sum;"))
|
||||
(test-assert "and the constructor is handed the expression"
|
||||
(emits? "(struct p ((x int) (y int)))
|
||||
(fn f ((s (struct p))) (closure () int)
|
||||
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
|
||||
"_make(s.x + s.y)"))
|
||||
(test-assert "capturing a pointer is how by-reference is spelled"
|
||||
(emits? "(struct p ((x int)))
|
||||
(fn f ((s (* (struct p)))) (closure () int)
|
||||
(return (closure () int ((q s)) (return (-> q x)))))"
|
||||
"struct p* q;"))
|
||||
;; A bare function is a closure that captures nothing, so it
|
||||
;; converts wherever one is expected -- the pointer goes in the
|
||||
;; environment and one thunk per signature reads it back out
|
||||
(test-assert "a named function in a var initializer"
|
||||
(emits? "(fn g ((n int)) int (return n))
|
||||
(fn f () void (var c (closure ((int)) int) g))"
|
||||
"ƛint_int_fromfn(g)"))
|
||||
(test-assert "a lambda, which is a bare function too"
|
||||
(emits? "(fn f () void (var c (closure ((int)) int)
|
||||
(lambda ((n int)) int (return n))))"
|
||||
"ƛint_int_fromfn(λ0_f)"))
|
||||
(test-assert "an argument, against the parameter that signature wrote"
|
||||
(emits? "(fn g ((n int)) int (return n))
|
||||
(fn h ((c (closure ((int)) int))) int (return (c 1)))
|
||||
(fn f () int (return (h g)))"
|
||||
"h(ƛint_int_fromfn(g))"))
|
||||
(test-assert "a return, against the declared return type"
|
||||
(emits? "(fn g ((n int)) int (return n))
|
||||
(fn f () (closure ((int)) int) (return g))"
|
||||
"return ƛint_int_fromfn(g)"))
|
||||
(test-assert "the thunk reads the pointer out of the environment"
|
||||
(emits? "(fn g ((n float)) int (return 1))
|
||||
(fn f () void (var c (closure ((float)) int) g))"
|
||||
"return ƛcaptures->f(ƛa0)"))
|
||||
;; a signature that does not match is left alone, and C rejects it
|
||||
(test-assert "a function of the wrong signature does not convert"
|
||||
(not (emits? "(fn g ((n float)) int (return 1))
|
||||
(fn f () void (var c (closure ((int)) int) g))"
|
||||
"_fromfn(g)")))
|
||||
;; a closure is lifted into the function it was written in, so
|
||||
;; there has to be one
|
||||
(test-assert "a closure at toplevel is refused"
|
||||
(reports? "(var c (closure () int) (closure () int () (return 1)))"
|
||||
"only be written inside a function"))
|
||||
(test-assert "and so is one in a struct field"
|
||||
(reports? "(struct s ((f (closure () int) (closure () int () (return 1)))))"
|
||||
"only be written inside a function"))
|
||||
;; A block opens a scope, so what it declares ends with it
|
||||
(test-assert "a name shadowed in a block does not escape it"
|
||||
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
|
||||
(fn f () int (var c (closure () int) (mk))
|
||||
(do (var c int 9) (g c))
|
||||
(return (c)))"
|
||||
"ƛvoid_int_call(c)"))
|
||||
(test-assert "and the shadowing declaration is what the block sees"
|
||||
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
|
||||
(fn f () int (var c (closure () int) (mk))
|
||||
(do (var c int 9) (g c))
|
||||
(return (c)))"
|
||||
"g(c)"))
|
||||
;; The receiver is written twice, so a name used as an argument
|
||||
;; must not be mistaken for a call of its own
|
||||
(test-assert "a closure passed as an argument stays a value"
|
||||
(emits? "(fn g ((c (closure ((int)) int))) int (return 0))
|
||||
(fn f ((c (closure ((int)) int))) int (return (g c)))"
|
||||
"g(c)")))
|
||||
|
||||
;; An include target is a path, so none of the identifier mangling
|
||||
;; applies to it: GL/gl.h is a file and GLːgl.h is not.
|
||||
@@ -543,16 +763,16 @@
|
||||
(defmacro (t x) (type-match (type-of x) (float 1) (else 0)))
|
||||
(fn f () int (return (t (g))))"
|
||||
"return 1;"))
|
||||
;; a macro is shown the written spelling, not a generated name
|
||||
(test-assert "a function pointer, spelled the way it was written"
|
||||
(emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
(defmacro (t x) (type-match (type-of x) ((fn _ _) 1) (else 0)))
|
||||
;; a macro is shown the written spelling, not the generated struct
|
||||
(test-assert "a closure, spelled the way it was written"
|
||||
(emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(defmacro (t x) (type-match (type-of x) ((closure _ _) 1) (else 0)))
|
||||
(fn f () int (var c _ (mk)) (return (t c)))"
|
||||
"return 1;"))
|
||||
(test-assert "and calling one has the function's return type"
|
||||
(emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
(test-assert "and calling one has the closure's return type"
|
||||
(emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(defmacro (t x) (type-match (type-of x) (int 1) (else 0)))
|
||||
(fn f () int (var c _ (mk)) (return (t (c 1))))"
|
||||
"return 1;"))
|
||||
@@ -594,19 +814,6 @@
|
||||
"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]"))
|
||||
;; each `_' is its own variable: solving one leaves the rest open
|
||||
(test-assert "every wildcard in a signature is its own"
|
||||
(emits? "(fn g ((x int)) char (return 0))
|
||||
(fn f () void (var h (fn ((_)) _) g))"
|
||||
"char (*h)(int) = g"))
|
||||
(test-assert "and the signature's arity has to match"
|
||||
(reports? "(fn g ((x int) (y int)) int (return 0))
|
||||
(fn f () void (var h (fn ((_)) _) g))"
|
||||
"type mismatch"))
|
||||
(test-assert "a typedef answers as itself"
|
||||
(emits? "(typedef count int) (fn g () count (return 0))
|
||||
(fn f () void (var x _ (g)))"
|
||||
"count x = g()"))
|
||||
;; only an integer was taken for a length; a name was read as part
|
||||
;; of the element's
|
||||
(test-assert "of a named length"
|
||||
@@ -633,6 +840,9 @@
|
||||
(test-assert "a lambda's as well"
|
||||
(reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))")
|
||||
"a function's types are written out"))
|
||||
(test-assert "and a closure's"
|
||||
(reports? (in-fn "(var c (closure ((int)) int) (closure ((x int)) _ () (return x)))")
|
||||
"a function's types are written out"))
|
||||
;; a call was typed by asking the global table what a function of
|
||||
;; that name returns, which a local pointer is not
|
||||
;; a value if had no rule either: it is the join of its values
|
||||
@@ -664,6 +874,13 @@
|
||||
(emits? (string-append "(struct ops ((op (fn ((int)) float))))"
|
||||
"(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))")
|
||||
"float r = o.op(1)"))
|
||||
(test-assert "a closure's call, which goes through a helper nothing typed"
|
||||
(emits? "(fn f ((c (closure ((int)) int))) void (var r _ (c 4)))"
|
||||
"int r = ƛint_int_call(c, 4)"))
|
||||
(test-assert "and one returning a closure is called as one"
|
||||
(emits? (string-append "(fn mk ((k int)) (closure ((int)) int) (return (closure ((b int)) int (k) (return (+ k b)))))"
|
||||
"(fn f () void (var fp (fn ((int)) (closure ((int)) int)) mk) (var r _ ((fp 3) 4)))")
|
||||
"int r = ƛint_int_call(fp(3), 4)"))
|
||||
(test-assert "while a function is the pointer it already is"
|
||||
(emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))"
|
||||
"int (*p)(int) = g"))
|
||||
@@ -716,17 +933,18 @@
|
||||
(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"))
|
||||
;; a function pointer type reaches the solver as itself
|
||||
(test-assert "a lambda, from the signature that produced it"
|
||||
(emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
;; 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"
|
||||
(emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(fn f () void (var c _ (mk)))"
|
||||
"int (*c)(int) = mk()"))
|
||||
"struct ƛint_int c = mk()"))
|
||||
(test-assert "and it is callable once inferred"
|
||||
(emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
(emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(fn f () int (var c _ (mk)) (return (c 1)))"
|
||||
"return c(1)"))
|
||||
"ƛint_int_call(c, 1)"))
|
||||
;; C's usual arithmetic conversions, far enough to answer `_'
|
||||
(test-assert "floating beats integral"
|
||||
(emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d"))
|
||||
@@ -800,16 +1018,16 @@
|
||||
;; without `$' a list is one form, so a head that is itself a form
|
||||
;; stays a call rather than becoming two statements
|
||||
(test-assert "a computed callee stays one form"
|
||||
(emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
(emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(defmacro (apply-it x) `((mk) ,x))
|
||||
(fn f () int (return (apply-it 5)))"
|
||||
"mk()(5)"))
|
||||
"ƛint_int_call(mk(), 5)"))
|
||||
;; spliced, it would have become two forms in the `return' -- the
|
||||
;; comma operator, and the wrong answer
|
||||
(test-assert "rather than two forms in its context"
|
||||
(not (emits? "(fn mk () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int (return b))))
|
||||
(not (emits? "(fn mk () (closure ((int)) int)
|
||||
(return (closure ((b int)) int () (return b))))
|
||||
(defmacro (apply-it x) `((mk) ,x))
|
||||
(fn f () int (return (apply-it 5)))"
|
||||
"return mk(), 5"))))
|
||||
@@ -878,6 +1096,14 @@
|
||||
(emits? "(include stdio.h) (fn f () void (static-assert (== 1 1) \"x\"))"
|
||||
"_Static_assert(1 == 1, \"x\")")))
|
||||
|
||||
;; c-struct/aux wrote the tag and the first `*' after it, and
|
||||
;; dropped the rest of the chain
|
||||
(test-group "a pointer chain to a struct"
|
||||
(test-assert "keeps every star"
|
||||
(emits? (in-fn "(var q (* * struct p))") "struct p* * q;"))
|
||||
(test-assert "and every qualifier between them"
|
||||
(emits? (in-fn "(var q (* const * union u))") "union u* const * q;")))
|
||||
|
||||
;; Operands past what an operator takes were written as they came:
|
||||
;; (< a b c) as C's own chain, which compares a boolean with c
|
||||
(test-group "operator arity"
|
||||
@@ -1026,10 +1252,7 @@
|
||||
(emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;"))
|
||||
(test-assert "a number too wide for long long is unsigned, and says so"
|
||||
(emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)")
|
||||
"n = 18446744073709551615u;"))
|
||||
(test-assert "the least long long is spelled as LLONG_MIN, and typed"
|
||||
(emits? (in-fn "(var n _ -9223372036854775808)")
|
||||
"long long n = -9223372036854775807 - 1;")))
|
||||
"n = 18446744073709551615u;")))
|
||||
|
||||
;; A define's body was pasted unwalked, and unparenthesised: `cast'
|
||||
;; stayed a call, and (* x D) regrouped with D's own operator
|
||||
@@ -1207,22 +1430,6 @@
|
||||
"(var g (struct h2) #(#((struct pt) : 1)))")
|
||||
"h2 g = {{1}}")))
|
||||
|
||||
;; fmt-c kept the first star after a tag and dropped what followed it,
|
||||
;; and took an enum's star for its list of values
|
||||
(test-group "pointers to tagged types"
|
||||
(test-assert "a const pointer to a struct stays const"
|
||||
(emits? "(var q (const * struct what))" "struct what* const q;"))
|
||||
(test-assert "and one in an array"
|
||||
(emits? "(var a [const * struct what 4])" "struct what* const a[4];"))
|
||||
(test-assert "a pointer to a pointer keeps both stars"
|
||||
(emits? "(var pp (* * struct what))" "struct what* * pp;"))
|
||||
(test-assert "so does a union's"
|
||||
(emits? "(var u (const * union val))" "union val* const u;"))
|
||||
(test-assert "a pointer to an enum is a pointer"
|
||||
(emits? "(enum mood (glad sad)) (var e (* enum mood))" "enum mood* e;"))
|
||||
(test-assert "and a const one"
|
||||
(emits? "(enum mood (glad sad)) (var f (const * enum mood))" "enum mood* const f;")))
|
||||
|
||||
;; Toplevel forms used to be separated by a blank line unconditionally,
|
||||
;; which spread a block of adjacent typedefs over twice the lines its
|
||||
;; author wrote
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Stands in for the C compiler: writes the arguments it was given, one
|
||||
# to a line, to $CC_ARGUMENTS
|
||||
printf '%s\n' "$@" > "$CC_ARGUMENTS"
|
||||
@@ -1,108 +0,0 @@
|
||||
;;; What sexc makes of its command line.
|
||||
;;;
|
||||
;;; Everything after the first `--' is the C compiler's, word for word;
|
||||
;;; `-o -' is stdout; --depfile writes a make rule. Each shows only in
|
||||
;;; what a sexc process hands on, so each is checked on one. `cc' here
|
||||
;;; stands in for the compiler and writes down the arguments it got.
|
||||
;;;
|
||||
;;; make check-command-line
|
||||
|
||||
(import scheme
|
||||
(chicken base)
|
||||
(chicken file)
|
||||
(chicken io)
|
||||
(chicken pathname)
|
||||
(chicken process)
|
||||
(chicken process-context)
|
||||
(chicken string)
|
||||
srfi-1
|
||||
test)
|
||||
|
||||
(define sexc (or (get-environment-variable "SEXC") "../../sexc"))
|
||||
|
||||
(define scratch (create-temporary-directory))
|
||||
(define (built name) (make-pathname scratch name))
|
||||
|
||||
(define cc-arguments-file (built "cc-arguments"))
|
||||
(set-environment-variable! "CC_ARGUMENTS" cc-arguments-file)
|
||||
(define cc-option (string-append "--c-compiler=" (make-pathname (current-directory) "cc")))
|
||||
|
||||
;;; The lines sexc prints when run with ARGS and INPUT on its stdin, or
|
||||
;;; #f when it fails
|
||||
(define (output-with-input input . args)
|
||||
(let ((proc (process sexc args)))
|
||||
(display input (process-input-port proc))
|
||||
(close-output-port (process-input-port proc))
|
||||
(let ((lines (read-lines (process-output-port proc))))
|
||||
(process-wait proc)
|
||||
(and (process-returned-normally? proc)
|
||||
(zero? (process-exit-status proc))
|
||||
lines))))
|
||||
|
||||
(define (output-of . args)
|
||||
(apply output-with-input "" args))
|
||||
|
||||
(define (cc-arguments)
|
||||
(call-with-input-file cc-arguments-file read-lines))
|
||||
|
||||
;;; ("-o" "a" "/tmp/x.c" "-lm") -> ("-lm")
|
||||
(define (past-c-file arguments)
|
||||
(cdr (find-tail (lambda (a) (equal? (pathname-extension a) "c")) arguments)))
|
||||
|
||||
;;; What the compiler got past sexc's own -o and .c file, when sexc
|
||||
;;; compiles with ARGS
|
||||
(define (cc-tail . args)
|
||||
(and (apply output-of cc-option args)
|
||||
(past-c-file (cc-arguments))))
|
||||
|
||||
(define hello (string-intersperse (call-with-input-file "hello.sex" read-lines) "\n"))
|
||||
|
||||
(test-group "--"
|
||||
;; `OpenGL' has no dash, and was once dropped for it, leaving
|
||||
;; -framework to swallow whatever came next
|
||||
(test "what follows reaches the compiler as written"
|
||||
'("-framework" "OpenGL" "-Wall")
|
||||
(cc-tail "hello.sex" "-o" (built "a") "--" "-framework" "OpenGL" "-Wall"))
|
||||
(test "what precedes stays with sexc"
|
||||
(list "-o" (built "a"))
|
||||
(begin (cc-tail "hello.sex" "-o" (built "a") "--" "-lm")
|
||||
(take (cc-arguments) 2)))
|
||||
(test "without one the compiler gets nothing more"
|
||||
'()
|
||||
(cc-tail "hello.sex" "-o" (built "a")))
|
||||
(test "nor after a trailing one"
|
||||
'()
|
||||
(cc-tail "hello.sex" "-o" (built "a") "--"))
|
||||
;; ld takes a `--' of its own
|
||||
(test "only the first one separates"
|
||||
'("-Wl,--as-needed" "--" "-lm")
|
||||
(cc-tail "hello.sex" "-o" (built "a") "--" "-Wl,--as-needed" "--" "-lm"))
|
||||
(test "a file after it is the compiler's, and the source is stdin"
|
||||
'("extra.o")
|
||||
(and (output-with-input hello cc-option "-o" (built "a") "--" "extra.o")
|
||||
(past-c-file (cc-arguments)))))
|
||||
|
||||
;;; getopt-long reads a lone `-' as an option, and refused `-o -'
|
||||
(test-group "-o -"
|
||||
(test-assert "writes the C to stdout"
|
||||
(member "int main (void) {" (or (output-of "hello.sex" "-C" "-o" "-") '())))
|
||||
(test-assert "and so does --output -"
|
||||
(member "int main (void) {" (or (output-of "hello.sex" "-C" "--output" "-") '()))))
|
||||
|
||||
;;; The rules for the modules a unit imports are checked in tests/modules
|
||||
(test-group "--depfile"
|
||||
(copy-file "hello.sex" (built "a b.sex"))
|
||||
(test "a space is escaped, the way make reads it"
|
||||
(list (string-append (built "a\\ b.c") ": " (built "a\\ b.sex")))
|
||||
(and (output-of (built "a b.sex") "-C" "-o" (built "a b.c")
|
||||
(string-append "--depfile=" (built "a b.d")))
|
||||
(call-with-input-file (built "a b.d") read-lines)))
|
||||
(test "stdin is no file to depend on"
|
||||
(list (string-append (built "hello.c") ":"))
|
||||
(and (output-with-input hello "-C" "-o" (built "hello.c")
|
||||
(string-append "--depfile=" (built "hello.d")))
|
||||
(call-with-input-file (built "hello.d") read-lines))))
|
||||
|
||||
(delete-directory scratch #t)
|
||||
|
||||
(test-exit)
|
||||
@@ -1,2 +0,0 @@
|
||||
(pub fn main () int
|
||||
(return 0))
|
||||
@@ -5,7 +5,8 @@
|
||||
;;; is checked here is what the compiler refuses, and that it refuses
|
||||
;;; it with the name of whatever is wrong.
|
||||
;;;
|
||||
;;; `in-fn' comes 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)
|
||||
|
||||
@@ -42,6 +43,16 @@ ahead of its pub forms."
|
||||
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
|
||||
(apply string-append body) ")"))
|
||||
|
||||
(define (spec-src . body)
|
||||
(string-append
|
||||
"(record v ((x int)))"
|
||||
"(spec (p T)"
|
||||
" (fn s ((self (* const T))) void)"
|
||||
" (fn both ((self (* const T))) void (.s self)))"
|
||||
"(realize (p v)"
|
||||
" (fn s ((self (* const v))) void (return)))"
|
||||
(apply string-append body)))
|
||||
|
||||
(test-group "encapsulation"
|
||||
|
||||
;; A record is a struct plus a typedef of its own name, so the bare
|
||||
@@ -269,12 +280,12 @@ ahead of its pub forms."
|
||||
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
|
||||
(test-assert "though it can point at itself"
|
||||
(emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
|
||||
(test-assert "a function fills a function-pointer field"
|
||||
(test-assert "a function argument becomes the closure its field holds"
|
||||
(emits? (string-append
|
||||
"(fn g ((n int)) int (return n))"
|
||||
"(sum t ((a ((k (fn ((int)) int))))))"
|
||||
"(sum t ((a ((k (closure ((int)) int))))))"
|
||||
"(fn f () t (return (t/a g)))")
|
||||
"(struct tːa){g}"))
|
||||
"ƛint_int_fromfn(g)"))
|
||||
(test-assert "a tag-only sum has no union at all"
|
||||
(not (emits? "(sum light ((red ()) (green ())))" "union")))
|
||||
(test-assert "a sum is declared once"
|
||||
@@ -286,6 +297,104 @@ ahead of its pub forms."
|
||||
(test-assert "and is declared once"
|
||||
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
|
||||
|
||||
;; A spec is a contract that emits nothing; a realization is its
|
||||
;; methods for one type. The refusals are what make it a contract.
|
||||
(test-group "spec and realize"
|
||||
(test-assert "a spec on its own emits nothing"
|
||||
(not (emits? "(spec (p T) (fn s ((a (* const T))) void))" "p")))
|
||||
(test-assert "a realization mangles type, spec and method"
|
||||
(emits? (spec-src "") "void vːpːs"))
|
||||
(test-assert "a default is copied per realizing type"
|
||||
(emits? (spec-src "") "vːpːboth"))
|
||||
(test-assert "and its parameter is substituted"
|
||||
(emits? (spec-src "") "void vːpːboth (const v * self)"))
|
||||
(test-assert "a default calls that type's own required method"
|
||||
(emits? (spec-src "") "vːpːs(self)"))
|
||||
(test-assert "a default is static even when the realization is pub"
|
||||
(emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void)"
|
||||
" (fn d ((a (* const T))) void (.s a)))"
|
||||
"(pub realize (p v)"
|
||||
" (fn s ((a (* const v))) void (return)))")
|
||||
"static void vːpːd"))
|
||||
(test-assert "but a written method is not"
|
||||
(not (emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(pub realize (p v)"
|
||||
" (fn s ((a (* const v))) void (return)))")
|
||||
"static void vːpːs")))
|
||||
(test-assert "a spec method answers to .method"
|
||||
(emits? (spec-src "(fn f () void (var a v #(v : 1)) (.s (& a)))") "vːpːs(&a)"))
|
||||
|
||||
(test-assert "a spec is declared once"
|
||||
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
|
||||
"spec is already declared"))
|
||||
(test-assert "a typedef realizes what its type does"
|
||||
(reports? (string-append (spec-src "") "(typedef alias v)(realize (p alias))")
|
||||
"spec is already realized for"))
|
||||
(test-assert "a type realizes a spec once"
|
||||
(reports? (string-append (spec-src "") "(realize (p v)"
|
||||
" (fn s ((a (* const v))) void (return)))")
|
||||
"spec is already realized for"))
|
||||
(test-assert "a realization names a spec that exists"
|
||||
(reports? "(record v ((x int)))(realize (nope v))" "no such spec"))
|
||||
(test-assert "every required method is provided"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void)"
|
||||
" (fn q ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"realization is missing a method of"))
|
||||
(test-assert "and the missing one is named"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void)"
|
||||
" (fn q ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"q"))
|
||||
(test-assert "a docstring is not a body"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void \"doc\"))"
|
||||
"(realize (p v))")
|
||||
"realization is missing a method of"))
|
||||
(test-assert "nor is a comment"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) int\n"
|
||||
" ;; must be implemented\n"
|
||||
" ))"
|
||||
"(realize (p v))")
|
||||
"realization is missing a method of"))
|
||||
(test-assert "a documented default is still a default"
|
||||
(emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) int \"doc\" (return 1)))"
|
||||
"(realize (p v))")
|
||||
"/* doc */"))
|
||||
(test-assert "a method the spec has not got is refused"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return))"
|
||||
" (fn z ((a (* const v))) void (return)))")
|
||||
"spec has no such method"))
|
||||
(test-assert "a return type has to match the spec"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) int (return 1)))")
|
||||
"return type does not match"))
|
||||
(test-assert "so do the arguments"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a v)) void (return)))")
|
||||
"arguments do not match"))
|
||||
(test-assert "but not on how a pointer is spelled"
|
||||
(emits? (string-append "(record v ((x int)))"
|
||||
"(spec (p T) (fn s ((a * const T)) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"void vːpːs (const v * a)"))
|
||||
(test-assert "a method name already taken on the type is refused"
|
||||
(reports? (string-append "(record v ((x int)))"
|
||||
"(ops v (fn s ((a (* const v))) void (return)))"
|
||||
"(spec (p T) (fn s ((a (* const T))) void))"
|
||||
"(realize (p v) (fn s ((a (* const v))) void (return)))")
|
||||
"method is already defined on")))
|
||||
|
||||
;; match is an if over the tag whose arms bind the payload. What
|
||||
;; it refuses is why it exists.
|
||||
(test-group "match"
|
||||
@@ -308,18 +417,18 @@ ahead of its pub forms."
|
||||
").h")))
|
||||
(test-assert "a scrutinee that is not a path is read once"
|
||||
(emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))")
|
||||
"shape λm0 = mk()"))
|
||||
"shape ƛm0 = mk()"))
|
||||
(test-assert "a path scrutinee is not copied"
|
||||
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
|
||||
"λm0")))
|
||||
"ƛm0")))
|
||||
(test-assert "unless a binder is named like a part of it"
|
||||
(emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))")
|
||||
"shape λm0 = s"))
|
||||
"shape ƛm0 = s"))
|
||||
(test-assert "a macro scrutinee is typed by what it expands to"
|
||||
(emits? (string-append "(defmacro (the a) a)"
|
||||
(sum-src "(match (the s) ((circle (r)) (= out r))"
|
||||
" (else (= out 0.0)))"))
|
||||
"shape λm0 = s"))
|
||||
"shape ƛm0 = s"))
|
||||
(test-assert "a typedef of a sum is matched as the sum"
|
||||
(emits? (string-append
|
||||
"(sum shape ((circle ((r int))) (empty ())))"
|
||||
@@ -392,10 +501,10 @@ ahead of its pub forms."
|
||||
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
|
||||
" (else (= out 0.0)))))")
|
||||
"s.tag == shapeǂcircle"))
|
||||
(test-assert "and so is a lambda's, wherever the lambda stands"
|
||||
(emits? (sum-src "(var c (fn ((shape)) int) (lambda ((v shape)) int"
|
||||
" (match v ((circle (r)) (return 1)) (else (return 0)))))")
|
||||
"v.tag == shapeǂcircle"))
|
||||
(test-assert "and so is a closure's, wherever the closure stands"
|
||||
(emits? (sum-src "(var c (closure () int) (closure () int ((t s))"
|
||||
" (match t ((circle (r)) (return 1)) (else (return 0)))))")
|
||||
"t.tag == shapeǂcircle"))
|
||||
;; a pointer to one was refused, where `.' reads through one
|
||||
;; a variant with fields is a member of the sum's union, which C
|
||||
;; would not take named `int'
|
||||
@@ -449,6 +558,17 @@ ahead of its pub forms."
|
||||
(interface-reports? "(pub var n _ 42)" "write it out"))
|
||||
(test-assert "all of it"
|
||||
(interface-reports? "(pub var p (* _) 0)" "write it out"))
|
||||
;; a spec is seen by importers as a type is: pub, or not at all
|
||||
(test-assert "a pub realization of a private spec is refused"
|
||||
(interface-reports? (string-append "(spec (shown T) (fn show ((self (* const T))) int))"
|
||||
"(pub record m ((c int)))"
|
||||
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")
|
||||
"importers cannot see this spec; make it pub"))
|
||||
(test "and of a pub one is not"
|
||||
'()
|
||||
(interface-of (string-append "(pub spec (shown T) (fn show ((self (* const T))) int))"
|
||||
"(pub record m ((c int)))"
|
||||
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")))
|
||||
(test "a private one is solved where it is"
|
||||
'()
|
||||
(interface-of "(var n _ 42)"))
|
||||
|
||||
@@ -1,132 +1,192 @@
|
||||
;;; The C each declaration comes out as: names, types, variables,
|
||||
;;; initializers, functions and structs. Non-pub ones are static, which
|
||||
;;; the fragments leave out.
|
||||
;;; Types
|
||||
(test-group "fmt-writer"
|
||||
|
||||
(test-group "fmt-c-writer"
|
||||
(test
|
||||
'(const int)
|
||||
(walk-type '(const int)))
|
||||
|
||||
(test-group "names"
|
||||
(test-assert "kebab case is snake case"
|
||||
(emits? "(var kebab-case int)" "int kebab_case;"))
|
||||
;; A Lisp predicate and mutator, in letters C takes
|
||||
(test-assert "a predicate"
|
||||
(emits? "(var ident-start? int)" "int ident_startʔ;"))
|
||||
(test-assert "a mutator"
|
||||
(emits? "(var reset! int)" "int resetꜝ;"))
|
||||
;; The `regex' egg's string-substitute dropped one trailing character
|
||||
;; per multi-byte one, and the C still compiled under the new name
|
||||
(test-assert "a non-ASCII name survives"
|
||||
(emits? "(var naïve-count int)" "int naïve_count;"))
|
||||
(test-assert "wherever the dash is"
|
||||
(emits? "(var aï-b int)" "int aï_b;"))
|
||||
(test-assert "or with none"
|
||||
(emits? "(var ïï int)" "int ïï;"))
|
||||
(test-assert "an arrow inside a name is C's"
|
||||
(emits? "(fn f () void (= this->member 1))" "this->member = 1;")))
|
||||
(test
|
||||
'(%array (const char) 512)
|
||||
(walk-type '(¤ const char 512)))
|
||||
|
||||
;; The operators spelled with the characters names are converted from
|
||||
(test-group "operators"
|
||||
(test-assert "-="
|
||||
(emits? "(fn f ((a int) (b int)) void (-= a b))" "a -= b;"))
|
||||
(test-assert "!"
|
||||
(emits? "(fn f ((a int)) void (if (! a) (return)))" "if (!a)"))
|
||||
(test-assert "!="
|
||||
(emits? "(fn f ((a int) (b int)) void (if (!= a b) (return)))" "if (a != b)")))
|
||||
(test
|
||||
'(%array (float) 512)
|
||||
(walk-type '(¤ (float) 512)))
|
||||
|
||||
(test-group "toplevel comments"
|
||||
(test-assert "are C comments"
|
||||
(emits? ";; hi" "/* hi */"))
|
||||
(test-assert "without the markers or the padding"
|
||||
(emits? ";;; Foo " "/* Foo */")))
|
||||
(test
|
||||
'(%array (const char) 512)
|
||||
(walk-type '(¤ (const char) 512)))
|
||||
|
||||
(test-group "types"
|
||||
(test-assert "an array"
|
||||
(emits? "(var a [const char 512])" "const char a[512];"))
|
||||
(test-assert "whose element type is grouped"
|
||||
(emits? "(var c [(const char) 512])" "const char c[512];"))
|
||||
(test-assert "an unsized one"
|
||||
(emits? "(extern var d [const char])" "extern const char d[];"))
|
||||
(test-assert "a pointer to const"
|
||||
(emits? "(var p (* const char))" "const char * p;"))
|
||||
(test-assert "a const pointer to const"
|
||||
(emits? "(var q (const * const char))" "const char * const q;"))
|
||||
(test-assert "a function pointer"
|
||||
(emits? "(var fp (fn ((int) (float) [const * struct what]) void))"
|
||||
"void (*fp)(int, float, struct what* const []);"))
|
||||
(test-assert "taking an array"
|
||||
(emits? "(var fq (fn ((int) [float]) void))"
|
||||
"void (*fq)(int, float []);"))
|
||||
(test-assert "an array of them"
|
||||
(emits? "(extern var fa [(fn ((int) [float]) void)])"
|
||||
"extern void (*fa[])(int, float []);")))
|
||||
(test
|
||||
'(%array (const char))
|
||||
(walk-type '(¤ const char)))
|
||||
|
||||
(test-group "variables"
|
||||
(test-assert "a local array"
|
||||
(emits? "(fn f () void (var a [float 8]))" "float a[8];"))
|
||||
(test-assert "a pointer, initialized"
|
||||
(emits? "(fn f () void (var n int) (var b (* int) (& n)))" "int * b = &n;"))
|
||||
(test-assert "a pointer to const"
|
||||
(emits? "(fn f () void (var n int) (var c (* const int) (& n)))"
|
||||
"const int * c = &n;"))
|
||||
(test-assert "a struct"
|
||||
(emits? "(fn f () void (var s (struct suc)))" "struct suc s;"))
|
||||
(test-assert "a pointer to a const struct"
|
||||
(emits? "(fn f ((s1 (* const struct suc))) void (var t (* const struct suc) s1))"
|
||||
"const struct suc * t = s1;"))
|
||||
(test-assert "grouped"
|
||||
(emits? "(fn f ((s1 (* const struct suc))) void (var u (* (const struct suc)) s1))"
|
||||
"const struct suc * u = s1;"))
|
||||
(test-assert "a struct from a call"
|
||||
(emits? "(fn f () void (var v (struct suc) (hoge piyo)))"
|
||||
"struct suc v = hoge(piyo);"))
|
||||
(test-assert "a pointer to one"
|
||||
(emits? "(fn f () void (var w (* struct suc) (hoge piyo)))"
|
||||
"struct suc* w = hoge(piyo);")))
|
||||
(test
|
||||
'(%array (const char))
|
||||
(walk-type '(¤ (const char))))
|
||||
|
||||
(test-group "initializers"
|
||||
(test-assert "a bare one is braces"
|
||||
(emits? "(fn f () void (var a [int 2] #(1 2)))" "int a[2] = {1, 2};"))
|
||||
(test-assert "`:' ends the type and makes it a compound literal"
|
||||
(emits? "(fn f () void (var p (struct point) #(struct point : 3 4)))"
|
||||
"struct point p = (struct point){3, 4};"))
|
||||
(test-assert "the type is bare words, as everywhere else"
|
||||
(emits? "(fn f () void (var s (* const char) #(* const char : 65)))"
|
||||
"const char * s = (const char *){65};"))
|
||||
(test-assert "and may be an array type"
|
||||
(emits? "(fn f () void (var t [int 3] #([int 3] : 10 20 30)))"
|
||||
"int t[3] = (int [3]){10, 20, 30};"))
|
||||
(test-assert "`.field value' is a designated initializer, kebab and all"
|
||||
(emits? "(fn f () void (var n (struct named) #(struct named : .n 7 .first-name \"zoe\")))"
|
||||
"(struct named){.n = 7, .first_name = \"zoe\"}"))
|
||||
(test-assert "positional and designated may be mixed"
|
||||
(emits? "(fn f () void (var m (struct point) #(struct point : 1 .y 5)))"
|
||||
"(struct point){1, .y = 5}"))
|
||||
(test-assert "designators work in an untyped initializer too"
|
||||
(emits? "(fn f () void (var o (struct point) #(.y 5)))"
|
||||
"struct point o = {.y = 5};")))
|
||||
(test
|
||||
'(%array float 8)
|
||||
(walk-type '(¤ float 8)))
|
||||
|
||||
(test-group "functions"
|
||||
(test-assert "a prototype may leave its parameters nameless"
|
||||
(emits? "(fn puk ((int) [float 8]) void)" "void puk (int, float [8]);"))
|
||||
(test-assert "an array parameter"
|
||||
(emits? "(fn g ((argc int) (argv [const char])) int (return 0))"
|
||||
"int g (int argc, const char argv[]) {"))
|
||||
(test-assert "a pointer parameter"
|
||||
(emits? "(fn quxu ((bar (* struct piq))) int (return 0))"
|
||||
"int quxu (struct piq * bar) {"))
|
||||
(test-assert "an array of pointers"
|
||||
(emits? "(fn quxu ((bar (* struct piq)) (ploop [* struct tt])) int (return 0))"
|
||||
"int quxu (struct piq * bar, struct tt* ploop[]) {")))
|
||||
(test
|
||||
"Pointer to const char"
|
||||
'(const char *)
|
||||
(walk-type '(* const char)))
|
||||
|
||||
(test-group "structs"
|
||||
(test-assert "names are converted"
|
||||
(emits? "(struct no-kebab ((a int) (f float)))"
|
||||
"struct no_kebab {\n int a;\n float f;\n};"))
|
||||
(test-assert "fields sharing a type share a line, and a field may be a struct"
|
||||
(emits? "(struct settings ((x y w h u32) (colors [struct ((r g b a float)) 4])))"
|
||||
"struct settings {\n u32 x, y, w, h;\n struct{\n float r, g, b, a;\n } colors[4];\n};"))
|
||||
(test-assert "a named one"
|
||||
(emits? "(struct settings ((x y w h u32) (colors [struct color ((r g b a float)) 4])))"
|
||||
" struct color{\n float r, g, b, a;\n } colors[4];"))
|
||||
(test-assert "or a function pointer"
|
||||
(emits? "(struct mega-kebab ((a int) (min (fn ((int) [int]) bool))))"
|
||||
" bool (*min)(int, int []);"))))
|
||||
(test
|
||||
"Const pointer to const char"
|
||||
'(const char * const)
|
||||
(walk-type '(const * const char)))
|
||||
|
||||
(test
|
||||
'(%fun void (int float (%array (struct what * const))))
|
||||
(walk-type '(fn ((int) (float) (¤ (const * struct what))) void)))
|
||||
|
||||
(test
|
||||
'(%fun void (int (%array float) (%array (struct what * const))))
|
||||
(walk-type '(fn ((int) (¤ float) (¤ (const * struct what))) void)))
|
||||
|
||||
(test
|
||||
'(%array (%fun void (int (%array float) (%array (struct what * const)))))
|
||||
(walk-type '(¤ (fn ((int) (¤ float) (¤ (const * struct what))) void))))
|
||||
|
||||
;; Type convert to C
|
||||
(test
|
||||
'(int)
|
||||
(type-convert-to-c '(int)))
|
||||
|
||||
(test
|
||||
'(* int)
|
||||
(type-convert-to-c '(int *)))
|
||||
|
||||
(test
|
||||
'(* const int)
|
||||
(type-convert-to-c '(const int *)))
|
||||
|
||||
(test
|
||||
'(const * const char)
|
||||
(type-convert-to-c '(const char * const)))
|
||||
|
||||
;;; Variable defs
|
||||
(test
|
||||
'(%var (%array float 8) a)
|
||||
(walk-var '(var a (¤ float 8))))
|
||||
|
||||
(test
|
||||
'(%var (int *) a (& n))
|
||||
(walk-var '(var a (* int) (& n))))
|
||||
|
||||
(test
|
||||
'(%var (const int *) a (& n))
|
||||
(walk-var '(var a (* const int) (& n))))
|
||||
|
||||
(test
|
||||
'(%var (struct suc) s)
|
||||
(walk-var '(var s (struct suc))))
|
||||
|
||||
(test
|
||||
'(%var (const struct suc *) s s1)
|
||||
(walk-var '(var s (* const struct suc) s1)))
|
||||
|
||||
(test
|
||||
'(%var (const struct suc *) s s1)
|
||||
(walk-var '(var s (* (const struct suc)) s1)))
|
||||
|
||||
(test
|
||||
'(%var (struct suc) s (hoge piyo))
|
||||
(walk-var '(var s (struct suc) (hoge piyo))))
|
||||
|
||||
(test
|
||||
'(%var (struct suc *) s (hoge piyo))
|
||||
(walk-var '(var s (* struct suc) (hoge piyo))))
|
||||
|
||||
;;; Initializers and compound literals
|
||||
(test "a bare initializer is unchanged"
|
||||
'#(1 2)
|
||||
(walk-expr '#(1 2)))
|
||||
|
||||
(test "`:' ends the type and makes it a compound literal"
|
||||
'(%compound (struct point) 3 4)
|
||||
(walk-expr '#(struct point : 3 4)))
|
||||
|
||||
(test "the type is bare words, as everywhere else"
|
||||
'(%compound (const char *) 65)
|
||||
(walk-expr '#(* const char : 65)))
|
||||
|
||||
(test "and may be an array type"
|
||||
'(%compound (%array int 3) 10 20 30)
|
||||
(walk-expr '#(¤ int 3 : 10 20 30)))
|
||||
|
||||
(test "a grouped type is unwrapped the way a declaration's is"
|
||||
'(%compound (%array int 3) 10)
|
||||
(walk-expr '#((¤ int 3) : 10)))
|
||||
|
||||
(test "`.field value' is a designated initializer, kebab and all"
|
||||
'(%compound (struct named) (%designate n 7) (%designate first_name "zoe"))
|
||||
(walk-expr '#(struct named : .n 7 .first-name "zoe")))
|
||||
|
||||
(test "positional and designated may be mixed"
|
||||
'(%compound (struct point) 1 (%designate y 5))
|
||||
(walk-expr '#(struct point : 1 .y 5)))
|
||||
|
||||
(test "designators work in an untyped initializer too"
|
||||
'#((%designate y 5))
|
||||
(walk-expr '#(.y 5)))
|
||||
|
||||
;;; Fn defs
|
||||
(test
|
||||
'(%fun void puk ((int #f) ((%array float 8) #f)))
|
||||
(walk-fn-def '(fn puk ((int) (¤ float 8)) void)))
|
||||
|
||||
(test
|
||||
'(%fun int main ((int argc) ((%array (const char)) argv))
|
||||
(return 0))
|
||||
(walk-fn-def
|
||||
'(fn main ((argc int) (argv (¤ const char))) int
|
||||
(return 0))))
|
||||
(test
|
||||
'(%fun int quxu (((struct piq *) bar))
|
||||
(return 0))
|
||||
(walk-fn-def
|
||||
'(fn quxu ((bar (* struct piq))) int
|
||||
(return 0))))
|
||||
|
||||
(test
|
||||
'(%fun int quxu (((struct piq *) bar) ((%array (struct tt *)) ploop))
|
||||
(return 0))
|
||||
(walk-fn-def
|
||||
'(fn quxu ((bar (* struct piq)) (ploop (¤ * struct tt))) int
|
||||
(return 0))))
|
||||
|
||||
;; Structs
|
||||
(test
|
||||
'(struct no_kebab ((int a) (float f)))
|
||||
(walk-struct '(struct no-kebab ((a int) (f float)))))
|
||||
|
||||
(test
|
||||
'(struct settings ((u32 x y w h)
|
||||
((%array (struct ((float r g b a))) 4) colors)))
|
||||
(walk-struct
|
||||
'(struct settings
|
||||
((x y w h u32)
|
||||
(colors [¤ struct ((r g b a float)) 4])))))
|
||||
|
||||
(test
|
||||
'(struct settings ((u32 x y w h)
|
||||
((%array (struct color ((float r g b a))) 4) colors)))
|
||||
(walk-struct
|
||||
'(struct settings
|
||||
((x y w h u32)
|
||||
(colors [¤ struct color ((r g b a float)) 4])))))
|
||||
|
||||
(test
|
||||
'(struct mega_kebab ((int a)
|
||||
((struct ((int year) (int month) (int day))) dob)
|
||||
((%fun bool (int (%array int))) min)))
|
||||
(walk-struct '(struct mega-kebab
|
||||
((a int)
|
||||
(dob (struct ((year int)
|
||||
(month int)
|
||||
(day int))))
|
||||
(min (fn ((int) (¤ int)) bool)))))))
|
||||
|
||||
190
tests/infer.scm
190
tests/infer.scm
@@ -3,7 +3,7 @@
|
||||
;;; Names registered in the type database are prefixed, since the
|
||||
;;; database is one table shared by every suite in the linked binary.
|
||||
|
||||
(import infer types)
|
||||
(import infer types (chicken sort))
|
||||
|
||||
;;; Parse and print a surface type again. Everything in this suite goes
|
||||
;;; through this pair, which is deliberate: they are the only thing the
|
||||
@@ -85,10 +85,23 @@
|
||||
|
||||
;; Each _ is its own variable: solving one must not solve the rest.
|
||||
(let ((t (parse-type '(fn ((_)) _))))
|
||||
(unify t (parse-type '(fn ((int)) _)) #f)
|
||||
(unify (car (fn-args t)) (parse-type 'int) #f)
|
||||
(test "one hole at a time" '(fn ((int)) _) (unparse-type t))))
|
||||
|
||||
(test-group "decay"
|
||||
(test-group "structure"
|
||||
(test-assert "a pointer is a pointer" (ptr-type? (parse-type '(* char))))
|
||||
(test "and knows what it points at" 'char
|
||||
(unparse-type (ptr-target (parse-type '(* char)))))
|
||||
(test "quals sit on the level they were written at" '(const)
|
||||
(ptr-quals (parse-type '(const * char))))
|
||||
(test "an unsized array has no size" #f (array-size (parse-type '(¤ int))))
|
||||
(test "a sized one does" 16 (array-size (parse-type '(¤ int 16))))
|
||||
(test "an aggregate is nominal" 'point (agg-name (parse-type '(struct point))))
|
||||
(test-assert "a variadic signature says so"
|
||||
(fn-variadic? (parse-type '(fn ((* const char) (...)) int))))
|
||||
(test-assert "and a plain one does not"
|
||||
(not (fn-variadic? (parse-type '(fn ((int)) int)))))
|
||||
|
||||
;; decay: the conversion C performs at a call site, an operand of
|
||||
;; `+', or the left half of a subscript.
|
||||
(test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16)))))
|
||||
@@ -102,7 +115,7 @@
|
||||
(test-error "and not with another one"
|
||||
(unify (parse-type 'int) (parse-type 'char) #f))
|
||||
|
||||
(let ((a (parse-type '_)))
|
||||
(let ((a (fresh-tvar)))
|
||||
(unify a (parse-type '(* const char)) #f)
|
||||
(test "a variable takes the shape it is unified with"
|
||||
'(* const char) (unparse-type a)))
|
||||
@@ -112,8 +125,8 @@
|
||||
(unify p (parse-type '(* int)) #f)
|
||||
(test "a partial type is completed by one step" '(* int) (unparse-type p)))
|
||||
|
||||
(let ((a (parse-type '_))
|
||||
(b (parse-type '_)))
|
||||
(let ((a (fresh-tvar))
|
||||
(b (fresh-tvar)))
|
||||
(unify a b #f)
|
||||
(unify b (parse-type 'double) #f)
|
||||
(test "two variables joined then solved" 'double (unparse-type a)))
|
||||
@@ -139,7 +152,168 @@
|
||||
(add-typedef 'i-count '(typedef i-count int))
|
||||
(test-assert "a typedef unifies with its target"
|
||||
(unify (parse-type 'i-count) (parse-type 'int) #f))
|
||||
(let ((a (parse-type '_)))
|
||||
(let ((a (fresh-tvar)))
|
||||
(unify a (parse-type 'i-count) #f)
|
||||
(test "and keeps its name when it is the one printed"
|
||||
'i-count (unparse-type a)))))
|
||||
'i-count (unparse-type a)))
|
||||
|
||||
(test-group "the unknown type"
|
||||
(test-assert "? is consistent with anything"
|
||||
(unify the-unknown-type (parse-type '(struct point)) #f))
|
||||
(test-assert "in either order"
|
||||
(unify (parse-type 'int) the-unknown-type #f))
|
||||
;; ...and binds nothing. Degrading to ? is what keeps an
|
||||
;; unparsed C declaration from poisoning everything it touches.
|
||||
(let ((a (fresh-tvar)))
|
||||
(unify a the-unknown-type #f)
|
||||
(test "a variable met with ? stays open" '_ (unparse-type a))))
|
||||
|
||||
(test-group "occurs check"
|
||||
;; Unreachable without recursive types, and the alternative to
|
||||
;; having it is not an error but a hang.
|
||||
(let ((a (fresh-tvar)))
|
||||
(test-error "a variable may not contain itself"
|
||||
(unify a (make-ptr a (list)) #f))))
|
||||
|
||||
(test-group "rigid variables"
|
||||
(let ((r (fresh-rigid-tvar))
|
||||
(a (fresh-tvar)))
|
||||
(test-error "a type parameter does not unify with a type"
|
||||
(unify r (parse-type 'int) #f))
|
||||
(test-assert "an ordinary variable binds to it instead"
|
||||
(unify a r #f))
|
||||
;; An unsolved variable resolves to itself.
|
||||
(test-assert "it is still open" (tvar? (resolve r))))
|
||||
;; ...and the same the other way round: it is which side is free
|
||||
;; that decides, not which side was written first.
|
||||
(let ((r (fresh-rigid-tvar))
|
||||
(a (fresh-tvar)))
|
||||
(test-assert "rigid first binds the free one" (unify r a #f))
|
||||
(test-assert "to the parameter itself" (eq? r (resolve a))))
|
||||
(let ((r1 (fresh-rigid-tvar))
|
||||
(r2 (fresh-rigid-tvar)))
|
||||
(test-error "two parameters do not unify with each other"
|
||||
(unify r1 r2 #f)))))
|
||||
|
||||
(test-group "constraints"
|
||||
(test #t (entails? 'numeric (parse-type 'int)))
|
||||
(test #t (entails? 'numeric (parse-type '(unsigned long))))
|
||||
(test #t (entails? 'integral (parse-type 'char)))
|
||||
(test #f (entails? 'integral (parse-type 'double)))
|
||||
(test #t (entails? 'floating (parse-type 'double)))
|
||||
(test #f (entails? 'floating (parse-type 'int)))
|
||||
(test #f (entails? 'numeric (parse-type '(* char))))
|
||||
(test #t (entails? 'scalar (parse-type '(* char))))
|
||||
(test #f (entails? 'numeric (parse-type 'void)))
|
||||
|
||||
(add-enum 'i-mood '(enum i-mood (glad sad)))
|
||||
(test "an enum is an integer" #t (entails? 'integral (parse-type '(enum i-mood))))
|
||||
|
||||
;; The third answer, and the important one. A name from a header
|
||||
;; might well be numeric; #f would reject working programs and #t
|
||||
;; would invent knowledge.
|
||||
(test "an unparsed C name is not known either way"
|
||||
'unknown (entails? 'numeric (parse-type 'size-t)))
|
||||
(test "nor is an open variable" 'unknown (entails? 'numeric (fresh-tvar)))
|
||||
(test "? entails nothing, but says so quietly"
|
||||
'unknown (entails? 'numeric the-unknown-type))
|
||||
|
||||
;; A typedef is entailed by what it resolves to, so an alias cannot
|
||||
;; sneak past a constraint its target would fail.
|
||||
(add-typedef 'i-len '(typedef i-len int))
|
||||
(test "a typedef is judged by its target" #t (entails? 'numeric (parse-type 'i-len)))
|
||||
|
||||
;; A constrained variable checks its classes at the moment it is
|
||||
;; solved, not at the end.
|
||||
(let ((a (fresh-tvar '(numeric))))
|
||||
(test-error "solving to a type that fails the class is an error"
|
||||
(unify a (parse-type '(* char)) #f)))
|
||||
(let ((a (fresh-tvar '(numeric))))
|
||||
(test-assert "and to one that satisfies it is not"
|
||||
(unify a (parse-type 'double) #f)))
|
||||
;; ...but an unparsed name is not a failure, it is an absence of
|
||||
;; knowledge, and must stay silent.
|
||||
(let ((a (fresh-tvar '(numeric))))
|
||||
(test-assert "an unparsed C name does not trip a constraint"
|
||||
(unify a (parse-type 'GLuint) #f)))
|
||||
|
||||
;; Joining two variables joins what is known about both.
|
||||
(let ((a (fresh-tvar '(numeric)))
|
||||
(b (fresh-tvar '(integral))))
|
||||
(unify a b #f)
|
||||
(test "constraints merge when variables do"
|
||||
'("integral" "numeric")
|
||||
(sort (map symbol->string (tvar-classes b)) string<?)))
|
||||
|
||||
(test-group "defaulting"
|
||||
(let ((a (fresh-tvar '(numeric))))
|
||||
(default-type-variables! a #f)
|
||||
(test "an open numeric is an int" 'int (unparse-type a)))
|
||||
(let ((a (fresh-tvar '(floating))))
|
||||
(default-type-variables! a #f)
|
||||
(test "an open floating is a double" 'double (unparse-type a)))
|
||||
(let ((a (fresh-tvar)))
|
||||
(test "a variable with nothing known about it cannot be defaulted"
|
||||
#f (default-type-variables! a #f))
|
||||
(test "and stays a hole, for the caller to complain about"
|
||||
'_ (unparse-type a)))
|
||||
;; Defaulting reaches into the structure, since the hole may be
|
||||
;; anywhere: `(var p (* _) ...)'.
|
||||
(let ((t (parse-type '(* _))))
|
||||
(unify (ptr-target t) (fresh-tvar '(numeric)) #f)
|
||||
(default-type-variables! t #f)
|
||||
(test "and it reaches inside a type" '(* int) (unparse-type t))))
|
||||
|
||||
(test-group "user classes"
|
||||
;; A trait bound is the same shape as `numeric', discharged by
|
||||
;; the same procedure -- that is the point of one representation.
|
||||
;; It differs in two rules, and both are stated while there is
|
||||
;; still only one kind of constraint to state them about.
|
||||
(register-class! 'i-ord #f #f #t)
|
||||
(add-struct 'i-circle '(struct i-circle ((r int))))
|
||||
(test "no instance, no entailment" #f (entails? 'i-ord (parse-type '(struct i-circle))))
|
||||
(add-instance! 'i-ord (parse-type '(struct i-circle)))
|
||||
(test "and with one, entailment" #t (entails? 'i-ord (parse-type '(struct i-circle))))
|
||||
;; Instances key on the resolved type, so an alias cannot be
|
||||
;; registered twice under two names.
|
||||
(add-typedef 'i-circle-alias '(typedef i-circle-alias (struct i-circle)))
|
||||
(test "an alias of an instance is the same instance"
|
||||
#t (entails? 'i-ord (parse-type 'i-circle-alias)))
|
||||
;; Decision 2: static dispatch cannot select an instance for a
|
||||
;; type it does not know, so a strict class says no to ? rather
|
||||
;; than shrugging the way `numeric' does.
|
||||
(test "a strict class refuses ?" #f (entails? 'i-ord the-unknown-type))
|
||||
(test "where a lenient one abstains" 'unknown (entails? 'numeric the-unknown-type))
|
||||
;; ...and it has no default to fall back on.
|
||||
(let ((a (fresh-tvar '(i-ord))))
|
||||
(test-error "an unresolved user constraint is an error, not a guess"
|
||||
(default-type-variables! a #f)))))
|
||||
|
||||
(test-group "schemes"
|
||||
;; Nothing generalizes yet. The shape is here because a scheme
|
||||
;; without a constraint list is the wrong shape for every bounded
|
||||
;; generic, and because instantiation is how a generic body gets
|
||||
;; fresh cells instead of a second type for the same one.
|
||||
(let* ((a (fresh-tvar '(numeric)))
|
||||
(id (make-fn-type a (list a) #f))
|
||||
(s (generalize id (list))))
|
||||
(test "the free variable is quantified" 1 (length (scheme-vars s)))
|
||||
(test "carrying its class as the scheme's context"
|
||||
'((numeric)) (list (map car (scheme-constraints s))))
|
||||
|
||||
(let ((one (instantiate s))
|
||||
(two (instantiate s)))
|
||||
(test "an instantiation is still open" '(fn ((_)) _) (unparse-type one))
|
||||
(unify (fn-ret one) (parse-type 'int) #f)
|
||||
(test "solving one instantiation" '(fn ((int)) int) (unparse-type one))
|
||||
(test "leaves the other alone" '(fn ((_)) _) (unparse-type two))
|
||||
(test "and the scheme itself untouched" '(fn ((_)) _) (unparse-type id))))
|
||||
|
||||
(let* ((a (fresh-tvar))
|
||||
(b (fresh-tvar))
|
||||
(s (generalize (make-fn-type a (list b) #f) (list b))))
|
||||
(test "a variable free in the environment is not quantified"
|
||||
1 (length (scheme-vars s)))
|
||||
(let ((inst (instantiate s)))
|
||||
(unify (car (fn-args inst)) (parse-type 'char) #f)
|
||||
(test "so instantiating solves it for everyone" 'char (unparse-type b))))))
|
||||
|
||||
@@ -17,13 +17,14 @@
|
||||
;;; get the true source line) and in the C output (to get the line the
|
||||
;;; directives claim). The two must agree.
|
||||
|
||||
(import (chicken pathname)
|
||||
(chicken port)
|
||||
(import (chicken port)
|
||||
(chicken string)
|
||||
srfi-1
|
||||
srfi-13
|
||||
fmt-c-writer
|
||||
semen)
|
||||
reader
|
||||
semen
|
||||
utils)
|
||||
|
||||
;;; ------------------------------------------------------------------
|
||||
;;; Fixture. Line numbers are in the trailing comments; keep them
|
||||
@@ -97,9 +98,15 @@
|
||||
;;; Pipeline and #line accounting
|
||||
|
||||
(define (compile-to-c source #!optional (file "fixture.sex"))
|
||||
"Run reader -> semen -> writer on SOURCE, read from FILE,
|
||||
returning the generated C."
|
||||
(let ((forms (read-source source file)))
|
||||
"Run reader -> semen -> writer on SOURCE, returning the generated C.
|
||||
parse-all is called directly rather than through read-raw-forms so the
|
||||
fixture can be given a file name: a location carries one, and the
|
||||
file is what makes an imported module report itself rather than the unit
|
||||
that imported it."
|
||||
(let ((forms (with-input-from-string source
|
||||
(lambda ()
|
||||
(parameterize ((current-source-file file))
|
||||
(parse-all (current-input-port)))))))
|
||||
(with-output-to-string
|
||||
(lambda () (emit-c (semen-process forms))))))
|
||||
|
||||
@@ -231,26 +238,23 @@ after that is one more. Lines before the first directive get #f."
|
||||
;; an `if' arm is a statement only where the `if' is one: a
|
||||
;; directive between `?' and `:' does not compile
|
||||
(maps "conditional argument" "123")
|
||||
;; a bare 123 may be a digit run of the fixture's path, in every #line
|
||||
(test-assert "holds no directive"
|
||||
(let ((start (string-contains c-out "mvar < 123")))
|
||||
(not (string-contains (substring c-out start (string-contains c-out ": 125" start))
|
||||
(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.
|
||||
(test-group "file name"
|
||||
(test "every directive names the fixture"
|
||||
(list "fixture.sex")
|
||||
(list "\"fixture.sex\"")
|
||||
(delete-duplicates
|
||||
(map (lambda (quoted)
|
||||
(pathname-strip-directory (string-trim-both quoted #\")))
|
||||
(filter values (map directive-file (split-lines c-out))))))
|
||||
(filter values (map directive-file (split-lines c-out)))))
|
||||
;; it was pasted between quotes as it came: a quote ended it, a
|
||||
;; backslash began an escape, and ??= was a trigraph
|
||||
(test-assert "and is written the way C writes a string"
|
||||
(string-suffix? "/we\\\"ird\\\\a?\\?=.sex\""
|
||||
(test "and is written the way C writes a string"
|
||||
"\"we\\\"ird\\\\dir/a?\\?=.sex\""
|
||||
(directive-file
|
||||
(find directive-line
|
||||
(split-lines (compile-to-c "(fn f () int (return 1))"
|
||||
"we\"ird\\a??=.sex"))))))))
|
||||
"we\"ird\\dir/a??=.sex")))))))
|
||||
|
||||
@@ -1,38 +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 file)
|
||||
(chicken pathname)
|
||||
(import (chicken pathname)
|
||||
(chicken process-context)
|
||||
semen
|
||||
sex-modules)
|
||||
|
||||
(define (write-module dir name)
|
||||
(create-directory dir #t)
|
||||
(with-output-to-file (make-pathname dir name "sex")
|
||||
(lambda () (display "(pub fn found () int)"))))
|
||||
|
||||
(test-group "module path"
|
||||
;; make-absolute-pathname took `src' for a directory under the root,
|
||||
;; and an import searched /src/
|
||||
(let ((start (current-directory))
|
||||
(scratch (create-temporary-directory)))
|
||||
(write-module (make-pathname scratch "src") "mp-relative")
|
||||
(write-module (make-pathname scratch "lib") "mp-absolute")
|
||||
(change-directory scratch)
|
||||
(set-environment-variable! "SEX_MODULE_PATH"
|
||||
(string-append "src:" (make-pathname scratch "lib")))
|
||||
(set-environment-variable! "SEX_MODULE_PATH" "src:/abs/lib")
|
||||
(load-persistent-module-paths)
|
||||
(change-directory start)
|
||||
|
||||
(test "a relative entry is from the working directory"
|
||||
'((pub fn found () int))
|
||||
(semen-process '((import mp-relative))))
|
||||
(make-absolute-pathname (current-directory) "src")
|
||||
(second (get-module-paths)))
|
||||
(test "an absolute one is as written"
|
||||
'((pub fn found () int))
|
||||
(semen-process '((import mp-absolute))))
|
||||
"/abs/lib"
|
||||
(third (get-module-paths)))
|
||||
|
||||
(set-environment-variable! "SEX_MODULE_PATH" "")
|
||||
(load-persistent-module-paths)
|
||||
(unset-environment-variable! "SEX_MODULE_PATH")
|
||||
(delete-directory scratch #t)))
|
||||
(unset-environment-variable! "SEX_MODULE_PATH"))
|
||||
|
||||
@@ -10,8 +10,11 @@
|
||||
;;;
|
||||
;;; It also checks what only a second translation unit can check: that an
|
||||
;;; imported type reaches the type database, by expanding a macro that
|
||||
;;; reads the imported struct's fields; and that a record can cross as a
|
||||
;;; handle alone, its fields left behind and its methods still found.
|
||||
;;; reads the imported struct's fields; and that a closure type crossing
|
||||
;;; the boundary works both ways -- one built in the module and called
|
||||
;;; here, one built here and called there, through a code pointer that is
|
||||
;;; static in the other object. And that a record can cross as a handle
|
||||
;;; 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. And a type the
|
||||
@@ -35,7 +38,6 @@
|
||||
;;;
|
||||
;;; gen/made writes its pub forms by macro calls, which are expanded when
|
||||
;;; its interface is read; the macros it used for that stay its own.
|
||||
;;; gen/broken's call raises, which reading its interface reports.
|
||||
;;;
|
||||
;;; make check-modules
|
||||
|
||||
@@ -89,14 +91,6 @@
|
||||
(irregex-match ".*/greet-app: greet-app\\.sex .*/greet\\.sex .*/ledger\\.sex"
|
||||
(call-with-input-file (built "greet-app.d") read-line)))
|
||||
|
||||
;;; Each module has a rule of its own, so make takes one deleted since as
|
||||
;;; out of date rather than as a file it has no rule to make
|
||||
(test "and gives each a rule of its own"
|
||||
'("greet.sex:" "ledger.sex:")
|
||||
(filter-map (lambda (line)
|
||||
(and (irregex-match ".*\\.sex:" line) (pathname-strip-directory line)))
|
||||
(call-with-input-file (built "greet-app.d") read-lines)))
|
||||
|
||||
(test "a module's interface does not depend on where sexc runs"
|
||||
'("(record spine)" "(import page)")
|
||||
(take (or (output-of sexc "--public-interface" "shelf/book.sex") '()) 2))
|
||||
@@ -136,11 +130,11 @@
|
||||
'("made 42 7 1 2")
|
||||
(output-of (built "made-app")))
|
||||
|
||||
;;; ...but a call failing for other than a name its module declares fails
|
||||
;;; there as well
|
||||
(test-assert "a toplevel macro call that raises fails the interface too"
|
||||
(let ((err (error-of sexc "--public-interface" "gen/broken.sex")))
|
||||
(and err (irregex-search "broken\\.sex:8: expanding boom: nope" err))))
|
||||
;;; ...while a realization of a spec importers cannot see is refused by
|
||||
;;; the module that writes it, not by an importer naming it first
|
||||
(test-assert "a pub realization of a spec imported without pub is refused"
|
||||
(let ((err (error-of sexc "specs/money.sex" "-C" "-o" "-")))
|
||||
(and err (irregex-search "money.sex:8: importers cannot see this spec" err) #t)))
|
||||
|
||||
(test "the app runs through both"
|
||||
'("hello, world"
|
||||
@@ -149,7 +143,9 @@
|
||||
"text times "
|
||||
"text times "
|
||||
"mood 1"
|
||||
"closure 15 21 201"
|
||||
"vec2 7 7"
|
||||
"vec2(3 4)"
|
||||
"tally 2"
|
||||
"board 42"
|
||||
"ledger 2"
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
;;; A toplevel macro call failing for what it is, not for asking after a
|
||||
;;; name declared here: an importer is told so, as this module is
|
||||
(defmacro (boom)
|
||||
(error "nope"))
|
||||
|
||||
(pub fn fine () int (return 1))
|
||||
|
||||
(boom)
|
||||
@@ -27,10 +27,19 @@
|
||||
(var m (enum mood) grumpy)
|
||||
(printf "mood %d\n" m)
|
||||
|
||||
(var add-10 (closure ((int)) int) (make-adder 10))
|
||||
(printf "closure %d %d" (add-10 5) (apply-twice add-10 1))
|
||||
(var base int 100)
|
||||
(var here (closure ((int)) int)
|
||||
(closure ((x int)) int (base) (return (+ base x))))
|
||||
(printf " %d\n" (apply-twice here 1))
|
||||
|
||||
;; the bare record name, then the method both ways round
|
||||
(var v vec2 #(vec2 : 3 4))
|
||||
(printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v)))
|
||||
|
||||
(.show-line v)
|
||||
|
||||
;; only the handle crossed: (. t n) here is an incomplete type
|
||||
(var t (* tally) (tally/make))
|
||||
(.bump t)
|
||||
|
||||
@@ -62,6 +62,19 @@
|
||||
(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
|
||||
;;; says so.
|
||||
(pub fn make-adder ((n int)) (closure ((int)) int)
|
||||
(return (closure ((b int)) int (n)
|
||||
(return (+ n b)))))
|
||||
|
||||
;;; The other direction: a closure built by the importer, whose code
|
||||
;;; pointer is static in *its* object, called from here
|
||||
(pub fn apply-twice ((f (closure ((int)) int)) (x int)) int
|
||||
(return (f (f x))))
|
||||
|
||||
;;; A record and an ops block crossing the boundary. The record has to
|
||||
;;; arrive as the struct *and* its typedef, or the bare name does not
|
||||
;;; work there; the ops block has to arrive as a block rather than as
|
||||
@@ -97,6 +110,20 @@
|
||||
;;; called, so there is no function for two units to both define.
|
||||
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
|
||||
|
||||
;;; A spec and a realization over the boundary. The written method
|
||||
;;; travels as a prototype and keeps external linkage; the default
|
||||
;;; does not travel at all -- the importer synthesizes its own static
|
||||
;;; copy from the spec, which is why a default is static even here.
|
||||
(pub spec (printable T)
|
||||
(fn show ((self (* const T))) void)
|
||||
(fn show-line ((self (* const T))) void
|
||||
(.show self)
|
||||
(printf "\n")))
|
||||
|
||||
(pub realize (printable vec2)
|
||||
(fn show ((self (* const vec2))) void
|
||||
(printf "vec2(%d %d)" (. self x) (. self y))))
|
||||
|
||||
;;; Not `pub': invisible to importers, and static in the generated C.
|
||||
(fn unused-helper () void
|
||||
(printf "private\n"))
|
||||
|
||||
9
tests/modules/specs/money.sex
Normal file
9
tests/modules/specs/money.sex
Normal file
@@ -0,0 +1,9 @@
|
||||
;;; Imports shown without pub, so its importers cannot see the spec
|
||||
;;; this realizes: refused here, rather than in whichever importer
|
||||
;;; names money before shown
|
||||
(import shown)
|
||||
|
||||
(pub record money ((cents int)))
|
||||
|
||||
(pub realize (shown money)
|
||||
(fn show ((self (* const money))) int (return (. self cents))))
|
||||
2
tests/modules/specs/shown.sex
Normal file
2
tests/modules/specs/shown.sex
Normal file
@@ -0,0 +1,2 @@
|
||||
(pub spec (shown T)
|
||||
(fn show ((self (* const T))) int))
|
||||
@@ -1,75 +0,0 @@
|
||||
;;; Sex source in, C or the error it raises out, the way sexc runs
|
||||
;;; the pipeline: reader -> semen -> writer. The suites after this one
|
||||
;;; check the compiler through these.
|
||||
|
||||
(import (chicken condition)
|
||||
(chicken file)
|
||||
(chicken pathname)
|
||||
(chicken port)
|
||||
srfi-13
|
||||
fmt-c-writer
|
||||
reader
|
||||
semen)
|
||||
|
||||
(define (read-source source #!optional (name "codegen.sex"))
|
||||
"The forms of SOURCE, read from a file NAME, which is what the
|
||||
locations then name: (read-source \"(f)\") reads (f) from codegen.sex."
|
||||
(let* ((dir (create-temporary-directory))
|
||||
(file (make-pathname dir name)))
|
||||
(with-output-to-file file (lambda () (display source)))
|
||||
(let ((forms (read-from-file file)))
|
||||
(delete-directory dir #t)
|
||||
forms)))
|
||||
|
||||
(define (sex->c source)
|
||||
"Compile SOURCE, a string of Sex, and return the generated C."
|
||||
(let ((forms (read-source source)))
|
||||
(with-output-to-string
|
||||
(lambda ()
|
||||
(parameterize ((sex-line-directives 'none))
|
||||
(emit-c (semen-process forms)))))))
|
||||
|
||||
;;; Warnings are what `warns?' is for; a test that happens to trip one
|
||||
;;; should not print it
|
||||
(define (silently thunk)
|
||||
"THUNK's value, with whatever it wrote to stderr dropped."
|
||||
(let ((value #f))
|
||||
(with-error-output-to-string (lambda () (set! value (thunk))))
|
||||
value))
|
||||
|
||||
(define (emits? source fragment)
|
||||
(and (string-contains (silently (lambda () (sex->c source))) fragment) #t))
|
||||
|
||||
(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 (thunk) #f)))
|
||||
|
||||
(define (fails-with? thunk fragment)
|
||||
(let ((m (failure-message thunk)))
|
||||
(and m (string-contains m fragment) #t)))
|
||||
|
||||
(define (reports? source fragment)
|
||||
(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 (warnings source)
|
||||
"What compiling SOURCE writes to stderr."
|
||||
(with-error-output-to-string (lambda () (sex->c source))))
|
||||
|
||||
(define (warns? source fragment)
|
||||
(and (string-contains (warnings source) fragment) #t))
|
||||
@@ -1,7 +1,7 @@
|
||||
(import
|
||||
test)
|
||||
|
||||
(include-relative "pipeline.scm")
|
||||
(include-relative "basic.scm")
|
||||
(include-relative "semen.scm")
|
||||
(include-relative "reader.scm")
|
||||
(include-relative "fmt-c-writer.scm")
|
||||
@@ -9,6 +9,7 @@
|
||||
(include-relative "line-directives.scm")
|
||||
(include-relative "codegen.scm")
|
||||
(include-relative "encapsulation.scm")
|
||||
(include-relative "args.scm")
|
||||
(include-relative "module-path.scm")
|
||||
(include-relative "types.scm")
|
||||
(include-relative "infer.scm")
|
||||
|
||||
@@ -1,8 +1,35 @@
|
||||
(import semen
|
||||
(import srfi-69
|
||||
semen
|
||||
types)
|
||||
|
||||
(define print-str-fn
|
||||
'(fn print-str ((s string)) void
|
||||
(printf "%s" s)))
|
||||
|
||||
(define sum-fn
|
||||
'(pub fn sum ((a int) (b int)) float
|
||||
(return (cast (+ a b) float))))
|
||||
|
||||
(test-group "semen"
|
||||
;;; Macro expansion
|
||||
(test-assert (sex-fn? print-str-fn))
|
||||
(test #f (sex-fn-public? print-str-fn))
|
||||
(test 'void (sex-fn-return-type print-str-fn))
|
||||
(test 'print-str (sex-fn-name print-str-fn))
|
||||
(test '((s string)) (sex-fn-arglist print-str-fn))
|
||||
(test '(fn print-str ((s string)) void) (sex-fn-prototype print-str-fn))
|
||||
(test '((printf "%s" s)) (sex-fn-body print-str-fn))
|
||||
|
||||
(test-assert (sex-fn? sum-fn))
|
||||
(test #t (sex-fn-public? sum-fn))
|
||||
(test 'float (sex-fn-return-type sum-fn))
|
||||
(test 'sum (sex-fn-name sum-fn))
|
||||
(test '((a int) (b int)) (sex-fn-arglist sum-fn))
|
||||
(test '(pub fn sum ((a int) (b int)) float) (sex-fn-prototype sum-fn))
|
||||
(test '((return (cast (+ a b) float))) (sex-fn-body sum-fn))
|
||||
|
||||
(test-assert (sex-fn? '(extern fn foo () void)))
|
||||
(test 'foo (sex-fn-name '(extern fn foo () void)))
|
||||
(test #f (sex-fn? '(struct point ((x int)))))
|
||||
|
||||
(let ((sex-code
|
||||
'((defmacro (sum-var name a b c)
|
||||
@@ -12,6 +39,17 @@
|
||||
|
||||
(test '((var v 6)) (semen-process sex-code)))
|
||||
|
||||
;;; Macro expansion
|
||||
|
||||
(define (form-identity form env)
|
||||
form)
|
||||
|
||||
(test 'a (walk-form 'a form-identity (make-hash-table)))
|
||||
(test '(a b c) (walk-form '(a b c) form-identity (make-hash-table)))
|
||||
|
||||
(test 'a (macro-expand 'a))
|
||||
(test '(a b c) (macro-expand '(a b c)))
|
||||
|
||||
(let ((sex-code-macro
|
||||
'((defmacro (x10 a)
|
||||
`(* 10 ,a))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
(compilation "-- -std=c11 -pedantic-errors")
|
||||
(input)
|
||||
(output "c11: 42 43 6 4 6 12 5 0 -9223372036854775808"
|
||||
(output "c11: 42 43 6 4 6 12 5 0"
|
||||
"trigraphs: what??! ??= ???( ??/")
|
||||
(return 0)
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
;;; one that reaches past it -- a GNU statement expression, a C23
|
||||
;;; keyword -- fails here rather than on a user's compiler.
|
||||
;;;
|
||||
;;; A lifted lambda is the one that leans on C11 itself, through
|
||||
;;; `_Static_assert'; the record, the method and the match are here for
|
||||
;;; what they emit, and the globals for initializers that have to be
|
||||
;;; constants.
|
||||
;;; A capturing closure is the one that leans on C11 itself, through
|
||||
;;; max_align_t in the environment and `_Static_assert' on its size;
|
||||
;;; the record, the method and the match are here for what they emit,
|
||||
;;; and the globals for initializers that have to be constants.
|
||||
;;;
|
||||
;;; It is also the one mode where C still reads trigraphs, which Sex has
|
||||
;;; none of: a string says what was written, `??/' before its closing
|
||||
@@ -33,7 +33,6 @@
|
||||
(var origin point #())
|
||||
(var unit _ (shape/square 1))
|
||||
(var pair [_ 2] #(#(point : 1 2) #(point : 3 4)))
|
||||
(var least _ -9223372036854775808)
|
||||
|
||||
(fn sides ((s shape)) int
|
||||
(var n int 0)
|
||||
@@ -44,10 +43,11 @@
|
||||
|
||||
(pub fn main () int
|
||||
(var p point #(point : 6 7))
|
||||
(var add-k (fn ((int)) int)
|
||||
(lambda ((v int)) int (return (+ v 1))))
|
||||
(printf "c11: %d %d %d %d %d %d %d %d %lld\n"
|
||||
(var k int 1)
|
||||
(var add-k (closure ((int)) int)
|
||||
(closure ((v int)) int (k) (return (+ v k))))
|
||||
(printf "c11: %d %d %d %d %d %d %d %d\n"
|
||||
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)
|
||||
(sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least)
|
||||
(sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y))
|
||||
(printf "trigraphs: %s\n" "what??! ??= ???( ??/")
|
||||
(return 0))
|
||||
|
||||
69
tests/sex-programs/closure-signatures.sex
Normal file
69
tests/sex-programs/closure-signatures.sex
Normal file
@@ -0,0 +1,69 @@
|
||||
(input)
|
||||
(output "one argument of two words: 7"
|
||||
"two arguments of one: 7"
|
||||
"unsigned, one argument: 9"
|
||||
"unsigned, two arguments: 3"
|
||||
"captured global: 12"
|
||||
"captured function: 8"
|
||||
"curried: 42 42"
|
||||
"taking one: 21")
|
||||
(return 0)
|
||||
|
||||
;;; A closure's struct is named after its signature, so that two
|
||||
;;; translation units agree on it without sharing a header. The name is
|
||||
;;; built by flattening the argument list, and flattening loses where one
|
||||
;;; argument ends and the next begins: `((long long))' and
|
||||
;;; `((long) (long))' are different signatures that used to mangle alike,
|
||||
;;; and the second quietly reused the first one's struct.
|
||||
;;;
|
||||
;;; A capture that borrows a name reads it from wherever the name is
|
||||
;;; declared, a global or a function included.
|
||||
;;;
|
||||
;;; A closure's signature may name closures in turn: one returned is
|
||||
;;; currying, one taken is a callback.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(var scale int 3)
|
||||
|
||||
(fn double-it ((n int)) int
|
||||
(return (* n 2)))
|
||||
|
||||
(fn curried-add () (closure ((int)) (closure ((int)) int))
|
||||
(return (closure ((a int)) (closure ((int)) int) ()
|
||||
(return (closure ((b int)) int (a) (return (+ a b)))))))
|
||||
|
||||
(pub fn main () int
|
||||
(var one-wide (closure ((long long)) int)
|
||||
(closure ((a (long long))) int () (return (cast a int))))
|
||||
(printf "one argument of two words: %d\n" (one-wide 7))
|
||||
|
||||
(var two-longs (closure ((long) (long)) int)
|
||||
(closure ((a long) (b long)) int () (return (cast (+ a b) int))))
|
||||
(printf "two arguments of one: %d\n" (two-longs 3 4))
|
||||
|
||||
(var one-unsigned (closure ((unsigned int)) int)
|
||||
(closure ((a (unsigned int))) int () (return (cast a int))))
|
||||
(printf "unsigned, one argument: %d\n" (one-unsigned 9))
|
||||
|
||||
(var two-unsigned (closure ((unsigned) (int)) int)
|
||||
(closure ((a unsigned) (b int)) int () (return (+ (cast a int) b))))
|
||||
(printf "unsigned, two arguments: %d\n" (two-unsigned 1 2))
|
||||
|
||||
;; a capture names what it borrows, and the name need not be a local
|
||||
(var scaled (closure ((int)) int)
|
||||
(closure ((x int)) int (scale) (return (* x scale))))
|
||||
(printf "captured global: %d\n" (scaled 4))
|
||||
|
||||
(var doubled (closure ((int)) int)
|
||||
(closure ((x int)) int (double-it) (return (double-it x))))
|
||||
(printf "captured function: %d\n" (doubled 4))
|
||||
|
||||
(var add (closure ((int)) (closure ((int)) int)) (curried-add))
|
||||
(var add2 (closure ((int)) int) (add 2))
|
||||
(printf "curried: %d %d\n" (add2 40) ((add 1) 41))
|
||||
|
||||
(var twice (closure (((closure ((int)) int)) (int)) int)
|
||||
(closure ((f (closure ((int)) int)) (x int)) int () (return (f (f x)))))
|
||||
(printf "taking one: %d\n" (twice add2 17))
|
||||
(return 0))
|
||||
149
tests/sex-programs/closures.sex
Normal file
149
tests/sex-programs/closures.sex
Normal file
@@ -0,0 +1,149 @@
|
||||
(input)
|
||||
(output "Adders: 15 25"
|
||||
"Two captures: 47"
|
||||
"No captures: 7"
|
||||
"Through a parameter: 110"
|
||||
"From an array: 1 2 3"
|
||||
"Index evaluated once: 21 i 1"
|
||||
"Through a struct member: 8"
|
||||
"Shadowed in a block: 9 then 15"
|
||||
"Nested: 33"
|
||||
"Named capture: 7"
|
||||
"Captured pointer: 11 then 12"
|
||||
"From a bare fn: 20 42 7"
|
||||
"Captured array: 6 3, still 6"
|
||||
"Captured const: 6"
|
||||
"Unnamed parameter: 2"
|
||||
"Empty bodies: called")
|
||||
(return 0)
|
||||
|
||||
;;; A closure is a code pointer beside its captures, so what this
|
||||
;;; checks is that the captures survive the lifting -- that two
|
||||
;;; closures of one shape keep their own environments, that a closure
|
||||
;;; outlives the call that built it, and that calling one through a
|
||||
;;; parameter, an array element or a struct member resolves the same
|
||||
;;; way as through a local.
|
||||
;;;
|
||||
;;; A receiver is also an ordinary expression: `[table (++ i)]' has to
|
||||
;;; evaluate its index exactly once, the way it would for an array of
|
||||
;;; function pointers.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(fn double-it ((n int)) int
|
||||
(return (* n 2)))
|
||||
|
||||
;;; a bare function is a closure that captures nothing, so it converts
|
||||
;;; wherever one is expected -- here a declared return type
|
||||
(fn as-closure () (closure ((int)) int)
|
||||
(return double-it))
|
||||
|
||||
(fn make-adder ((n int)) (closure ((int)) int)
|
||||
(return (closure ((b int)) int (n)
|
||||
(return (+ n b)))))
|
||||
|
||||
(fn make-affine ((k int) (b int)) (closure ((int)) int)
|
||||
(return (closure ((x int)) int (k b)
|
||||
(return (+ (* k x) b)))))
|
||||
|
||||
(fn make-const-7 () (closure () int)
|
||||
(return (closure () int ()
|
||||
(return 7))))
|
||||
|
||||
;;; A closure arriving as a parameter: its type is written, so the call
|
||||
;;; resolves without knowing where it came from
|
||||
(fn apply-twice ((f (closure ((int)) int)) (x int)) int
|
||||
(return (f (f x))))
|
||||
|
||||
(struct handlers ((on-tick (closure ((int)) int))))
|
||||
|
||||
(pub fn main () int
|
||||
(var add-10 (closure ((int)) int) (make-adder 10))
|
||||
(var add-20 (closure ((int)) int) (make-adder 20))
|
||||
(printf "Adders: %d %d\n" (add-10 5) (add-20 5))
|
||||
|
||||
(var affine (closure ((int)) int) (make-affine 5 2))
|
||||
(printf "Two captures: %d\n" (affine 9))
|
||||
|
||||
(var seven (closure () int) (make-const-7))
|
||||
(printf "No captures: %d\n" (seven))
|
||||
|
||||
(printf "Through a parameter: %d\n" (apply-twice (make-adder 50) 10))
|
||||
|
||||
(var table [(closure ((int)) int) 3])
|
||||
(var i int 0)
|
||||
(for (= i 0) (< i 3) (++ i)
|
||||
(= [table i] (make-adder i)))
|
||||
(printf "From an array: %d %d %d\n"
|
||||
([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
|
||||
;; printf would be unsequenced whatever the closure did
|
||||
(= i 0)
|
||||
(var once int ([table (++ i)] 20))
|
||||
(printf "Index evaluated once: %d i %d\n" once i)
|
||||
|
||||
(var h (struct handlers) #((struct handlers) : .on-tick (make-adder 5)))
|
||||
(printf "Through a struct member: %d\n" ((. h on-tick) 3))
|
||||
|
||||
;; a block opens a scope: the inner `add-10' ends with it, and the
|
||||
;; call after it is the closure again
|
||||
(do (var add-10 int 9)
|
||||
(printf "Shadowed in a block: %d then " add-10))
|
||||
(printf "%d\n" (add-10 5))
|
||||
|
||||
;; a closure built inside a closure, capturing that one's capture
|
||||
(var outer (closure ((int)) int)
|
||||
(closure ((x int)) int ()
|
||||
(var inner (closure ((int)) int) (make-adder x))
|
||||
(return (inner 3))))
|
||||
(printf "Nested: %d\n" (outer 30))
|
||||
|
||||
;; a capture can name what it holds rather than borrow a variable's
|
||||
;; name, and the expression is evaluated where the closure is written
|
||||
(var pt (struct handlers))
|
||||
(var sum-once (closure () int)
|
||||
(closure () int ((sum (+ 3 4))) (return sum)))
|
||||
(printf "Named capture: %d\n" (sum-once))
|
||||
|
||||
;; capturing a pointer is how by-reference is spelled; the caller owns
|
||||
;; what it points at
|
||||
(var counter int 11)
|
||||
(var peek (closure () int)
|
||||
(closure () int ((at (& counter))) (return (* at))))
|
||||
(printf "Captured pointer: %d then " (peek))
|
||||
(++ counter)
|
||||
(printf "%d\n" (peek))
|
||||
|
||||
;; ...and in an initializer, as an argument, and as a return
|
||||
(var from-fn (closure ((int)) int) double-it)
|
||||
(printf "From a bare fn: %d %d %d\n"
|
||||
(apply-twice from-fn 5)
|
||||
((as-closure) 21)
|
||||
(apply-twice (lambda ((n int)) int (return (+ n 1))) 5))
|
||||
|
||||
;; an array is copied in, element by element, as C copies one neither
|
||||
;; by = nor into a parameter; so are the rows of one of arrays
|
||||
(var xs [int 3] #(1 2 3))
|
||||
(var m [int 2 2] #(#(1 2) #(3 4)))
|
||||
(var sum3 (closure () int) (closure () int (xs) (return (+ [xs 0] [xs 1] [xs 2]))))
|
||||
(var corner (closure () int) (closure () int (m) (return [m 1 0])))
|
||||
(printf "Captured array: %d %d" (sum3) (corner))
|
||||
(= [xs 0] 100)
|
||||
(printf ", still %d\n" (sum3))
|
||||
|
||||
;; a const local is captured as its value, and stays const inside
|
||||
(var k (const int) 5)
|
||||
(var plus-k (closure ((int)) int) (closure ((v int)) int (k) (return (+ v k))))
|
||||
(printf "Captured const: %d\n" (plus-k 1))
|
||||
|
||||
(var second (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))
|
||||
(printf "Unnamed parameter: %d\n" (second 1 2))
|
||||
|
||||
(var nothing (closure () void) (closure () void ()))
|
||||
(var nothing-either (fn () void) (lambda () void))
|
||||
(nothing)
|
||||
(nothing-either)
|
||||
(printf "Empty bodies: called\n")
|
||||
(return 0))
|
||||
@@ -3,8 +3,8 @@
|
||||
"-5")
|
||||
(return 0)
|
||||
|
||||
;;; A recursive sum and an inherent method on it: every layer of
|
||||
;;; encapsulation in one program, built at once.
|
||||
;;; A recursive sum, an inherent method on it, and a spec realized for
|
||||
;;; it: every layer of encapsulation in one program, built at once.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
@@ -19,15 +19,20 @@
|
||||
(match (* self)
|
||||
((lit (v)) (return v))
|
||||
((neg (e)) (return (- (.eval e))))
|
||||
((add (l r)) (return (+ (.eval l) (.eval r))))))
|
||||
(pub fn show ((self (* const expr))) void
|
||||
((add (l r)) (return (+ (.eval l) (.eval r)))))))
|
||||
|
||||
(spec (printable T)
|
||||
(fn show ((self (* const T))) void)
|
||||
(fn show-line ((self (* const T))) void ; default, calls the required one
|
||||
(.show self)
|
||||
(printf "\n")))
|
||||
|
||||
(realize (printable expr)
|
||||
(fn show ((self (* const expr))) void
|
||||
(match (* self)
|
||||
((lit (v)) (printf "%g" v))
|
||||
((neg (e)) (printf "-") (.show e))
|
||||
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")"))))
|
||||
(pub fn show-line ((self (* const expr))) void
|
||||
(.show self)
|
||||
(printf "\n")))
|
||||
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")")))))
|
||||
|
||||
(pub fn main () int
|
||||
(var two expr (expr/lit 2.0))
|
||||
|
||||
61
tests/sex-programs/fixpoint.sex
Normal file
61
tests/sex-programs/fixpoint.sex
Normal file
@@ -0,0 +1,61 @@
|
||||
(input)
|
||||
(output "direct: 120"
|
||||
"fac: 120 3628800"
|
||||
"fib: 55 6765"
|
||||
"applied on the spot: 120")
|
||||
(return 0)
|
||||
|
||||
;;; A fixed point built out of closures, which is the hardest thing to
|
||||
;;; ask of them: recursion with no recursive function anywhere, only
|
||||
;;; self-application.
|
||||
;;;
|
||||
;;; Self-application needs `x x' and so a recursive type, which is
|
||||
;;; spelled here by routing it through a named struct whose field is a
|
||||
;;; closure whose own signature mentions that struct. The generated
|
||||
;;; closure struct is written before `struct rec' is, so this only
|
||||
;;; compiles because a forward declaration is emitted ahead of both.
|
||||
;;;
|
||||
;;; Note what `fix' captures: a *pointer* to the knot, not the knot. A
|
||||
;;; closure is a code pointer beside N bytes of environment, so
|
||||
;;; capturing one by value would need N >= 8 + N. No budget makes that
|
||||
;;; true, and the static assertion says so rather than letting it
|
||||
;;; corrupt anything.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(struct rec ((f (closure (((* (struct rec))) (int)) int))))
|
||||
|
||||
;;; Takes a step that expects itself, returns an ordinary closure with
|
||||
;;; the self-application hidden inside
|
||||
(fn fix ((step (* (struct rec)))) (closure ((int)) int)
|
||||
(return (closure ((n int)) int (step)
|
||||
(return ((. step f) step n)))))
|
||||
|
||||
(pub fn main () int
|
||||
(var fac-knot (struct rec))
|
||||
(= (. fac-knot f)
|
||||
(closure ((self (* (struct rec))) (n int)) int ()
|
||||
(if (<= n 1) (return 1))
|
||||
(return (* n ((. self f) self (- n 1))))))
|
||||
|
||||
;; the knot applied to itself directly, without fix
|
||||
(printf "direct: %d\n" ((. fac-knot f) (& fac-knot) 5))
|
||||
|
||||
(var fib-knot (struct rec))
|
||||
(= (. fib-knot f)
|
||||
(closure ((self (* (struct rec))) (n int)) int ()
|
||||
(if (< n 2) (return n))
|
||||
(return (+ ((. self f) self (- n 1))
|
||||
((. self f) self (- n 2))))))
|
||||
|
||||
;; one combinator, two different recursions
|
||||
(var fac (closure ((int)) int) (fix (& fac-knot)))
|
||||
(var fib (closure ((int)) int) (fix (& fib-knot)))
|
||||
(printf "fac: %d %d\n" (fac 5) (fac 10))
|
||||
(printf "fib: %d %d\n" (fib 10) (fib 20))
|
||||
|
||||
;; the combinator's result invoked where it is returned, with no
|
||||
;; intervening `var' -- the receiver's type is the return type of the
|
||||
;; signature it came from, which is what the name table records
|
||||
(printf "applied on the spot: %d\n" ((fix (& fac-knot)) 5))
|
||||
(return 0))
|
||||
@@ -8,8 +8,8 @@
|
||||
"0 1 4 9 "
|
||||
"4"
|
||||
"42"
|
||||
"<fn of 0: 10>"
|
||||
"32"
|
||||
"<closure of 0: 10>"
|
||||
"42"
|
||||
"2 1"
|
||||
"Hello from Sex!")
|
||||
(return 0)
|
||||
@@ -47,11 +47,11 @@
|
||||
(= (. m y) (/ (+ (. a y) (. b y)) 2))
|
||||
(return m))
|
||||
|
||||
;;; A lambda's type is written once, in the signature; `_' reads it
|
||||
;;; from there wherever the function is called.
|
||||
(fn make-adder () (fn ((int)) int)
|
||||
(return (lambda ((b int)) int
|
||||
(return (+ b 10)))))
|
||||
;;; The closure's type is written once, in the signature; `_' reads it
|
||||
;;; from there at every use.
|
||||
(fn make-adder ((n int)) (closure ((int)) int)
|
||||
(return (closure ((b int)) int (n)
|
||||
(return (+ n b)))))
|
||||
|
||||
;;; A macro that asks what it was handed.
|
||||
;;;
|
||||
@@ -68,9 +68,9 @@
|
||||
;; NOTE: ,x twice -- a macro that duplicates its argument still has
|
||||
;; to think about evaluating it twice. Inference does not fix that.
|
||||
((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y)))
|
||||
;; a function type is a type like any other, so it dispatches like
|
||||
;; one -- and `_' saves a clause per signature
|
||||
((fn _ int) `(printf "<fn of 0: %d>\n" (,x 0)))
|
||||
;; a closure is a type like any other, so it dispatches like one --
|
||||
;; and `_' saves a clause per signature
|
||||
((closure _ int) `(printf "<closure of 0: %d>\n" (,x 0)))
|
||||
(else (error "print: don't know how to print" (type-of x)))))
|
||||
|
||||
;;; The temporary's type is the thing the macro could not write down
|
||||
@@ -136,14 +136,14 @@
|
||||
(var squares [_ 4] #(0 1 4 9))
|
||||
(print [squares 2])
|
||||
|
||||
;; A function pointer's type comes from the signature that produced
|
||||
;; it, and calling one needs that type and nothing else.
|
||||
(var add-10 _ (make-adder))
|
||||
;; A closure's type comes from the signature that produced it, and
|
||||
;; calling one needs that type and nothing else.
|
||||
(var add-10 _ (make-adder 10))
|
||||
(print (add-10 32))
|
||||
(print add-10)
|
||||
|
||||
;; ...including where it is returned, with no name in between.
|
||||
(print ((make-adder) 22))
|
||||
(print ((make-adder 20) 22))
|
||||
|
||||
;; A macro writing a declaration it could not have written before.
|
||||
(var a _ 1)
|
||||
@@ -157,12 +157,12 @@
|
||||
;;; Open questions this draft raises, to settle before Layer 2 ships:
|
||||
;;;
|
||||
;;; 1. SETTLED. `type-match' took `_' on the pattern side, so
|
||||
;;; `(fn _ int)' above is one clause rather than one per 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 list, so
|
||||
;;; `(caddr (type-of x))' reads an array's length.
|
||||
;;; `(closure _ int)' above is one clause rather than one per
|
||||
;;; 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
|
||||
;;; list, so `(caddr (type-of x))' reads an array's length.
|
||||
;;;
|
||||
;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each
|
||||
;;; element with the hole, so the element type comes from the
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"decayed: 2 2 there"
|
||||
"unsigned wins either way: 4294967295 4294967295"
|
||||
"toplevel: 1 2.5 hi 12"
|
||||
"closure in place: 5"
|
||||
"a type is not a call: 7"
|
||||
"radix literals: 224 5 128"
|
||||
"a double reaches C whole: 1"
|
||||
@@ -34,6 +35,9 @@
|
||||
(var s _ "hi")
|
||||
(var a _ (+ 3 (* 3 3)))
|
||||
|
||||
(fn make-adder ((k int)) (closure ((int)) int)
|
||||
(return (closure ((b int)) int (k) (return (+ k b)))))
|
||||
|
||||
(pub fn main () int
|
||||
(var x int 6)
|
||||
(var y int 3)
|
||||
@@ -76,9 +80,14 @@
|
||||
|
||||
(printf "toplevel: %d %g %s %d\n" n d s a)
|
||||
|
||||
;; a closure literal is its own type, so it can be called where it is
|
||||
;; written, the way a lambda already could
|
||||
(printf "closure in place: %d\n"
|
||||
((closure ((v int)) int () (return v)) 5))
|
||||
|
||||
;; a `fn' type's parameter list looks exactly like a call; with a
|
||||
;; function named `f' in scope it used to be read as one
|
||||
(var f (fn ((int)) int) (lambda ((v int)) int (return (+ v 1))))
|
||||
;; closure named `f' in scope it used to be read as one
|
||||
(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))
|
||||
|
||||
|
||||
83
tests/sex-programs/specs.sex
Normal file
83
tests/sex-programs/specs.sex
Normal file
@@ -0,0 +1,83 @@
|
||||
(input)
|
||||
(output "$12.34"
|
||||
"(3, 4)"
|
||||
"max 1234"
|
||||
"realizes ord: money 1, point 0"
|
||||
"calls its own: 9")
|
||||
(return 0)
|
||||
|
||||
;;; A spec is a contract and emits nothing; a realization is the
|
||||
;;; spec's methods for one type, mangled typeːspecːmethod. A default
|
||||
;;; is copied into every realizing type with the parameter
|
||||
;;; substituted, so the `show' it calls is that type's own.
|
||||
;;;
|
||||
;;; What the layer is for is the last line: a generic asks `realizes?'
|
||||
;;; before it expands, and says so itself rather than leaving a wall
|
||||
;;; of C errors two stages downstream.
|
||||
|
||||
(include stdio.h)
|
||||
|
||||
(record money ((cents int)))
|
||||
(record point ((x int) (y int)))
|
||||
|
||||
(spec (printable T)
|
||||
(fn show ((self (* const T))) void)
|
||||
(fn show-line ((self (* const T))) void ; default, calls the required one
|
||||
(.show self)
|
||||
(printf "\n")))
|
||||
|
||||
(spec (ord T)
|
||||
(fn less ((a (* const T)) (b (* const T))) bool))
|
||||
|
||||
(realize (printable money)
|
||||
(fn show ((self (* const money))) void
|
||||
(printf "$%d.%02d" (/ (. self cents) 100) (% (. self cents) 100))))
|
||||
|
||||
(realize (printable point)
|
||||
(fn show ((self (* const point))) void
|
||||
(printf "(%d, %d)" (. self x) (. self y))))
|
||||
|
||||
(realize (ord money)
|
||||
(fn less ((a (* const money)) (b (* const money))) bool
|
||||
(return (< (. a cents) (. b cents)))))
|
||||
|
||||
;;; A bounded generic: the macro refuses before it expands
|
||||
(defmacro (max-of type)
|
||||
(unless (realizes? 'ord type)
|
||||
(error "does not realize ord" type))
|
||||
`(fn ,(cat 'max- type) ((a (* const ,type)) (b (* const ,type))) ,type
|
||||
(if (,(cat type '/ord/less) a b)
|
||||
(return (* b))
|
||||
(return (* a)))))
|
||||
|
||||
(max-of money)
|
||||
|
||||
(defmacro (ord? type) (if (realizes? 'ord type) 1 0))
|
||||
|
||||
;;; A realization's methods may call one another, whatever order they
|
||||
;;; come in: `total', written, calls the default `doubled', which calls
|
||||
;;; the later default `plus-one', which calls `base', written below them
|
||||
(spec (sized T)
|
||||
(fn total ((self (* const T))) int)
|
||||
(fn doubled ((self (* const T))) int (return (* 2 (.plus-one self))))
|
||||
(fn plus-one ((self (* const T))) int (return (+ 1 (.base self))))
|
||||
(fn base ((self (* const T))) int))
|
||||
|
||||
(realize (sized point)
|
||||
(fn total ((self (* const point))) int (return (+ 1 (.doubled self))))
|
||||
(fn base ((self (* const point))) int (return (. self x))))
|
||||
|
||||
(pub fn main () int
|
||||
(var m money #(money : 1234))
|
||||
(var p point #(point : 3 4))
|
||||
|
||||
(.show-line m) ; the default, through the registry
|
||||
(point/printable/show-line (& p)) ; and spelled out
|
||||
|
||||
(var cheap money #(money : 150))
|
||||
(var big money (max-money (& m) (& cheap)))
|
||||
(printf "max %d\n" (. big cents))
|
||||
|
||||
(printf "realizes ord: money %d, point %d\n" (ord? money) (ord? point))
|
||||
(printf "calls its own: %d\n" (.total p))
|
||||
(return 0))
|
||||
@@ -189,8 +189,8 @@
|
||||
'yes (type-match '(struct point) ((struct _) 'yes) (else 'no)))
|
||||
(test "and the keyword still has to agree"
|
||||
'no (type-match '(union point) ((struct _) 'yes) (else 'no)))
|
||||
(test "a function of any signature"
|
||||
'yes (type-match '(fn ((float)) int) ((fn _ _) 'yes) (else 'no)))
|
||||
(test "a closure of any signature"
|
||||
'yes (type-match '(closure ((float)) int) ((closure _ _) 'yes) (else 'no)))
|
||||
(test "an exact pattern is still exact"
|
||||
'no (type-match '(* int) ((* const char) 'yes) (else 'no)))
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
(import scheme
|
||||
(chicken base)
|
||||
(chicken condition)
|
||||
(chicken eval)
|
||||
(chicken file)
|
||||
(chicken io)
|
||||
(chicken pathname)
|
||||
@@ -44,22 +43,11 @@
|
||||
;;; module the tests import
|
||||
(define eggs (call-with-input-file "dependencies.txt" read-list))
|
||||
|
||||
;;; A scheme.scm is not the module every unit imports. Asked from /,
|
||||
;;; since here a NAME.import.scm built from NAME.scm would answer
|
||||
(define (chicken-module? name)
|
||||
(let ((here (current-directory)))
|
||||
(dynamic-wind
|
||||
(lambda () (change-directory "/"))
|
||||
(lambda () (handle-exceptions exn #f (module-environment name) #t))
|
||||
(lambda () (change-directory here)))))
|
||||
|
||||
(define (module-file name)
|
||||
(and (symbol? name)
|
||||
(not (memq name eggs))
|
||||
(let ((file (string-append (symbol->string name) ".scm")))
|
||||
(and (file-exists? file)
|
||||
(not (chicken-module? name))
|
||||
file))))
|
||||
(and (file-exists? file) file))))
|
||||
|
||||
;;; FILE's forms, or the end of the scan, naming the file that has none
|
||||
(define (forms-of file)
|
||||
@@ -72,11 +60,9 @@
|
||||
(exit 1))
|
||||
(call-with-input-file file read-list)))
|
||||
|
||||
;;; The names FILE imports, and the files it includes, skipping those
|
||||
;;; SEEN already, so two files that include each other are read once
|
||||
;;; each; the vendored sex-fmt-c imports inside its (module name
|
||||
;;; exports ...) form
|
||||
(define (scan file #!optional (seen (list file)))
|
||||
;;; The names FILE imports, and the files it includes; the vendored
|
||||
;;; sex-fmt-c imports inside its (module name exports ...) form
|
||||
(define (scan file)
|
||||
(let loop ((forms (forms-of file)) (names '()) (files '()))
|
||||
(if (null? forms)
|
||||
(values names files)
|
||||
@@ -88,15 +74,11 @@
|
||||
((eq? (car form) 'import)
|
||||
(loop (cdr forms) (append (map spec-name (cdr form)) names) files))
|
||||
((eq? (car form) 'include-relative)
|
||||
(let ((included (make-pathname (pathname-directory file) (cadr form)))
|
||||
(seen (append files seen)))
|
||||
(if (member included seen)
|
||||
(loop (cdr forms) names files)
|
||||
(let-values (((more-names more-files)
|
||||
(scan included (cons included seen))))
|
||||
(let ((included (make-pathname (pathname-directory file) (cadr form))))
|
||||
(let-values (((more-names more-files) (scan included)))
|
||||
(loop (cdr forms)
|
||||
(append more-names names)
|
||||
(append (cons included more-files) files))))))
|
||||
(append (cons included more-files) files)))))
|
||||
(else (loop (cdr forms) names files)))))))
|
||||
|
||||
(define (symbol<? a b)
|
||||
|
||||
60
types.scm
60
types.scm
@@ -34,6 +34,12 @@
|
||||
variant-fields
|
||||
reset-declarations!
|
||||
|
||||
add-spec!
|
||||
get-spec
|
||||
spec-parameter
|
||||
spec-methods
|
||||
add-realization!
|
||||
realizes?
|
||||
normalize-fields
|
||||
|
||||
add-method!
|
||||
@@ -43,7 +49,6 @@
|
||||
|
||||
add-name-type!
|
||||
get-name-type
|
||||
unknown-name
|
||||
type-of
|
||||
current-type-of
|
||||
get-return-type
|
||||
@@ -151,21 +156,11 @@
|
||||
(define (add-name-type! name type)
|
||||
(hash-table-set! +name-db+ name type))
|
||||
|
||||
;;; Called with each name a lookup finds nothing for. A module's
|
||||
;;; interface is read before its declarations are, so a macro call there
|
||||
;;; asking after one -- (field-count box), box being its record -- is
|
||||
;;; told nothing, and fails for that rather than for being wrong
|
||||
(define unknown-name (make-parameter void))
|
||||
|
||||
(define (known name info)
|
||||
(unless info ((unknown-name) name))
|
||||
info)
|
||||
|
||||
;;; #f for a name never declared, which is what `printf' looks like
|
||||
;;; until something parses stdio.h. Not an error here; the caller
|
||||
;;; decides.
|
||||
(define (get-name-type name)
|
||||
(known name (hash-table-ref/default +name-db+ name #f)))
|
||||
(hash-table-ref/default +name-db+ name #f))
|
||||
|
||||
;;; What `(make-adder 10)' has for a type: `make-adder's return type,
|
||||
;;; or #f when NAME is not a function with a signature on record
|
||||
@@ -177,7 +172,7 @@
|
||||
(third type))))
|
||||
|
||||
(define (get-tag-info name)
|
||||
(known name (hash-table-ref/default +tag-db+ name #f)))
|
||||
(hash-table-ref/default +tag-db+ name #f))
|
||||
|
||||
;;; First look up the ordinary identifier, then tag of that id when
|
||||
;;; no ordinary one was declared, as C does
|
||||
@@ -301,7 +296,7 @@
|
||||
(hash-table-set! +ops-db+ (cons (type-key type) method) qualified))
|
||||
|
||||
(define (get-method type method)
|
||||
(known type (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)))
|
||||
(hash-table-ref/default +ops-db+ (cons (type-key type) method) #f))
|
||||
|
||||
;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength
|
||||
(define (qualify-op type name)
|
||||
@@ -318,14 +313,43 @@
|
||||
((memq (car type) '(const volatile)) (ops-key (cadr type)))
|
||||
(else #f)))
|
||||
|
||||
;;; Sums, constructors and methods refuse a second declaration
|
||||
;;; A spec is a parameter and a list of methods, each of which either
|
||||
;;; declares a signature or also carries a default body:
|
||||
;;;
|
||||
;;; (spec (printable T) (fn show ((self (* const T))) void))
|
||||
;;; -> printable -> (T (fn show ((self (* const T))) void))
|
||||
;;;
|
||||
;;; And a realization is only ever asked whether it exists -- the
|
||||
;;; methods it provides land in +ops-db+ like any others.
|
||||
(define +spec-db+ (make-hash-table))
|
||||
(define +realize-db+ (make-hash-table))
|
||||
|
||||
(define (add-spec! name parameter methods)
|
||||
(hash-table-set! +spec-db+ name (cons parameter methods)))
|
||||
|
||||
(define (get-spec name)
|
||||
(hash-table-ref/default +spec-db+ name #f))
|
||||
|
||||
(define (spec-parameter spec) (car spec))
|
||||
(define (spec-methods spec) (cdr spec))
|
||||
|
||||
(define (add-realization! spec type)
|
||||
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
|
||||
|
||||
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
|
||||
(define (realizes? spec type)
|
||||
(hash-table-exists? +realize-db+ (cons spec (type-key type))))
|
||||
|
||||
;;; Sums, constructors, methods and specs refuse a second declaration
|
||||
;;; of the same name, which is per translation unit rather than per
|
||||
;;; process -- so a process that compiles two units has to start the
|
||||
;;; second one clean.
|
||||
(define (reset-declarations!)
|
||||
(set! +sum-db+ (make-hash-table))
|
||||
(set! +constructor-db+ (make-hash-table))
|
||||
(set! +ops-db+ (make-hash-table)))
|
||||
(set! +ops-db+ (make-hash-table))
|
||||
(set! +spec-db+ (make-hash-table))
|
||||
(set! +realize-db+ (make-hash-table)))
|
||||
|
||||
;;; Type matcher macro
|
||||
;;; (type-match type
|
||||
@@ -343,8 +367,8 @@
|
||||
;;;
|
||||
;;; `_' in a pattern matches anything in that position, the same thing
|
||||
;;; it means in a type. Without it every spelling has to be enumerated:
|
||||
;;; `(fn ((int)) int)' and `(fn ((float)) int)' are separate clauses for
|
||||
;;; what is one case.
|
||||
;;; `(closure ((int)) int)' and `(closure ((float)) int)' are separate
|
||||
;;; clauses for what is one case.
|
||||
;;;
|
||||
;;; A `_' written last takes everything that remains, because a type's
|
||||
;;; words are spread rather than nested -- `(* const char)' is three
|
||||
|
||||
19
utils.scm
19
utils.scm
@@ -10,6 +10,7 @@
|
||||
|
||||
(export
|
||||
get-env-var
|
||||
set-working-directory
|
||||
to-absolute-pathname
|
||||
comment-form?
|
||||
strip-header-comments
|
||||
@@ -24,9 +25,12 @@
|
||||
form-end-line
|
||||
copy-form-source!
|
||||
stamp-form-source!
|
||||
form-location
|
||||
set-form-type!
|
||||
form-type
|
||||
sex-error
|
||||
sex-warning
|
||||
(with-directory set-working-directory))
|
||||
with-directory)
|
||||
|
||||
(define-syntax prog1
|
||||
(syntax-rules ()
|
||||
@@ -125,6 +129,19 @@
|
||||
;;; The file `parse-all' is currently reading. Bound by the reader
|
||||
(define current-source-file (make-parameter "<unknown>"))
|
||||
|
||||
;;; What type a form has, once something has worked it out. Keyed by
|
||||
;;; cons cell like the sources above, so one form has one type: a body
|
||||
;;; typed at two instantiations has to be copied before the second.
|
||||
(define +form-types+ (make-hash-table eq?))
|
||||
|
||||
(define (set-form-type! form type)
|
||||
(when (pair? form)
|
||||
(hash-table-set! +form-types+ form type))
|
||||
type)
|
||||
|
||||
(define (form-type form)
|
||||
(hash-table-ref/default +form-types+ form #f))
|
||||
|
||||
(define (set-form-source! form file line #!optional (end-line line))
|
||||
(hash-table-set! +form-sources+ form (list file line end-line)))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user