diff --git a/Makefile b/Makefile index a0924ab..2ba0f4c 100644 --- a/Makefile +++ b/Makefile @@ -20,8 +20,16 @@ CSC_FLAGS += -K prefix -static prefix = /usr/local exec_prefix = $(prefix) bindir = $(exec_prefix)/bin +datarootdir = $(prefix)/share +datadir = $(datarootdir) +# sexc looks for the standard library beside itself: next to the binary +# in a work tree, and bindir/../share/sex once installed +sexlibdir = $(datadir)/sex INSTALL = install INSTALL_PROGRAM = $(INSTALL) +INSTALL_DATA = $(INSTALL) -m 644 + +SEX_LIB = $(wildcard lib/*.sex) MODULE_FLAGS = -emit-all-import-libraries -module-registration -c @@ -72,8 +80,8 @@ sex-macros.o: sex-macros.module.scm sex-macros.scm reader.o: reader.module.scm reader.scm utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils -sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils +sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o types.o utils.o + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils semen.o: semen.module.scm semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils @@ -96,11 +104,12 @@ sextest: $(MAKE) -C ./tools/sextest sextest cp ./tools/sextest/sextest . -SEX_TEST_PROGRAMS = c99 \ +SEX_TEST_PROGRAMS = c11 \ closure-signatures \ closures \ comments \ compound-literals \ + encapsulation \ feature-flags \ features \ fixpoint \ @@ -109,7 +118,12 @@ SEX_TEST_PROGRAMS = c99 \ lambdas \ lists \ operators \ + ops \ + records \ serialize \ + specs \ + sums \ + threading \ type-shapes \ unicode \ unnamed-params \ @@ -128,15 +142,18 @@ check run-tests: sexc sex-tests sextest install: all installdirs $(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc + $(INSTALL_DATA) $(SEX_LIB) $(DESTDIR)$(sexlibdir) install-strip: $(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install installdirs: - $(INSTALL) -d $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(sexlibdir) uninstall: rm -f $(DESTDIR)$(bindir)/sexc + rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%) + -rmdir $(DESTDIR)$(sexlibdir) $(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache $(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR) diff --git a/Readme.org b/Readme.org index 57d7e66..251a2f6 100644 --- a/Readme.org +++ b/Readme.org @@ -45,7 +45,9 @@ tree's ~.eggs~ path): #+end_src ** Installation -GNU directory variables: ~prefix~, ~exec_prefix~, ~bindir~, ~DESTDIR~. +GNU directory variables: ~prefix~, ~exec_prefix~, ~bindir~, ~datadir~, +~DESTDIR~. The binary goes to ~bindir~ and the standard library to +~$(datadir)/sex~. #+begin_src sh # default installation (/usr/local/bin/) @@ -123,7 +125,8 @@ Hello, Alex! * Features ** Full C interoperability Just ~(include "Your/Favourite/Library.h")~ and use it as you would -have is C. +have is C. One ~include~ takes as many headers as you care to name: +~(include stdio.h stdlib.h string.h)~. *** Auto kebabification For hardcore fans of traditional Lisp naming convention, @@ -131,17 +134,52 @@ Sex offers automatic kebabification of all symbols, i.e. no more ugly ~GL_ARRAY_BUFFER~ s in your code, they may be written in their proper form: ~GL-ARRAY-BUFFER~. +** Member access +~(. x field ...)~ reads a path, and writes C's ~.~ or its ~->~ according +to what it is reading from. Each step asks the type in hand, so one path +may be both: + +#+begin_src scheme +(struct point ((x int) (y int))) +(struct line ((a (* struct point)) (b (struct point)))) + +(. p x) ; p : (struct point) -> p.x +(. pp x) ; pp : (* struct point) -> pp->x +(. l a x) ; l.a is a pointer -> l.a->x +(. lp b y) ; lp is, l.b is not -> lp->b.y +#+end_src + +A receiver whose type cannot be worked out --- something out of a header +nothing has parsed --- is read as a value, with a warning saying so. For a +pointer there, ~(%-> p x)~ writes ~p->x~ whatever ~p~ is. + +A method is ~(.name receiver args ...)~ and a field is ~(. receiver +name)~, so the shape of a form says which of the two it is without +knowing any types: ~(. a b c)~ is a path and ~(.b a c)~ is a call. + ** Modules Each source file is a module. Module can provide public interface and be imported by using ~(import path/to/module)~ expression. Module -search path consists of two parts: first is relative to the source -being compiled location, and the second is ~SEX_MODULE_PATH~ -environment variable. +search path has three parts: first is relative to the source being +compiled location, then the ~SEX_MODULE_PATH~ environment variable, +and last the standard library. Module's public interface consists of everything declared ~pub~. Structures, function, macros, types, variables can be public. +** Standard library +~lib/~ holds the modules that come with the compiler. They are imported +like any other, and being searched last, a module of your own by the +same name wins over one of ours. + +~sexc~ looks for them beside itself, so a work tree needs nothing set +up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~. + +Each module is documented in a file of its own beside it: + +- [[file:lib/threading-macros.org][threading-macros]] --- ~->~, threading a value through a chain of calls + ** Read-time feature expressions Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that follows is kept only when the feature expression is true, and otherwise diff --git a/example/list.sex b/example/list.sex index 809ad68..5a1f8c9 100644 --- a/example/list.sex +++ b/example/list.sex @@ -9,25 +9,25 @@ (fn-name (cat 'make-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type) (var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type))) - (= (-> list next) NULL) + (= (. list next) NULL) (return list)))) (pub defmacro (add-value-list-T type is-public?) (let ((list-type (list 'struct (cat 'list- type))) (fn-name (cat 'add-value-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void - (while (!= (-> list next) NULL) - (= list (-> list next))) - (= (-> list next) (,(cat 'make-list- type))) - (= (-> list value) value)))) + (while (!= (. list next) NULL) + (= list (. list next))) + (= (. list next) (,(cat 'make-list- type))) + (= (. list value) value)))) (pub defmacro (length-list-T type is-public?) (let ((fn-name (cat 'length-list- type)) (list-type (list 'struct (cat 'list- type)))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t (var n size-t 0) - (while (!= (-> list next) NULL) - (= list (-> list next)) + (while (!= (. list next) NULL) + (= list (. list next)) (++ n)) (return n)))) @@ -35,14 +35,14 @@ `(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type) ((list ,(list '* 'struct (cat 'list- type)))) bool - (return (== (-> list next) NULL)))) + (return (== (. list next) NULL)))) (pub defmacro (list-for-each list-type list-var elt-type elt-var what-do) (let ((list-var-2 (cat list-var '-2))) `(do (var ,list-var-2 (* ,list-type) ,list-var) - (var ,elt-var ,elt-type (-> ,list-var-2 value)) - (while (!= (-> ,list-var-2 next) NULL) + (var ,elt-var ,elt-type (. ,list-var-2 value)) + (while (!= (. ,list-var-2 next) NULL) ,what-do - (= ,list-var-2 (-> ,list-var-2 next)) - (= ,elt-var (-> ,list-var-2 value)))))) + (= ,list-var-2 (. ,list-var-2 next)) + (= ,elt-var (. ,list-var-2 value)))))) diff --git a/example/serialize.sex b/example/serialize.sex index b6d2d6d..9b30a1f 100644 --- a/example/serialize.sex +++ b/example/serialize.sex @@ -32,7 +32,7 @@ ((* char) "%s") (else (error "serialize-struct: unsupported field type" type-name name type)))) - (-> v ,name)))))) + (. v ,name)))))) (if (not printers) (error "serialize-struct: no such struct" type-name) `(pub fn ,(cat 'serialize- type-name) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 05f9b8b..35be150 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -36,7 +36,7 @@ (define (line-directive src) ;; `%line' is fmt-c's #line directive. cpp-line concatenates its ;; second argument verbatim, so the file name arrives already quoted. - `(%line ,(cdr src) ,(fmt #f #\" (car src) #\"))) + `(%line ,(cadr src) ,(fmt #f #\" (car src) #\"))) (define (walk-body stmts) "Walk a statement list, re-anchoring each statement that has a known @@ -94,15 +94,23 @@ forms, and what remains." (cons (walk-stmt (cadr cs)) (cons (walk-expr (car cs)) acc))))))) +;;; mouse-x -> mouse_x, vec2/length -> vec2ːlength. +;;; +;;; `ː' is U+02D0, a modifier letter, because C takes letters in an +;;; identifier and not symbols -- clang rejects `§' outright. Not `__', +;;; 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 closures carry a ƛ for the same reason. (define (unkebabify sym) (case sym - ((-) sym) - ((--) sym) - ((->) sym) - ((-=) sym) + ((- -- -> -= / /=) sym) ; bare operators, not names (else (string->symbol - (irregex-replace/all "-(?!>)" (symbol->string sym) "_"))))) + (irregex-replace/all + "/" + (irregex-replace/all "-(?!>)" (symbol->string sym) "_") + "ː"))))) (define (atom-to-fmt-c atom) (case atom @@ -182,6 +190,9 @@ forms, and what remains." ;; (dot-access obj field ...) -> obj.field... member access. `%.' ;; is the fmt-c directive for the `.' operator (see sex-fmt-c). (('dot-access . rest) (cons '%. (map walk-expr rest))) + ;; `%->' is the C arrow. Nothing writes it: it is what a member + ;; path lowers to where the thing it reads from is a pointer + (('%-> . rest) (cons '%-> (map walk-expr rest))) (('var . _) (walk-var form)) ;; An expression has no room for a statement, so a comment in a ;; cast is dropped rather than relocated. @@ -484,17 +495,38 @@ forms, and what remains." ((or ('struct . _) ('union . _)) (walk-struct form)) (('enum . _) (walk-enum form)) + ;; A target is a filename and not an identifier: GL/gl.h is a path, + ;; and unkebabify would spell it GLːgl.h + (('include target) (list '%include target)) (('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest)) (else (walk-expr form)))) +;;; Two toplevel forms are separated by a blank line only if they were +;;; written that way: the prelude's typedefs come out packed, and so do +;;; the three includes at the top of a program that wrote them as three +;;; adjacent lines. Forms from different files -- the prelude, then an +;;; imported module, then the unit itself -- always get one. +(define (blank-line-between? prev next) + (if (equal? (form-file prev) (form-file next)) + (let ((end (form-end-line prev)) + (start (form-line next))) + (and end start (> (- start end) 1))) + #t)) + (define (emit-c sex-forms) - (for-each (lambda (form) - ;; Forms the reader did not produce -- the prelude, and - ;; anything a macro built that we could not attribute -- - ;; have no location and get no directive. - (let ((src (and (not (eq? (sex-line-directives) 'none)) - (form-source form)))) - (when src - (fmt #t (c-expr (line-directive src))))) - (fmt #t (c-expr (process-toplevel-form form)) nl)) - (pack-comments sex-forms))) + (let emit ((forms (pack-comments sex-forms)) (prev #f)) + (unless (null? forms) + (let ((form (car forms))) + (when (and prev (blank-line-between? prev form)) + (fmt #t nl)) + ;; Forms the reader did not produce -- the prelude, and + ;; anything a macro built that we could not attribute -- + ;; have no location and get no directive. + (let ((src (and (not (eq? (sex-line-directives) 'none)) + (form-source form)))) + (when src + (fmt #t (c-expr (line-directive src))))) + ;; `fl', not `nl': a comment leaves the cursor at the end of + ;; its line while everything else has already broken it + (fmt #t (c-expr (process-toplevel-form form)) fl) + (emit (cdr forms) form))))) diff --git a/lib/threading-macros.org b/lib/threading-macros.org new file mode 100644 index 0000000..8bcb3b4 --- /dev/null +++ b/lib/threading-macros.org @@ -0,0 +1,16 @@ +* threading-macros +~->~ passes a value through a chain of forms, each step taking what came +before it as its first argument, so the chain reads in the order it +happens instead of inside out. Clojure spells it this way and this is +the same thing: + +#+begin_src scheme +(import threading-macros) + +(-> 5 double-it (add 3) double-it) ; (double-it (add (double-it 5) 3)) +(-> lp (. a x)) ; lp->a->x +(-> q .length-sq) ; a method is a step like any other +#+end_src + +A step that is not a list is a call of one argument: ~(-> x f)~ is +~(f x)~. diff --git a/lib/threading-macros.sex b/lib/threading-macros.sex new file mode 100644 index 0000000..e572774 --- /dev/null +++ b/lib/threading-macros.sex @@ -0,0 +1,20 @@ +;;; Threading macros +;;; +;;; `->' passes a value through a chain of forms, each step taking what +;;; came before it as its first argument, so a chain of calls reads in +;;; the order it happens rather than inside out. Clojure spells it this +;;; way and this is the same thing: +;;; +;;; (-> 5 double-it (add 3)) == (add (double-it 5) 3) +;;; +;;; A step that is not a list is a call of one argument, so `(-> x f)' +;;; is `(f x)' and a method is a step like any other. + +(pub defmacro (-> x . steps) + (let thread ((acc x) (steps steps)) + (if (null? steps) + acc + (thread (if (pair? (car steps)) + (cons (car (car steps)) (cons acc (cdr (car steps)))) + (list (car steps) acc)) + (cdr steps))))) diff --git a/reader.scm b/reader.scm index dcc8e94..566fd10 100644 --- a/reader.scm +++ b/reader.scm @@ -38,11 +38,13 @@ (define (peek port) (peek-char port)) -;;; Record where a form started. Called with the line of the opening -;;; delimiter, sampled before it is consumed +;;; Record where a form started and where it ended. Called with the +;;; line of the opening delimiter, sampled before it is consumed, once +;;; the form itself has been read -- so the current line is the one its +;;; closing delimiter sits on (define (stamp form line) (when (pair? form) - (set-form-source! form (current-source-file) line)) + (set-form-source! form (current-source-file) line (current-line))) form) (define (delimiter? c) diff --git a/semen.scm b/semen.scm index e1952ea..62aba86 100644 --- a/semen.scm +++ b/semen.scm @@ -2,6 +2,7 @@ (import scheme + (only (scheme base) make-parameter) (chicken base) (chicken keyword) (chicken string) @@ -29,6 +30,7 @@ ;;; multiple forms, e.g. lambdas collected from a function may result ;;; in auxiliary structures and functions. (define (process raw-sex-forms) + (reset-declarations!) (process-rec raw-sex-forms (list))) (define (process-rec forms acc) @@ -82,6 +84,17 @@ ((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)) + ((or ('sum . _) + ('pub 'sum . _)) (process-sum sex-form acc)) + ((or ('record . _) + ('pub 'record . _)) (process-record sex-form acc)) ((or ('struct . _) ('pub 'struct . _)) (process-struct sex-form acc)) ((or ('union . _) @@ -91,14 +104,19 @@ ((or ('var . _) ('pub 'var . _) ('extern 'var . _)) (process-global-var sex-form acc)) - (('include . includes) (process-includes sex-form includes acc)) + ;; `pub' on either of these is what read-public-interface already + ;; 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 . _) ('pub 'define name . _)) (add-define name sex-form) (cons sex-form acc)) (('comment . _) (cons sex-form acc)) - (('import . modules) + ((or ('import . modules) + ('pub 'import . modules)) (process-imports (get-modules-public-forms modules) acc)) ((or ('defmacro . rest) @@ -153,16 +171,23 @@ (define (walk-form form walk-fn env) (if (atom? form) form (let ((new-form (walk-fn form env))) - (cond ((not (eq? form new-form)) - (walk-form new-form walk-fn env)) - (else - (let ((new-car (walk-form (car new-form) walk-fn env)) - (new-cdr (walk-form (cdr new-form) walk-fn env))) - (cond ((and (pair? new-car) - (eq? (car new-car) walk-embed-result)) - (append (cdr new-car) new-cdr)) - (else - (recons new-form new-car new-cdr))))))))) + (if (not (eq? form new-form)) + (walk-form new-form walk-fn env) + (walk-rest new-form walk-fn env))))) + +;;; The cdr of a form is a list of forms and not itself one, so it is +;;; walked without being offered to WALK-FN: otherwise the tail of +;;; (fn g () t) is the list (t), which reads as a call to a macro +;;; named t -- and a function whose return type shares a name with a +;;; macro expanded that tail and died on the arity. +(define (walk-rest form walk-fn env) + (if (atom? form) form + (let ((new-car (walk-form (car form) walk-fn env)) + (new-cdr (walk-rest (cdr form) walk-fn env))) + (if (and (pair? new-car) + (eq? (car new-car) walk-embed-result)) + (append (cdr new-car) new-cdr) + (recons form new-car new-cdr))))) ;;; Typdef @@ -230,7 +255,7 @@ ;; emits the comment immediately before the declaration (cons form (if doc - (cons (list 'comment doc) acc) + (cons (copy-form-source! form (list 'comment doc)) acc) acc))) (define (strip-fn-header-comments fn-form) @@ -252,17 +277,179 @@ (let* ((env (make-fn-env expanded)) ;; the parameters are the body's outermost scope (header (map resolve-closure-types (take expanded boundary))) - (body (walk-body (drop expanded boundary) env)) - (processed (append header body))) + (body (parameterize ((operand-position? #f)) + (walk-body (drop expanded boundary) env))) + ;; A function is header and body stitched together, so the + ;; result is fresh structure: without this the definition + ;; has no location, and nothing downstream can say where + ;; the function was written + (processed (copy-form-source! sex-fn-raw (append header body)))) (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) + (fold (lambda (entry acc) + (process-realized-method form name type + (and pub? (cdr entry)) (car entry) acc)) + acc + (realization-methods type parameter wanted given)))))) + +;;; 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. +(define (process-realized-method form spec type pub? method acc) + (let* ((name (second method)) + (qualified (qualify-op (qualify-op type spec) name)) + (renamed (rename-fn method qualified))) + (when (get-method type name) + (sex-error form "method is already defined on" type name)) + (add-method! type name qualified) + (process-fn (copy-form-source! form (if pub? (cons 'pub renamed) renamed)) + acc))) + +;;; 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 ...)) +;;; +;;; is (pub fn vec2/length ...) plus a registry entry, so that +;;; (. v length) can find it later. The block itself never reaches the +;;; writer; `pub' inside it means what it means outside. +(define (process-ops form acc) + (let ((type (and (pair? (cdr form)) (cadr form)))) + (unless (symbol? type) + (sex-error form "ops needs a type name" form)) + (fold (lambda (method acc) (process-op type method acc)) + acc + (cddr form)))) + +(define (process-op type form acc) + (if (comment-form? form) + (cons form acc) + (let ((core (and (pair? form) (fn-core form)))) + (unless (and (pair? core) (eq? (car core) 'fn) + (pair? (cdr core)) (symbol? (second core))) + (sex-error form "ops takes fn forms" form)) + (let ((name (second core))) + (when (get-method type name) + (sex-error form "method is already defined on" type name)) + (let ((qualified (qualify-op type name))) + (add-method! type name qualified) + (process-fn (rename-fn form qualified) acc)))))) + +(define (rename-fn form name) + (if (memq (first form) '(pub extern)) + (copy-form-source! form (cons (first form) (rename-fn (cdr form) name))) + (copy-form-source! form `(fn ,name ,@(cddr form))))) + (define (make-fn-env fn-form) (let ((env (make-hash-table)) (parameters (make-hash-table))) (for-each (lambda (param) - (when (and (pair? param) (pair? (cdr param))) - (hash-table-set! parameters (first param) (second param)))) + (when (named-arg? param) + (hash-table-set! parameters + (first param) + (named-arg-type param)))) (sex-fn-arglist fn-form)) (set! (hash-table-ref env :fn-name) (sex-fn-name fn-form)) (set! (hash-table-ref env :lambda-counter) 0) @@ -271,13 +458,22 @@ (set! (hash-table-ref env :scopes) (list parameters)) env)) -;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int). -;;; Anything that is not a plain (name type) -- a variadic tail -- goes -;;; through untouched. +;;; `(p (* struct point))' writes the type in one piece and +;;; `(p * struct point)' spreads it over the rest; both are +;;; `(* struct point)' +(define (named-arg-type param) + (if (null? (cddr param)) + (second param) + (cdr param))) + +;;; (fn sum ((a int) (b int)) int ...) -> (fn ((int) (int)) int), and +;;; (self * const v) is ((* const v)) just as (self (* const v)) is. +;;; Anything that names nothing -- a variadic tail -- goes through +;;; untouched. (define (arglist-types arglist) (map (lambda (param) - (if (and (pair? param) (= 2 (length param)) (named-arg? param)) - (list (second param)) + (if (named-arg? param) + (list (named-arg-type param)) param)) arglist)) @@ -344,26 +540,63 @@ (list walked)))) forms)) +;;; #t while the walk is inside a value -- an initializer, an argument, +;;; a returned expression -- where a statement-only form has no C +;;; spelling: +;;; +;;; (var n int (match s ...)) -> int n = switch (s.tag) { ... +;;; +;;; and in a control form's test, which C reads as an expression too: +;;; +;;; (if (match s ...) ...) -> if (switch (s.tag) { ... +(define operand-position? (make-parameter #f)) + +(define (walk-operand form env) + (parameterize ((operand-position? #t)) + (walk-statement form env))) + +;;; FORMS are values written inside PARENT, which is what a diagnostic +;;; about one of them points at -- a bare name has no location of its +;;; own: +;;; +;;; (var f (fn ((r float)) shape) shape/circle) +(define (walk-operands parent forms env) + (for-each (lambda (form) + (when (and (symbol? form) (get-constructor form)) + (sex-error parent + "a constructor is not a function; call it from a lambda" + form))) + forms) + (parameterize ((operand-position? #t)) + (walk-body forms env))) + (define (walk-statement form env) (cond + ((vector? form) (walk-literal form env)) ((not (list? form)) form) ((null? form) form) ;; expanded here rather than before the walk, so the macro body can ;; ask `(type-of x)' about a local the walk has already passed ((macro? form) - (let ((expansion (parameterize - ((current-type-of - (lambda (queried) - (unresolve-closure-types - (expression-type queried env))))) - (macroexpand form (list))))) + (let ((expansion (expand-call form env))) (if (and (pair? expansion) (null? (cdr expansion))) (walk-statement (car expansion) env) (cons walk-embed-result (walk-body expansion env))))) (else (case (car form) - ((do for while if switch) - (with-scope env (lambda () (walk-parts form env)))) + ((do) + (parameterize ((operand-position? #f)) + (with-scope env (lambda () (walk-parts form env))))) + + ((for while if switch) + (with-scope env (lambda () (walk-control form env)))) + + ((case case/fallthrough) + (walk-control form env)) + + ((default) + (parameterize ((operand-position? #f)) + (walk-parts form env))) ((lambda) (let ((name (aux-name! env make-lambda-name))) @@ -380,8 +613,8 @@ (copy-form-source! form `(,construct ,@(map (lambda (capture) - (walk-statement (capture-argument capture) - env)) + (walk-operand (capture-argument capture) + env)) (fourth form)))))))) ((var) @@ -401,7 +634,7 @@ form (append prefix (if (> (length form) 3) - (walk-body (drop form 3) env) + (walk-operands form (drop form 3) env) (list)))) env)) (bound (if (>= (length walked) 4) @@ -418,7 +651,7 @@ bound)) ((return) - (let ((walked (walk-parts form env))) + (let ((walked (copy-form-source! form (walk-operands form form env)))) (if (>= (length walked) 2) (copy-form-source! walked @@ -428,20 +661,119 @@ (cddr walked)))) walked))) + ((match) + (when (operand-position?) + (sex-error form "match is a statement, and has no value")) + (walk-match form env)) + + ((dot-access) (walk-member-path form env)) + (else - (let ((closure (receiver-closure-type (car form) env))) - (if closure - ;; the receiver is walked first: `((closure ((x int)) int - ;; () ...) 5)' registers `struct ƛint_int' on the way, and - ;; the call helper's signature names it - (let ((receiver (walk-statement (car form) env))) - (copy-form-source! - form - `(,(register-closure-call! closure form) - ,receiver - ,@(map (lambda (argument) (walk-statement argument env)) - (cdr form))))) - (convert-arguments (walk-parts form env) env)))))))) + (cond + ((method-head? (car form)) (walk-method-call form env)) + ((get-constructor (car form)) + => (lambda (constructor) (walk-construction form constructor env))) + ((receiver-closure-type (car form) env) + => (lambda (closure) + ;; the receiver is walked first: `((closure ((x int)) + ;; int () ...) 5)' registers `struct ƛint_int' on the + ;; way, and the call helper's signature names it + (let ((receiver (walk-operand (car form) env))) + (copy-form-source! + form + `(,(register-closure-call! closure form) + ,receiver + ,@(walk-operands form (cdr form) env)))))) + (else + (convert-arguments (copy-form-source! form (walk-operands form form env)) + env)))))))) + +;;; (shape/circle 1.0) is the value itself, written where it is used: +;;; +;;; (shape){.tag = shapeǂcircle, .u = {.circle = (struct shapeːcircle){1.0}}} +;;; +;;; so it is a constant where one is wanted, an lvalue a method can take +;;; the address of, and a pub sum pastes nothing into the importer but +;;; its declarations. A lambda argument is converted against its field +;;; the way a call converts one against its parameter. +(define (walk-construction form constructor env) + (let* ((name (car constructor)) + (tag (cdr constructor)) + (fields (variant-fields (get-sum name) tag)) + (args (walk-operands form (cdr form) env))) + (unless (= (length fields) (length args)) + (sex-error form "variant takes this many fields" tag (length fields))) + (sum-literal name tag + (map (lambda (field arg) (field-argument field arg env form)) + fields args)))) + +;;; An array field cannot be handed an array, C copying neither, so it +;;; is handed the array's elements: +;;; +;;; (shape/row #(1 2 3 4)) -> ...(struct shapeːrow){{1, 2, 3, 4}} +;;; (shape/row a) -> ...(struct shapeːrow){{a[0], a[1], a[2], a[3]}} +(define (field-argument field arg env form) + (let ((type (second field))) + (if (not (array-form? type)) + (convert-to-closure type arg env form) + (let ((given (expression-type arg env))) + (cond + ((brace-initializer? arg) + (let ((held (array-length type))) + (when (and held (not (= held (length (remove comment-form? + (vector->list arg)))))) + (sex-error form "array is not as long as its field" (first field)))) + arg) + ((not (array-form? given)) + (sex-error form "an array field takes an array" (first field))) + ((not (eqv? (array-length given) (array-length type))) + (sex-error form "array is not as long as its field" (first field))) + ;; `#([int 4] : 1 2 3 4)' is its own elements + ((vector? arg) (list->vector (cdr (memq ': (vector->list arg))))) + ((not (simple-path? arg)) + (sex-error form "an array is read once per element; bind it to a var first" + (first field))) + (else (spell-out-array type arg))))))) + +(define (array-form? type) + (and (pair? type) (eq? '¤ (car type)))) + +;;; [int 4] -> 4, and [int N] -> 4 after (define N 4); #f for a length +;;; nothing here can count +(define (array-length type) + (and (array-bound? type) + (let ((bound (last type))) + (cond ((and (integer? bound) (exact? bound)) bound) + ((symbol? bound) + (let ((info (get-type-info bound))) + (and info (eq? 'define (car info)) + (let ((value (caddr info))) + (and (= 1 (length value)) + (integer? (car value)) + (exact? (car value)) + (car value)))))) + (else #f))))) + +;;; xs : [int 2] -> #((¤ xs 0) (¤ xs 1)) +(define (spell-out-array type expr) + (list->vector (map (lambda (i) `(¤ ,expr ,i)) (iota (array-length type))))) + +;;; The forms a macro call stands for, with `(type-of x)' answered from +;;; ENV +(define (expand-call form env) + (parameterize ((current-type-of + (lambda (queried) + (unresolve-closure-types (expression-type queried env))))) + (macroexpand form (list)))) + +;;; `#(v : (.get a))' is `(v){vːget(&a)}': the values are expressions +;;; like any other, and the type before `:' is not one +(define (walk-literal form env) + (let* ((parts (vector->list form)) + (elements (or (and (memq ': parts) (cdr (memq ': parts))) parts))) + (list->vector + (append (drop-right parts (length elements)) + (map (lambda (element) (walk-operand element env)) elements))))) ;;; `(var n _ (strlen s))' becomes `(var n size-t (strlen s))'. (define (resolve-wildcard form env) @@ -554,6 +886,243 @@ (define (walk-parts form env) (copy-form-source! form (walk-body form env))) +;;; A control form, its tests walked as values and the rest as +;;; statements +(define (walk-control form env) + (let ((slots (count (lambda (part) (not (comment-form? part))) (cdr form)))) + (let loop ((parts (cdr form)) (i 0) (acc (list (car form)))) + (cond + ((null? parts) (copy-form-source! form (reverse acc))) + ((comment-form? (car parts)) (loop (cdr parts) i (cons (car parts) acc))) + (else + (let ((walked (parameterize ((operand-position? + (test-slot? (car form) i slots))) + (walk-body (list (car parts)) env)))) + (loop (cdr parts) (+ i 1) (append-reverse walked acc)))))))) + +;;; Whether the Ith of a control form's SLOTS is read as a value: an +;;; `if''s tests but not its trailing else, a `for''s header, the +;;; scrutinee of a `while' or a `switch', a `case''s label +(define (test-slot? head i slots) + (case head + ((if) (and (even? i) (< (+ i 1) slots))) + ((for) (< i 3)) + (else (= i 0)))) + +;;; (match s ((circle (r)) ...) ((empty ()) ...)) is a switch over the +;;; tag, each arm a block binding that variant's fields as locals. `_' +;;; drops one. An arm the sum does not have, a wrong number of +;;; binders, or a variant left out with no `else' are all errors here: +;;; a missing case is the thing this form exists to catch. +(define (walk-match form env) + (let* ((scrutinee (and (pair? (cdr form)) (second form))) + ;; a comment between arms goes the way the writer already + ;; drops one between switch clauses + (arms (remove comment-form? (cddr form))) + (type (expression-type scrutinee env)) + (name (ops-key type)) + (variants (and name (get-sum name)))) + (unless variants + (sex-error form "match wants a sum, and this is not one" + (or type 'unknown))) + (check-match form name variants arms) + (if (simple-path? scrutinee) + (walk-statement (match-switch name scrutinee variants arms) env) + ;; the scrutinee is read once per binding, so anything that + ;; could be read twice is read into a local first + (let ((held (aux-name! env make-match-name))) + (walk-statement + `(do (var ,held ,type ,scrutinee) + ,(match-switch name held variants arms)) + env))))) + +(define (make-match-name fn-name 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 +(define (simple-path? expr) + (cond ((symbol? expr) #t) + ((not (pair? expr)) #f) + (else (case (car expr) + ((dot-access %->) (simple-path? (second expr))) + ((*) (and (= 2 (length expr)) (simple-path? (second expr)))) + ((¤) (and (= 3 (length expr)) + (simple-path? (second expr)) + (or (symbol? (third expr)) (number? (third expr))))) + (else #f))))) + +(define (match-arm-variant arm) (and (pair? (car arm)) (car (car arm)))) + +(define (check-match form name variants arms) + (for-each + (lambda (arm) + (unless (and (pair? arm) + (or (eq? (car arm) 'else) + (and (list? (car arm)) (= 2 (length (car arm))) + (list? (second (car arm)))))) + (sex-error form "an arm is ((variant (binders ...)) body ...)" arm))) + arms) + (let* ((else? (lambda (arm) (eq? (car arm) 'else))) + (named (remove else? arms)) + (covered (map match-arm-variant named))) + (when (> (count else? arms) 1) + (sex-error form "match has more than one else")) + (for-each + (lambda (arm) + (let* ((variant (match-arm-variant arm)) + (fields (variant-fields variants variant))) + (unless fields + (sex-error form "not a variant of" name variant)) + (unless (= (length fields) (length (second (car arm)))) + (sex-error form "variant takes this many fields" variant + (length fields))))) + named) + (let ((twice (find (lambda (v) (> (count (cut eq? <> v) covered) 1)) + covered))) + (when twice + (sex-error form "arm is written twice" twice))) + (let ((missing (lset-difference eq? (map car variants) covered))) + (when (and (pair? missing) (not (any else? arms))) + (apply sex-error form "match leaves a variant out:" missing))))) + +(define (match-switch name scrutinee variants arms) + `(switch (dot-access ,scrutinee tag) + ,@(map (lambda (arm) + (if (eq? (car arm) 'else) + `(default (do ,@(cdr arm))) + (let* ((variant (match-arm-variant arm)) + (binders (second (car arm))) + (fields (variant-fields variants variant))) + `(case ,(sum-tag-constant name variant) + (do ,@(match-bindings scrutinee variant binders fields) + ,@(cdr arm)))))) + arms))) + +;;; A binder is a copy of its field, an array one included: +;;; +;;; (var xs [int 2] #((¤ s.u.row.xs 0) (¤ s.u.row.xs 1))) +(define (match-bindings scrutinee variant binders fields) + (filter-map + (lambda (binder field) + (and (not (eq? binder '_)) + (let ((type (second field)) + (path `(dot-access (dot-access (dot-access ,scrutinee u) ,variant) + ,(first field)))) + `(var ,binder ,type + ,(if (array-form? type) (spell-out-array type path) path))))) + binders fields)) + +;;; (.length v) is a call to vec2ːlength; (. v length) is the field +;;; `length', always. Keeping them apart means the shape of a form can +;;; be read without knowing the receiver's type -- (. a b c d) is a +;;; path and (.b a c d) is a call, and adding a field named like a +;;; method cannot quietly turn calls into reads. +;;; +;;; (.length v) -> (vec2ːlength (& v)) +;;; (.length p) -> (vec2ːlength p) +;;; (.sum-of p) -> (vec2ːsum_of (* p)) +;;; +;;; Which of those is written is decided by the receiver's type against +;;; the method's own, so the caller never has to match them up. +(define (method-head? head) + (and (symbol? head) + (let ((spelling (symbol->string head))) + (and (> (string-length spelling) 1) + (char=? #\. (string-ref spelling 0)))))) + +(define (method-head-name head) + (string->symbol (substring (symbol->string head) 1))) + +(define (walk-method-call form env) + (let ((name (method-head-name (car form)))) + (unless (pair? (cdr form)) + (sex-error form "a method call needs a receiver" form)) + (let* ((receiver (second form)) + (written (expression-type receiver env)) + (target (pointer-target written)) + (key (ops-key (or target written)))) + (unless key + (sex-error form "receiver of this has no type to dispatch on" name)) + (let ((method (get-method key name))) + (unless method + (sex-error form "no such method on" key name)) + (copy-form-source! + form + `(,method + ,(method-receiver method (or target written) (and target #t) + (walk-operand receiver env) form) + ,@(walk-operands form (cddr form) env))))))) + +;;; A method taking (* Self) wants an address and one taking Self wants +;;; a value; the receiver is one or the other, so one of the two gets +;;; `&' or `*' put in front of it. +;;; +;;; OBJECT is what the receiver holds or points at: a `(const v)' handed +;;; to a method taking (* v) would be quietly stripped of its const. +(define (method-receiver method object pointer? receiver form) + (let* ((self (method-self-type method)) + (wants-pointer? (and (pair? self) (eq? '* (car self))))) + (when (and wants-pointer? + (const-type? object) + (not (const-type? (pointer-target self)))) + (sex-error form "method may change its receiver, and this one is const" + method)) + (cond ((eq? wants-pointer? pointer?) receiver) + ((not wants-pointer?) `(* ,receiver)) + ;; `&(f())' is not C, and the method cannot be given a + ;; temporary from inside an expression + ((not (lvalue? receiver)) + (sex-error form "receiver is not an lvalue; bind it to a var first" + method)) + (else `(& ,receiver))))) + +;;; `(. p x)' is `p->x' when p is a pointer and `p.x' when it is not: +;;; the receiver's type says which, so a path reads the same however +;;; what it starts from is held. One step at a time, since only the +;;; type in hand can answer for the next field: +;;; +;;; (. l a x) l : (struct line), l.a : (* struct point) -> l.a->x +;;; +;;; A type we cannot work out is read as a value, which is what the +;;; path would have meant before any of this. +(define (walk-member-path form env) + (let ((base (second form))) + (let step ((expr (walk-operand base env)) + (type (expression-type base env)) + (fields (cddr form)) + (told? #f)) + (if (null? fields) + (copy-form-source! form expr) + (let ((target (pointer-target type))) + (unless (or type told?) + (sex-warning form "cannot type this; `.' reads it as a value" + base)) + (step (list (if target '%-> 'dot-access) expr (car fields)) + (field-type (or target type) (car fields)) + (cdr fields) + (or told? (not type)))))))) + +(define (lvalue? expr) + (cond ((symbol? expr) #t) + ((vector? expr) #t) ; a compound literal is one + ((not (pair? expr)) #f) + (else (case (car expr) + ((dot-access %-> ¤) #t) + ((*) (= 2 (length expr))) + (else #f))))) + +(define (method-self-type method) + (let ((signature (get-name-type method))) + (and (pair? signature) + (eq? 'fn (car signature)) + (pair? (cdr signature)) + (pair? (second signature)) + (unwrap-type (car (second signature)))))) + +(define (const-type? type) + (and (pair? type) (eq? 'const (car type)))) + (define (as-closure-type type) (cond @@ -594,7 +1163,17 @@ (let ((written (car parts))) (if (= 1 (length written)) (car written) written))))) ((symbol? expr) (or (lookup-name env expr) (get-name-type expr))) + ;; the walk expands `(the a)' before it gets there, so its type is + ;; that of what it expands to: + ;; + ;; (.len (the a)) (match (the s) ...) (. (the a) x) + ((macro? expr) + (let ((expansion (expand-call expr env))) + (and (pair? expansion) (null? (cdr expansion)) + (expression-type (car expansion) env)))) ((not (and (list? expr) (pair? expr))) #f) + ;; (shape/circle 1.0) -> shape + ((and (symbol? (car expr)) (get-constructor (car expr))) => car) ;; a call of no arguments is still a call ((< (length expr) 2) (and (symbol? (car expr)) (get-return-type (car expr)))) @@ -615,8 +1194,8 @@ (arithmetic-type expr env))) ((dot-access) (member-path-type (expression-type (second expr) env) (cddr expr))) - ((->) (member-path-type (pointer-target (expression-type (second expr) env)) - (cddr expr))) + ((%->) (member-path-type (pointer-target (expression-type (second expr) env)) + (cddr expr))) ((cast) (and (= 3 (length expr)) (third expr))) ((sizeof) 'size-t) ;; `(closure ((x int)) int () ...)' is a `(closure ((int)) int)', @@ -634,13 +1213,25 @@ ;; ...and an increment is the operand unpromoted: ;; (++ c), c : char -> char ((++ --) (expression-type (second expr) env)) - ;; otherwise a call: a closure answers with its own return type, - ;; anything else with what its signature says + ;; otherwise a call: a method answers for the name it resolves + ;; to, a closure with its own return type, anything else with + ;; what its signature says (else - (let ((closure (receiver-closure-type (car expr) env))) - (if closure - (third closure) - (and (symbol? (car expr)) (get-return-type (car expr)))))))))) + (cond + ((method-head? (car expr)) (method-call-type expr env)) + ((receiver-closure-type (car expr) env) => third) + (else (and (symbol? (car expr)) (get-return-type (car expr)))))))))) + +;;; (.length-sq (.sub a b)) types the inner call to find the outer +;;; one's receiver, so a method call has to answer like any other +(define (method-call-type expr env) + (and (pair? (cdr expr)) + (let* ((written (expression-type (second expr) env)) + (target (pointer-target written)) + (key (ops-key (or target written)))) + (and key + (let ((method (get-method key (method-head-name (car expr))))) + (and method (get-return-type method))))))) ;;; C's usual arithmetic conversions, far enough to answer `_': ;;; @@ -729,22 +1320,36 @@ (eq? '* (car type)) (unwrap-type (cdr type)))) +;;; A path looks through a pointer wherever it meets one, the way the +;;; access itself does: `l.a->x' and `l.b.x' are both (. l a x) and +;;; both answer with x's type (define (member-path-type type fields) (if (null? fields) type - (member-path-type (field-type type (car fields)) (cdr fields)))) + (member-path-type (field-type (or (pointer-target type) type) + (car fields)) + (cdr fields)))) (define (field-type type field) - (let ((name (cond ((symbol? type) type) - ((and (list? type) - (= 2 (length type)) - (memq (car type) '(struct union))) - (second type)) - (else #f)))) - (and name - (let* ((fields (get-fields name)) - (entry (and fields (assq field fields)))) - (and entry (second entry)))))) + (let* ((fields (type-fields type)) + (entry (and fields (assq field fields)))) + (and entry (second entry)))) + +;;; `(struct point)' names its fields in the type database. A sum's +;;; payload writes its union out in place -- `(union ((circle (struct +;;; shapeːcircle)) ...))' -- and carries them with it, so there is +;;; nothing to look up +(define (type-fields type) + (cond ((and (list? type) + (= 2 (length type)) + (memq (car type) '(struct union)) + (list? (second type))) + (second type)) + ;; `ops-key' is already the "name of the aggregate" question, + ;; const and all: (* const expr) derefs to (const expr), which + ;; has the fields `expr' has + ((ops-key type) => get-fields) + (else #f))) (define (make-lambda-name enclosing-fn-name counter) (string->symbol @@ -780,19 +1385,13 @@ (define +closure-env-bytes+ 16) -;;; +closure-env-bytes+ for capacity, the widest built-ins for -;;; alignment, hence union -- a union takes the strictest alignment of -;;; its members. `max_align_t' would say the second in one word: -;;; -;;; sexc hello-world.sex -- -std=c99 unknown type name 'max_align_t' +;;; +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+ ((bytes (¤ char ,+closure-env-bytes+)) - (align-integer (long long)) - (align-real (long double)) - (align-pointer (* void)) - (align-code (fn ((* void)) void))))) + `(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)) @@ -949,7 +1548,7 @@ (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)))) + (let ((call `((%-> ƛcaptures f) ,@(map first params)))) (for-each (lambda (emitted) (set! *pending-closure-structs* @@ -967,7 +1566,7 @@ (= (dot-access ƛc code) ,thunk) (var ƛcaptures (* (struct ,record)) (cast (& (dot-access ƛc env)) (* (struct ,record)))) - (= (-> ƛcaptures f) f) + (= (%-> ƛcaptures f) f) (return ƛc)))))) convert)) @@ -1085,7 +1684,7 @@ `((var ƛcaptures (* (struct ,record)) ƛe) ,@(map (lambda (cap) `(var ,(first cap) ,(second cap) - (-> ƛcaptures ,(first cap)))) + (%-> ƛcaptures ,(first cap)))) caps))) ,@body) @@ -1103,7 +1702,7 @@ `((var ƛcaptures (* (struct ,record)) (cast (& (dot-access ƛc env)) (* (struct ,record)))) ,@(map (lambda (cap) - `(= (-> ƛcaptures ,(first cap)) ,(first cap))) + `(= (%-> ƛcaptures ,(first cap)) ,(first cap))) caps))) (return ƛc)))))))) (else (sex-error form "malformed closure" form)))) @@ -1120,6 +1719,126 @@ (register-aggregate! form) (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 +;;; record holding both, and one constructor per variant: +;;; +;;; (var s shape (shape/circle 1.0)) +;;; +;;; The payload structs are plain structs rather than records on +;;; purpose: a record would typedef shapeːcircle into the ordinary +;;; namespace, where the constructor of that name already lives. As a +;;; tag it shares nothing. +(define (process-sum form acc) + (let* ((core (if (eq? (car form) 'pub) (cdr form) form)) + (name (and (pair? (cdr core)) (cadr core))) + (declared (and (pair? (cddr core)) (caddr core)))) + (unless (and (symbol? name) (list? declared) (pair? declared)) + (sex-error form "sum needs a name and a list of variants" form)) + (let ((variants (map (lambda (v) (parse-variant form v)) declared))) + (for-each (lambda (v) + (for-each (lambda (field) (check-variant-field form name field)) + (cdr v))) + variants) + (let* ((names (map car variants)) + (twice (find (lambda (v) (> (count (cut eq? <> v) names) 1)) names))) + (when twice + (sex-error form "variant is declared twice" twice))) + (when (get-sum name) + (sex-error form "sum is already defined" name)) + (add-sum! name variants) + (for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v))) + variants) + (fold match-sex-form acc + (map (lambda (f) (copy-form-source! form f)) + (sum-forms name variants)))))) + +(define (parse-variant form v) + (unless (and (list? v) (= 2 (length v)) (symbol? (car v)) (list? (cadr v))) + (sex-error form "a variant is (name (fields ...))" v)) + (cons (car v) (normalize-fields (cadr v)))) + +;;; (sum expr ((neg ((e expr))))) has no size; (neg ((e (* expr)))) does. +;;; An array field is spelled out element by element wherever it is +;;; copied, so its length has to be one sexc can count. +(define (check-variant-field form name field) + (let ((type (second field))) + (when (holds-by-value? type name) + (sex-error form "a sum holds itself through a pointer" (first field))) + (when (and (array-form? type) (not (array-length type))) + (sex-error form "array field needs a length written as a number" + (first field))))) + +(define (holds-by-value? type name) + (cond ((eq? type name) #t) + ((not (pair? type)) #f) + ((memq (car type) '(struct const volatile)) + (and (pair? (cdr type)) (holds-by-value? (cadr type) name))) + ((array-form? type) (holds-by-value? (array-element-type type) name)) + (else #f))) + +(define (sum-forms name variants) + (let ((carried (filter (lambda (v) (pair? (cdr v))) variants))) + `(;; forward, so a variant may hold a pointer back to the sum + (typedef ,name (struct ,name)) + (enum ,(sum-tag name) + ,(map (lambda (v) (sum-tag-constant name (car v))) variants)) + ,@(map (lambda (v) `(struct ,(qualify-op name (car v)) ,(cdr v))) + carried) + (struct ,name + ((tag (enum ,(sum-tag name))) + ,@(if (null? carried) + (list) + `((u (union ,(map (lambda (v) + `(,(car v) + (struct ,(qualify-op name (car v))))) + carried)))))))))) + +;;; #(shape : .tag shapeǂcircle .u #(.circle #((struct shapeːcircle) : 1.0))) +(define (sum-literal name tag values) + (list->vector + (append (list name ': (dotted 'tag) (sum-tag-constant name tag)) + (if (null? values) + (list) + (list (dotted 'u) + (vector (dotted tag) + (list->vector + (append (list (list 'struct (qualify-op name tag)) ':) + values)))))))) + +(define (dotted name) + (string->symbol (string-append "." (symbol->string name)))) + +;;; shape -> enum shapeǂ, circle -> shapeǂcircle. Not shapeːtag: that +;;; is where a variant named `tag' keeps its payload struct, and an enum +;;; and a struct share C's tag namespace. +(define (sum-tag name) + (string->symbol (string-append (symbol->string name) "ǂ"))) + +(define (sum-tag-constant name variant) + (string->symbol (string-append (symbol->string (sum-tag name)) + (symbol->string variant)))) + +;;; (record point ((x int) (y int))) is a struct that also names +;;; itself, so `point' alone stands where `(struct point)' had to: +;;; (var p point ...), (* const point), (sizeof point). +;;; +;;; struct, union and enum keep C's meaning, for a type that comes from +;;; a header or is laid out to match one. +(define (process-record form acc) + (let* ((core (if (eq? (car form) 'pub) (cdr form) form)) + (name (and (pair? (cdr core)) (cadr core)))) + (unless (symbol? name) + (sex-error form "record needs a name" form)) + (add-typedef name `(typedef ,name (struct ,name))) + (cons (copy-form-source! form `(typedef (struct ,name) ,name)) + (process-struct + (copy-form-source! form + (if (eq? (car form) 'pub) + `(pub struct ,@(cdr core)) + `(struct ,@(cdr core)))) + acc)))) + (define (register-aggregate! form) (let* ((f (if (eq? (car form) 'pub) (cdr form) form)) (name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f)))) @@ -1133,28 +1852,56 @@ ;;; No function around a toplevel form, so no scope chain: what a ;;; global's initializer names comes from `get-name-type' alone. -(define (make-toplevel-env) +;;; What a global's initializer is walked in: no names but its own, +;;; and anything it lifts is named after the global +(define (make-toplevel-env name) (let ((env (make-hash-table))) + (set! (hash-table-ref env :fn-name) name) + (set! (hash-table-ref env :lambda-counter) 0) + (set! (hash-table-ref env :lambda-aux-code) (list)) (set! (hash-table-ref env :scopes) (list)) env)) +;;; The writer spells neither `closure' nor `_', and an initializer is +;;; an expression like any other: +;;; +;;; (var n _ 1) -> int n = 1 +;;; (var o v #(v : (.get a))) -> v o = (v){vːget(&a)} (define (process-global-var sex-var acc) - ;; A global is not walked for lambdas, but the writer spells neither - ;; `closure' nor `_': `(var n _ 1)' has to reach it as `int n = 1' (let* ((resolved (resolve-closure-types sex-var)) (qualifier (and (memq (car resolved) '(pub extern)) (car resolved))) (core (if qualifier (cdr resolved) resolved)) + (env (make-toplevel-env (and (pair? (cdr core)) (second core)))) ;; `(extern var n int)' has no initializer to work a `_' out ;; from (core (if (eq? 'extern qualifier) core - (resolve-wildcard core (make-toplevel-env)))) + (let ((solved (resolve-wildcard + (copy-form-source! + core + (if (> (length core) 3) + (append (take core 3) + (walk-operands core (drop core 3) env)) + core)) + env))) + (copy-form-source! solved (map bare-braces solved))))) (form (if qualifier (copy-form-source! resolved (cons qualifier core)) core))) (when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core))) (add-name-type! (second core) (third core))) - (cons form acc))) + (cons form (append (hash-table-ref env :lambda-aux-code) acc)))) + +;;; A compound literal is not a constant, though cc lets one pass at file +;;; scope unless asked to be pedantic; where it initializes, its braces +;;; alone say the same: +;;; +;;; (var g t (t/a 1)) -> static t g = {.tag = tǂa, .u = {.a = {1}}} +(define (bare-braces form) + (if (vector? form) + (let ((parts (list-split (vector->list form) ':))) + (list->vector (map bare-braces (last parts)))) + form)) ;;; Utils (define (non-empty-list? form) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index fd05daf..89f8835 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -110,10 +110,19 @@ (define (c-paren x) (cat "(" (c-expr x) ")")) + ;; `.' and `->' associate left, and their right operand is always a + ;; name, so a member access written inside another is the left one + ;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r' + (define (c-member-op? x) + (let ((str (display-to-string x))) + (or (string=? str ".") (string=? str "->")))) + (define (c-maybe-paren op x) (lambda (st) ((fmt-let 'op op (if (and (c-op<= (fmt-op st) op) + (not (and (c-member-op? (fmt-op st)) + (c-member-op? op))) (not (vector? x))) (c-paren x) x)) @@ -297,8 +306,6 @@ (cond ((eq? (car x) (string->symbol ".")) ((apply c-op "." (cdr x)) st)) - ((eq? (car x) (string->symbol "->")) - ((apply c-op "->" (cdr x)) st)) ((eq? (car x) (string->symbol "++")) ((apply c-op "++" (cdr x)) st)) ((eq? (car x) (string->symbol "--")) diff --git a/sex-macros.scm b/sex-macros.scm index 350bddb..327c180 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -32,7 +32,11 @@ (only types get-type-info get-tag-info get-fields get-underlying-type type-match type-pattern-matches? map-fields - get-name-type get-return-type type-of)) + get-name-type get-return-type type-of + ;; 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) diff --git a/sex-mode.el b/sex-mode.el index b2197d0..3531666 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -38,8 +38,13 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") "import" "include" "fn" + "ops" "pub" + "record" + "realize" + "spec" "struct" + "sum" "var" "union") 'word) @@ -58,6 +63,7 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") "if" "for" "goto" + "match" "return" "switch" "var" @@ -81,6 +87,12 @@ All commands in `lisp-mode-shared-map' are inherited by this map.") (put 'fn 'lisp-indent-function 'defun) (put 'pub 'lisp-indent-function 'defun) (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) (put 'union 'lisp-indent-function 'defun) (put 'var 'lisp-indent-function 0) diff --git a/sex-modules.scm b/sex-modules.scm index 9939bd8..c3f1c61 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -11,6 +11,7 @@ matchable reader srfi-1 + types utils) (define +persistent-module-paths+ (list)) @@ -42,7 +43,20 @@ (define (get-module-paths) (cons (current-directory) - +persistent-module-paths+)) + (append +persistent-module-paths+ (standard-library-paths)))) + +;;; Where the modules shipped with the compiler live. Asked of the +;;; binary rather than baked in when it is built: in a work tree sexc +;;; sits beside lib/, and installed it sits in bindir with the modules +;;; under ../share/sex. Last in the search order, so a module of one's +;;; own wins over one of ours by the same name +(define (standard-library-paths) + (let ((binary (executable-pathname))) + (if binary + (let ((bin (pathname-directory binary))) + (list (make-pathname bin "lib") + (make-pathname (list (pathname-directory bin) "share") "sex"))) + (list)))) (define (locate-module name) ;; Module locations: relative to file being compiled, or in what was @@ -65,12 +79,16 @@ module-path)))) (define (read-public-interface module-path) - ;; pub fns are reduced to prototypes, other pub forms are just pasted + ;; pub fns are reduced to prototypes, other pub forms are just pasted. + ;; Declaration order is kept: a module that declares a type and then a + ;; pub fn taking it has to paste them that way round, or the prototype + ;; names a type C has not seen. (let ((raw-forms (read-from-file module-path))) - (fold - process-public-interface-form - (list) - raw-forms))) + (reverse + (fold + process-public-interface-form + (list) + raw-forms)))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so @@ -86,6 +104,35 @@ (('pub 'fn name args ret . _) `(pub fn ,name ,args ,ret))))) +;;; An ops block is not pub itself -- its methods are. The block leaves +;;; as a block, its pub methods reduced to prototypes, so the importer +;;; runs its own `process-ops' over it: prototypes alone would say that +;;; vec2ːlength exists without saying that vec2 has a `length', and +;;; (. v length) needs the second thing. +(define (ops-public-interface form) + (let ((type (and (pair? (cdr form)) (cadr form))) + (methods (filter (lambda (m) + (and (pair? m) (eq? (car m) 'pub) + (pair? (cdr m)) (eq? (cadr m) 'fn))) + (cddr form)))) + (and (symbol? type) + (pair? methods) + (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 @@ -96,8 +143,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 'struct '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))) diff --git a/tests/Makefile b/tests/Makefile index deae867..1e87b3c 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -6,7 +6,7 @@ MODULE_FLAGS = -emit-all-import-libraries -module-registration -c MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc SEX_OBJ = $(MODULES:%=%.o) -TESTS = basic semen reader fmt-c-writer utils line-directives codegen args types infer +TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args types infer TEST_SRCS = $(TESTS:%=%.scm) sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ) @@ -29,8 +29,8 @@ sex-macros.o: sex-macros.module.scm ../sex-macros.scm reader.o: reader.module.scm ../reader.scm utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils -sex-modules.o: sex-modules.module.scm ../sex-modules.scm reader.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils +sex-modules.o: sex-modules.module.scm ../sex-modules.scm reader.o types.o utils.o + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils semen.o: semen.module.scm ../semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils diff --git a/tests/codegen.scm b/tests/codegen.scm index 51b0a48..7fe9c25 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -26,8 +26,16 @@ (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 (sex->c source) fragment) #t)) + (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) (define (error-message source) "Compile SOURCE and return the error text as the user sees it -- @@ -48,6 +56,23 @@ compiles." (define (in-fn body) (string-append "(fn f ((a int) (b int)) void " body ")")) +;;; A struct, a struct holding a pointer to one, and locals of every +;;; shape a member path can start from +(define (in-line body) + (string-append + "(struct point ((x int) (y int)))" + "(struct line ((a (* struct point)) (b (struct point))))" + "(fn f ((lp (* struct line))) void" + " (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" ;; c-switch handed its scrutinee straight to `cat', which only works @@ -394,6 +419,31 @@ compiles." (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. + (test-group "include targets are paths" + (test-assert "a slash survives" + (emits? "(include SDL3/SDL.h)" "#include ")) + (test-assert "and so does a dash" + (emits? "(include my-header.h)" "#include ")) + (test-assert "pub include emits the same" + (emits? "(pub include GL/gl.h)" "#include "))) + + ;; The walker offered WALK-FN the cdr of every form as well as the + ;; form, so the tail (t) of (fn g () t) read as a call to a macro + ;; named t, and any function returning a type that shared a name + ;; with a macro died on that macro's arity. + (test-group "a form's tail is not a form" + (test-assert "a return type may share a name with a macro" + (emits? "(defmacro (t x) 1)(typedef t int)(fn g () t (return 1))" + "t g (void)")) + (test-assert "so may a parameter's type" + (emits? "(defmacro (u x) 1)(typedef u int)(fn g ((a u)) void (return))" + "void g (u a)")) + (test-assert "and the macro still expands where it is called" + (emits? "(defmacro (t x) x)(fn g () int (return (t 7)))" + "return 7"))) + ;; a macro body reads types as lists, so the srfi-1 accessors are in ;; scope beside the type database (test-group "macro list accessors" @@ -608,4 +658,65 @@ compiles." (test-assert "nor is an aggregate tag" (emits? "(struct t ((z int))) (struct s ((a (¤ struct t))))" "struct t a[]")) (test-assert "nor one behind a pointer" - (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]")))) + (emits? "(struct t ((z int))) (struct s ((a (¤ * struct t))))" "struct t* a[]"))) + + ;; `.' is C's `.' or its `->' depending on what is being read from, + ;; so a path reads the same however the thing it starts from is held + (test-group "member access" + (test-assert "a value reads with a dot" + (emits? (in-line "(= (. p x) 1)") "p.x = 1")) + (test-assert "a pointer reads with an arrow" + (emits? (in-line "(= (. pp x) 1)") "pp->x = 1")) + ;; each step asks the type in hand, so one path may be both + (test-assert "a pointer field inside a value" + (emits? (in-line "(= (. l a x) 1)") "l.a->x = 1")) + (test-assert "a value field inside a pointer" + (emits? (in-line "(= (. lp b y) 1)") "lp->b.y = 1")) + (test-assert "and two pointers in a row" + (emits? (in-line "(= (. lp a x) 1)") "lp->a->x = 1")) + ;; a path is left-associative and its right operand is always a + ;; name, so none of it needs parenthesising + (test-assert "a path carries no parens" + (not (emits? (in-line "(= (. lp a x) 1)") "(lp->a)"))) + ;; ...which is not to say nothing does + (test-assert "though a dereference still does" + (emits? (in-line "(= (. (* pp) x) 1)") "(*pp).x = 1")) + (test-assert "a type we cannot work out is read as a value" + (emits? (in-line "(= (. (guess) x) 1)") "guess().x = 1")) + (test-assert "and said so" + (warns? (in-line "(= (. (guess) x) 1)") "cannot type this")) + ;; the arrow is `%->' and nothing else writes one, so a bare `->' + ;; is an ordinary head -- a threading macro that nobody imported, + ;; and a call like any other unknown + (test-assert "a bare -> is not the arrow" + (emits? (in-line "(= (-> pp x) 1)") "->(pp, x) = 1"))) + + ;; A global's initializer is an expression like a local's, and walked + ;; the same way + (test-group "global initializers" + (test-assert "a path is dispatched on its type" + (emits? (string-append "(struct pt ((x int)))" + "(var a (struct pt) #((struct pt) : 1))" + "(var q (* int) (& (. a x)))") + "int * q = &a.x")) + (test-assert "a lambda is lifted, and named after the global" + (emits? "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))" + "int (*f)(int) = λ0_f")) + (test-assert "ahead of it" + (let ((c (sex->c "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))"))) + (< (string-contains c "static int λ0_f (int x)") + (string-contains c "(*f)(int) = λ0_f"))))) + + ;; Toplevel forms used to be separated by a blank line unconditionally, + ;; which spread a block of adjacent typedefs over twice the lines its + ;; author wrote + (test-group "vertical spacing" + (test-assert "adjacent forms stay adjacent" + (emits? "(include a.h)\n(include b.h)" "#include \n#include ")) + (test-assert "a blank line is kept" + (emits? "(include a.h)\n\n(include b.h)" "#include \n\n#include ")) + ;; the gap is measured from where the form ended, not where it began + (test-assert "a multi-line form does not invent one" + (emits? "(struct s\n ((x int)))\n(include b.h)" "};\n#include ")) + (test-assert "nor swallows one" + (emits? "(struct s\n ((x int)))\n\n(include b.h)" "};\n\n#include ")))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm new file mode 100644 index 0000000..8df2b09 --- /dev/null +++ b/tests/encapsulation.scm @@ -0,0 +1,476 @@ +;;; record, ops, sum and match, through the whole pipeline. +;;; +;;; The diagnostics are the point of these forms -- a match that +;;; leaves a variant out is the thing C cannot say -- so most of what +;;; is checked here is what the compiler refuses, and that it refuses +;;; it with the name of whatever is wrong. +;;; +;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, +;;; which run.scm includes first. + +(define (ops-src . body) + (string-append + "(record vec2 ((x float) (y float)))" + "(ops vec2" + " (pub fn length ((self (* const vec2))) float (return 1.0))" + " (fn sum-of ((self vec2)) float (return (. self x)))" + " (fn scale ((self (* vec2))) void (= (. self x) 2.0)))" + "(fn mk () vec2 (return #(vec2 : 1.0 2.0)))" + "(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) " + (apply string-append body) ")")) + +(define (sum-src . body) + (string-append + "(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))" + "(fn mk () shape (return (shape/circle 1.0)))" + "(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 + ;; name stands where (struct name) had to. + (test-group "record" + (test-assert "emits the struct" + (emits? "(record point ((x int) (y int)))" "struct point {")) + (test-assert "and a typedef of the same name" + (emits? "(record point ((x int) (y int)))" "typedef struct point point;")) + (test-assert "so the bare name is a type" + (emits? "(record point ((x int)))(fn f () void (var p point))" "point p;")) + (test-assert "and so is a pointer to it" + (emits? "(record point ((x int)))(fn f () void (var p (* const point)))" + "const point * p")) + (test-assert "struct keeps C's meaning" + (not (emits? "(struct raw ((x int)))" "typedef"))) + (test-assert "a record needs a name" + (reports? "(record ((x int)))" "record needs a name")) + ;; An opaque handle: the declaration is public, the fields are not + (test-assert "declared, then defined, is still defined" + (emits? "(pub record h)(record h ((x int)))" "struct h {"))) + + ;; An ops block is mangled functions plus a registry entry. `pub' + ;; inside it means what it means outside. + (test-group "ops" + (test-assert "a method is the type and the name, mangled" + (emits? (ops-src "") "float vec2ːlength")) + (test-assert "a pub method has external linkage" + (not (emits? (ops-src "") "static float vec2ːlength"))) + (test-assert "a private one does not" + (emits? (ops-src "") "static float vec2ːsum_of")) + (test-assert "the slash is not a division" + (emits? "(fn f () int (return (/ 10 2)))" "10 / 2")) + (test-assert "ops needs a type name" + (reports? "(ops (fn g ((s int)) void))" "ops needs a type name")) + (test-assert "and takes only fn forms" + (reports? "(record v ((x int)))(ops v (var n int 1))" "ops takes fn forms")) + (test-assert "a method is defined once" + (reports? (string-append "(record v ((x int)))" + "(ops v (fn g ((s v)) int (return 1))" + " (fn g ((s v)) int (return 2)))") + "method is already defined on")) + (test-assert "pub goes on the methods, not the block" + (reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))) + + ;; The method sits in the head, so the shape of a form can be read + ;; without knowing the receiver's type. + (test-group "method calls" + (test-assert "a value meeting a pointer self is addressed" + (emits? (ops-src "(.length v)") "vec2ːlength(&v)")) + (test-assert "a pointer meeting a pointer self is passed along" + (emits? (ops-src "(.length p)") "vec2ːlength(p)")) + (test-assert "a pointer meeting a value self is dereferenced" + (emits? (ops-src "(.sum-of p)") "vec2ːsum_of(*p)")) + (test-assert "a value meeting a value self is passed along" + (emits? (ops-src "(.sum-of v)") "vec2ːsum_of(v)")) + (test-assert "a field is still a field" + (emits? (ops-src "(var q float (. v x))") "v.x")) + ;; the whole reason the method moved into the head + (test-assert "a field and a method of one name coexist" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn x ((self (* const w))) int (return 2)))" + "(fn f () void (var a w #(w : 1)) (var b int (. a x))" + " (var c int (.x a)))") + "wːx(&a)")) + (test-assert "and the field reading is untouched" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn x ((self (* const w))) int (return 2)))" + "(fn f () void (var a w #(w : 1)) (var b int (. a x)))") + "int b = a.x")) + (test-assert "a method that is not there is named" + (reports? (ops-src "(.nope v)") "no such method on")) + (test-assert "and so is a receiver with no type to dispatch on" + (reports? "(fn f () void (var n int 1) (.get n))" "no such method on")) + (test-assert "a self spread over the parameter is a pointer self too" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn get ((self * const w)) int (return (. self x))))" + "(fn f () int (var a w #(w : 1)) (var p (* const w) (& a))" + " (return (+ (.get a) (.get p))))") + "wːget(&a) + wːget(p)")) + (test-assert "a const receiver is not handed to a method that may change it" + (reports? (ops-src "(var c (* const vec2) p) (.scale c)") + "this one is const")) + (test-assert "one that cannot change it takes it" + (emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))") + "vec2ːlength(c)")) + (test-assert "a macro receiver is typed by what it expands to" + (emits? (string-append "(defmacro (the a) a)" + (ops-src "(var n float (.length (the v)))")) + "vec2ːlength(&v)")) + (test-assert "and so is the start of a path" + (emits? (string-append "(defmacro (the a) a)" + (ops-src "(var q float (. (the p) x))")) + "p->x")) + (test-assert "a typedef of the type has its methods" + (emits? (string-append + "(record w ((x int)))" + "(typedef alias w)" + "(ops w (fn get ((self (* const w))) int (return (. self x))))" + "(fn f () int (var a alias #(alias : 1)) (return (.get a)))") + "wːget(&a)")) + (test-assert "and a method written on the typedef is the type's" + (emits? (string-append + "(record w ((x int)))" + "(typedef alias w)" + "(ops alias (fn get ((self (* const alias))) int (return 1)))" + "(fn f () int (var a w #(w : 1)) (return (.get a)))") + "aliasːget(&a)")) + (test-assert "a typedef of a scalar keeps its own" + (reports? (string-append + "(typedef meters float)" + "(ops meters (fn half ((self meters)) meters (return self)))" + "(fn f () void (var x float 1.0) (.half x))") + "no such method on")) + (test-assert "which a typedef of it shares" + (emits? (string-append + "(typedef meters float)" + "(typedef km meters)" + "(ops meters (fn half ((self meters)) meters (return self)))" + "(fn f () void (var x km 1.0) (var y km (.half x)))") + "metersːhalf(x)")) + (test-assert "a method call inside a literal is still a call" + (emits? (ops-src "(var w vec2 #(vec2 : (.length v) 1.0))") + "(vec2){vec2ːlength(&v), 1.0}")) + (test-assert "however deep" + (emits? (ops-src "(var ws [vec2 1] #(#(vec2 : (.length p) 1.0)))") + "{(vec2){vec2ːlength(p), 1.0}}")) + (test-assert "an address cannot be taken of a call" + (reports? (ops-src "(.length (mk))") "receiver is not an lvalue")) + ;; the inner call has to be typed to find the outer one's receiver + (test-assert "a method call can be another's receiver" + (emits? (string-append + "(record w ((x int)))" + "(ops w (fn twice ((a w)) w (return a))" + " (fn get ((a w)) int (return (. a x))))" + "(fn f () int (var a w #(w : 1)) (return (.get (.twice a))))") + "wːget(wːtwice(a))"))) + + ;; A sum is the tag enum, a payload struct per variant that carries + ;; fields, the record holding both, and a constructor each. + (test-group "sum" + (test-assert "the tag enum is named after the sum" + (emits? (sum-src "") "enum shapeǂ {")) + (test-assert "and its constants after the sum and the variant" + (emits? (sum-src "") "shapeǂcircle")) + (test-assert "a variant may be called tag" + (emits? "(sum t ((tag ((x int))) (none ())))" "struct tːtag {")) + (test-assert "a variant with fields gets a payload struct" + (emits? (sum-src "") "struct shapeːcircle {")) + (test-assert "the sum is typedef'd" + (emits? (sum-src "") "typedef struct shape shape;")) + ;; a typedef here would land in the namespace the constructor holds + (test-assert "a payload struct is not" + (not (emits? (sum-src "") "typedef struct shapeːcircle"))) + (test-assert "the typedef comes before the payloads, for a recursive sum" + (emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))" + "typedef struct expr expr;")) + (test-assert "a constructor is written in place" + (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" + "(struct tːa){1}")) + (test-assert "and is no function" + (not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" + "t tːa ("))) + (test-assert "so it is a constant at file scope" + (emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" + "static t g = {.tag = tǂa, .u = {.a = {1}}};")) + (test-assert "as is any literal a global starts from" + (emits? "(record point ((x int) (y int)))(var g point #(point : 1 2))" + "static point g = {1, 2};")) + (test-assert "and an lvalue a method can take the address of" + (emits? (string-append + "(sum t ((a ((x int)))))" + "(ops t (fn get ((self (* const t))) int (return 1)))" + "(fn f () int (return (.get (t/a 1))))") + "tːget(&(t){")) + (test-assert "a constructor takes as many arguments as its variant has fields" + (reports? "(sum t ((a ((x int)))))(fn f () t (return (t/a 1 2)))" + "variant takes this many fields")) + (test-assert "and is not a function value" + (reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))" + "a constructor is not a function")) + (test-assert "an array field takes a brace literal as it is" + (emits? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2))))" + "(struct tːa){{1, 2}}")) + (test-assert "and an array by its elements" + (emits? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 2] #(1 2)) (return (t/a v)))" + "(struct tːa){{v[0], v[1]}}")) + (test-assert "which have to be countable" + (reports? "(fn n () int (return 2))(sum t ((a ((xs [int (n)])))))" + "array field needs a length")) + (test-assert "and as many as the field holds" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))" + "array is not as long as its field")) + (test-assert "and so must a literal" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2 3))))" + "array is not as long as its field")) + (test-assert "not filling it with zeros either" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1))))" + "array is not as long as its field")) + (test-assert "an array field takes an array" + (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))" + "an array field takes an array")) + (test-assert "read from a path, not from a call" + (reports? (string-append "(sum t ((a ((xs [int 2])))))(fn g () int (return 0))" + "(fn f () t (var m [t 2]) (return (t/a (. [m (g)] u a xs))))") + "bind it to a var first")) + (test-assert "an array binder is a copy of each element" + (emits? (string-append "(sum t ((a ((xs [int 2])))))" + "(fn f ((s t)) int (match s ((a (xs)) (return [xs 0]))))") + "int xs[2] = {s.u.a.xs[0], s.u.a.xs[1]}")) + (test-assert "a sum cannot hold itself" + (reports? "(sum box ((inner ((x box)))))" "a sum holds itself through a pointer")) + (test-assert "nor an array of itself" + (reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer")) + (test-assert "though it can point at itself" + (emits? "(sum box ((inner ((x (* box))))))" "box * x;")) + (test-assert "a function argument becomes the closure its field holds" + (emits? (string-append + "(fn g ((n int)) int (return n))" + "(sum t ((a ((k (closure ((int)) int))))))" + "(fn f () t (return (t/a g)))") + "ƛint_int_fromfn(g)")) + (test-assert "a tag-only sum has no union at all" + (not (emits? "(sum light ((red ()) (green ())))" "union"))) + (test-assert "a sum is declared once" + (reports? "(sum t ((a ())))(sum t ((b ())))" "sum is already defined")) + (test-assert "and needs variants" + (reports? "(sum t)" "sum needs a name and a list of variants")) + (test-assert "a variant is a name and a field list" + (reports? "(sum t (a))" "a variant is")) + (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 a switch over the tag whose arms bind the payload. What + ;; it refuses is why it exists. + (test-group "match" + (test-assert "it switches on the tag" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" + " ((empty ()) (= out 0.0)))") + "switch (s.tag)")) + (test-assert "an arm binds its payload" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" + " ((empty ()) (= out 0.0)))") + "float r = s.u.circle.r")) + (test-assert "_ binds nothing" + (not (emits? (sum-src "(match s ((circle (r)) (= out r))" + " ((rect (w _)) (= out w))" + " ((empty ()) (= out 0.0)))") + ").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()")) + (test-assert "a path scrutinee is not copied" + (not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "ƛm0"))) + (test-assert "a macro scrutinee is typed by what it expands to" + (emits? (string-append "(defmacro (the a) a)" + (sum-src "(match (the s) ((circle (r)) (= out r))" + " (else (= out 0.0)))")) + "shape ƛm0 = s")) + (test-assert "a typedef of a sum is matched as the sum" + (emits? (string-append + "(sum shape ((circle ((r int))) (empty ())))" + "(typedef alias shape)" + "(fn f () int (var s alias (shape/circle 1))" + " (match s ((circle (r)) (return r)) ((empty ()) (return 0))))") + "case shapeǂcircle")) + (test-assert "else becomes default" + (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "default:")) + (test-assert "a comment between arms is dropped" + (emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 0.0)))") + "default:")) + + (test-assert "a variant left out is an error" + (reports? (sum-src "(match s ((circle (r)) (= out r)))") + "match leaves a variant out")) + (test-assert "and the missing ones are named" + (reports? (sum-src "(match s ((circle (r)) (= out r)))") "rect")) + (test-assert "else excuses the rest" + (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") + "switch (s.tag)")) + (test-assert "a variant the sum does not have is an error" + (reports? (sum-src "(match s ((circle (r)) (= out r)) ((square (w)) (= out w))" + " ((rect (w h)) (= out w)) ((empty ()) (= out 0.0)))") + "not a variant of")) + (test-assert "so is the wrong number of binders" + (reports? (sum-src "(match s ((circle (r q)) (= out r)) (else (= out 0.0)))") + "variant takes this many fields")) + (test-assert "so is the same arm twice" + (reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))" + " (else (= out 0.0)))") + "arm is written twice")) + (test-assert "so is a second else" + (reports? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0))" + " (else (= out 1.0)))") + "more than one else")) + (test-assert "so is an arm that is not one" + (reports? (sum-src "(match s foo)") "an arm is")) + (test-assert "match has no value" + (reports? (sum-src "(var n float (match s ((circle (r)) r) (else 0.0)))") + "match is a statement")) + (test-assert "not even as an argument" + (reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))") + "match is a statement")) + (test-assert "nor as an if's test" + (reports? (sum-src "(if (match s ((circle (r)) 1) (else 0)) (= out 1.0))") + "match is a statement")) + (test-assert "nor as a while's" + (reports? (sum-src "(while (match s ((circle (r)) 1) (else 0)) (= out 1.0))") + "match is a statement")) + (test-assert "nor in a for's header" + (reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)" + " (= out 1.0))") + "match is a statement")) + (test-assert "nor as a case label" + (reports? (sum-src "(switch 1 (case (match s ((circle (r)) 1) (else 0)) (= out 1.0)))") + "match is a statement")) + (test-assert "nor as a case/fallthrough's" + (reports? (sum-src "(switch 1 (case/fallthrough (match s ((circle (r)) 1) (else 0))" + " (= out 1.0)))") + "match is a statement")) + (test-assert "but an if's branches are statements, the else among them" + (emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))" + " (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))") + "out = 3.0;")) + (test-assert "but a case body is a statement" + (emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))" + " (else (= out 0.0)))))") + "switch (s.tag)")) + (test-assert "and so is a closure's, wherever the closure stands" + (emits? (sum-src "(var c (closure () int) (closure () int ((t s))" + " (match t ((circle (r)) (return 1)) (else (return 0)))))") + "switch (t.tag)")) + (test-assert "and a scrutinee that is not a sum" + (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" + "match wants a sum")))) diff --git a/tests/line-directives.scm b/tests/line-directives.scm index db74cd4..fa11abd 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -97,7 +97,7 @@ (define (compile-to-c source) "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 is (file . line), and 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 diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 5ff1468..034cd95 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -13,14 +13,15 @@ # 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. +# 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. SEXC ?= ../../sexc -EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201 +EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\ncolour 123 check: @$(SEXC) greet.sex -c -o greet.o diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 5903f81..7675207 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -33,4 +33,22 @@ (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) + (.bump t) + (printf "tally %d\n" (.count t)) + (.drop t) + + (var c colour (colour/rgb 1 2 3)) + (match c + ((rgb (r g b)) (printf "colour %d%d%d\n" r g b)) + ((none ()) (printf "colour none\n"))) (return 0)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 43da31e..3da58b3 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -5,7 +5,8 @@ ;;; the compiled object still has to be handed to the C compiler. See ;;; greet-app.sex. -(include stdio.h) +(pub include stdio.h) +(include stdlib.h) (pub var greet-count ;; a comment in the header of a public form is ;; not part of it: what the importer is given has @@ -48,6 +49,55 @@ (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 +;;; loose prototypes, or the importer learns that vec2ːmanhattan exists +;;; without learning that vec2 has a `manhattan' -- and (. v manhattan) +;;; needs the second thing. +(pub record vec2 ((x int) (y int))) + +(ops vec2 + (pub fn manhattan ((self (* const vec2))) int + (return (+ (. self x) (. self y))))) + +;;; An opaque record: the handle is public and the fields are not, so +;;; the importer holds a (* tally) and reaches it only through methods. +(pub record tally) + +(record tally ((n int))) + +(ops tally + (pub fn make () (* tally) + (var t (* tally) (malloc (sizeof tally))) + (= (. t n) 0) + (return t)) + (pub fn bump ((self (* tally))) void + (++ (. self n))) + (pub fn count ((self (* const tally))) int + (return (. self n))) + (pub fn drop ((self (* tally))) void + (free self))) + +;;; A pub sum is pasted whole, so the importer builds its own copy of +;;; the declarations; a constructor is written in place where it is +;;; called, so there is no function for two units to both define. +(pub sum colour ((rgb ((r int) (g int) (b int))) (none ()))) + +;;; A spec and a realization over the boundary. The written method +;;; 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")) diff --git a/tests/run.scm b/tests/run.scm index 4f77bfa..d0cc9ca 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -8,6 +8,7 @@ (include "utils.scm") (include "line-directives.scm") (include "codegen.scm") +(include "encapsulation.scm") (include "args.scm") (include "types.scm") (include "infer.scm") diff --git a/tests/sex-programs/c11.sex b/tests/sex-programs/c11.sex new file mode 100644 index 0000000..375503d --- /dev/null +++ b/tests/sex-programs/c11.sex @@ -0,0 +1,45 @@ +(compilation "-- -std=c11 -pedantic-errors") +(input) +(output "c11: 42 43 6 4 6 12") +(return 0) + +;;; C11 is the floor, and this is the program that holds it there: the +;;; C every feature emits has to build under it with no extension, so +;;; one that reaches past it -- a GNU statement expression, a C23 +;;; keyword -- fails here rather than on a user's compiler. +;;; +;;; 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. + +(include stdio.h) + +(record point ((x int) (y int))) + +(ops point + (fn area ((self (* const point))) int + (return (* (. self x) (. self y))))) + +(sum shape ((square ((side int))) (dot ()))) + +(var corner _ #(point : 2 3)) +(var unit _ (shape/square 1)) +(var pair [_ 2] #(#(point : 1 2) #(point : 3 4))) + +(fn sides ((s shape)) int + (var n int 0) + (match s + ((square (side)) (= n (* 4 side))) + ((dot ()) (= n 0))) + (return n)) + +(pub fn main () int + (var p point #(point : 6 7)) + (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\n" + (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) + (sides unit) (.area corner) (.area [pair 1])) + (return 0)) diff --git a/tests/sex-programs/c99.sex b/tests/sex-programs/c99.sex deleted file mode 100644 index f65cd37..0000000 --- a/tests/sex-programs/c99.sex +++ /dev/null @@ -1,28 +0,0 @@ -(compilation "-- -std=c99 -pedantic-errors") -(input) -(output "c99: 42") -(return 0) - -;;; The closure environment is part of the ABI, so its union is declared -;;; in every translation unit whether or not one is used. That put -;;; whatever it was written with into every program: `max_align_t' named -;;; the alignment in one word, and made C11 the floor for a program with -;;; no closure in it at all. -;;; -;;; The widest built-ins say the same thing -- a union is aligned for the -;;; strictest of its members -- and say it in C99. -;;; -;;; Closures themselves still want C11 for the `_Static_assert' that -;;; checks the captures fit, so this program keeps clear of them. - -(include stdio.h) - -(struct point ((x int) (y int))) - -(fn area ((p (struct point))) int - (return (* (. p x) (. p y)))) - -(pub fn main () int - (var p (struct point) #((struct point) : 6 7)) - (printf "c99: %d\n" (area p)) - (return 0)) diff --git a/tests/sex-programs/compound-literals.sex b/tests/sex-programs/compound-literals.sex index 26a84ef..ec1e5df 100644 --- a/tests/sex-programs/compound-literals.sex +++ b/tests/sex-programs/compound-literals.sex @@ -34,7 +34,7 @@ ;; a compound literal is an lvalue, so its address can be taken -- ;; until the end of the enclosing block, and no longer (var pp (* struct point) (& #(struct point : 9 9))) - (printf "through a pointer %d\n" (-> pp x)) + (printf "through a pointer %d\n" (. pp x)) ;; an array literal decays the way an array does (var a (* int) #([int 3] : 10 20 30)) diff --git a/tests/sex-programs/encapsulation.sex b/tests/sex-programs/encapsulation.sex new file mode 100644 index 0000000..4a4308d --- /dev/null +++ b/tests/sex-programs/encapsulation.sex @@ -0,0 +1,45 @@ +(input) +(output "-(2 + 3)" + "-5") +(return 0) + +;;; 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) + +(sum expr + ((lit ((v float))) + (neg ((e (* const expr)))) + (add ((l (* const expr)) (r (* const expr)))))) + +(ops expr + (pub fn eval ((self (* const expr))) float + ;; v, e, l and r are copies of the fields, not references to them + (match (* self) + ((lit (v)) (return v)) + ((neg (e)) (return (- (.eval e)))) + ((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 main () int + (var two expr (expr/lit 2.0)) + (var three expr (expr/lit 3.0)) + (var both expr (expr/add (& two) (& three))) + (var e expr (expr/neg (& both))) + + (.show-line e) ; -(2 + 3) + (printf "%g\n" (.eval e)) ; -5 + (return 0)) diff --git a/tests/sex-programs/fixpoint.sex b/tests/sex-programs/fixpoint.sex index 9d62771..624a617 100644 --- a/tests/sex-programs/fixpoint.sex +++ b/tests/sex-programs/fixpoint.sex @@ -29,14 +29,14 @@ ;;; the self-application hidden inside (fn fix ((step (* (struct rec)))) (closure ((int)) int) (return (closure ((n int)) int (step) - (return ((-> step f) step n))))) + (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)))))) + (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)) @@ -45,8 +45,8 @@ (= (. 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)))))) + (return (+ ((. self f) self (- n 1)) + ((. self f) self (- n 2)))))) ;; one combinator, two different recursions (var fac (closure ((int)) int) (fix (& fac-knot))) diff --git a/tests/sex-programs/inference.sex b/tests/sex-programs/inference.sex index 4dfbfb6..b5d3f0a 100644 --- a/tests/sex-programs/inference.sex +++ b/tests/sex-programs/inference.sex @@ -43,8 +43,8 @@ (var m (struct point)) ;; No `_' here: `m' has no initializer to infer from. Inference fills ;; in a type, it does not invent one. - (= (. m x) (/ (+ (-> a x) (-> b x)) 2)) - (= (. m y) (/ (+ (-> a y) (-> b y)) 2)) + (= (. m x) (/ (+ (. a x) (. b x)) 2)) + (= (. m y) (/ (+ (. a y) (. b y)) 2)) (return m)) ;;; The closure's type is written once, in the signature; `_' reads it @@ -118,7 +118,7 @@ (var p (* _) (& origin)) ;; Member access reads the same type database the macros do. - (var x _ (-> p x)) + (var x _ (. p x)) (printf "%d\n" x) ;; A call into a function Sex has actually parsed: the return type is diff --git a/tests/sex-programs/list-macros.sex b/tests/sex-programs/list-macros.sex index 809ad68..5a1f8c9 100644 --- a/tests/sex-programs/list-macros.sex +++ b/tests/sex-programs/list-macros.sex @@ -9,25 +9,25 @@ (fn-name (cat 'make-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type) (var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type))) - (= (-> list next) NULL) + (= (. list next) NULL) (return list)))) (pub defmacro (add-value-list-T type is-public?) (let ((list-type (list 'struct (cat 'list- type))) (fn-name (cat 'add-value-list- type))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void - (while (!= (-> list next) NULL) - (= list (-> list next))) - (= (-> list next) (,(cat 'make-list- type))) - (= (-> list value) value)))) + (while (!= (. list next) NULL) + (= list (. list next))) + (= (. list next) (,(cat 'make-list- type))) + (= (. list value) value)))) (pub defmacro (length-list-T type is-public?) (let ((fn-name (cat 'length-list- type)) (list-type (list 'struct (cat 'list- type)))) `(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t (var n size-t 0) - (while (!= (-> list next) NULL) - (= list (-> list next)) + (while (!= (. list next) NULL) + (= list (. list next)) (++ n)) (return n)))) @@ -35,14 +35,14 @@ `(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type) ((list ,(list '* 'struct (cat 'list- type)))) bool - (return (== (-> list next) NULL)))) + (return (== (. list next) NULL)))) (pub defmacro (list-for-each list-type list-var elt-type elt-var what-do) (let ((list-var-2 (cat list-var '-2))) `(do (var ,list-var-2 (* ,list-type) ,list-var) - (var ,elt-var ,elt-type (-> ,list-var-2 value)) - (while (!= (-> ,list-var-2 next) NULL) + (var ,elt-var ,elt-type (. ,list-var-2 value)) + (while (!= (. ,list-var-2 next) NULL) ,what-do - (= ,list-var-2 (-> ,list-var-2 next)) - (= ,elt-var (-> ,list-var-2 value)))))) + (= ,list-var-2 (. ,list-var-2 next)) + (= ,elt-var (. ,list-var-2 value)))))) diff --git a/tests/sex-programs/ops.sex b/tests/sex-programs/ops.sex new file mode 100644 index 0000000..12bb812 --- /dev/null +++ b/tests/sex-programs/ops.sex @@ -0,0 +1,58 @@ +(compilation "-- -lm") +(input) +(output "5.0 5.0 10.0 14.0 14.0 6.0" + "struct receiver: 14" + "private: 8.0") +(return 0) + +;;; An ops block is mangled fns plus a registry entry, so a method is +;;; reachable both ways: spelled out as vec2/length, or as (.length v). +;;; The method sits in the head, not in a field position, so (. v x) is +;;; always the field x and the two cannot be confused -- here vec2 has +;;; both a field x and methods, and nothing arbitrates between them. +;;; +;;; Whether the receiver is addressed, dereferenced or passed along is +;;; decided by its type against the method's own, so (.length v) and +;;; (.length p) both work. `ops' takes a plain C struct too: it keys on +;;; the tag, not on the typedef a record happens to add. + +(include stdio.h) +(include math.h) + +(record vec2 ((x float) (y float))) + +(ops vec2 + (pub fn length ((self (* const vec2))) float + "Pointer self, so (.length v) has to take the address." + (return (sqrtf (+ (* (. self x) (. self x)) + (* (. self y) (. self y)))))) + + (fn scale ((self (* vec2)) (k float)) void + (*= (. self x) k) + (*= (. self y) k)) + + (fn sum-of ((self vec2)) float + ;; value self, so (.sum-of p) has to dereference + (return (+ (. self x) (. self y))))) + +(struct raw ((a int) (b int))) + +(ops raw + (fn total ((self (* const (struct raw)))) int + (return (+ (. self a) (. self b))))) + +(pub fn main () int + (var v vec2 #(vec2 : 3.0 4.0)) + (var p (* vec2) (& v)) + + (printf "%.1f %.1f " (.length v) (vec2/length (& v))) + (.scale v 2.0) + (printf "%.1f %.1f %.1f %.1f\n" + (.length p) (.sum-of v) (.sum-of p) (. v x)) + + (var r (struct raw) #(struct raw : 6 8)) + (printf "struct receiver: %d\n" (.total r)) + + (var u vec2 #(vec2 : 8.0 0.0)) + (printf "private: %.1f\n" (vec2/sum-of u)) + (return 0)) diff --git a/tests/sex-programs/records.sex b/tests/sex-programs/records.sex new file mode 100644 index 0000000..0477e97 --- /dev/null +++ b/tests/sex-programs/records.sex @@ -0,0 +1,46 @@ +(input) +(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8") +(return 0) + +;;; A record is a struct that also names itself, so the bare name +;;; stands wherever (struct name) had to: a var, a pointer, an array +;;; element, an arglist, a return type, a sizeof. struct keeps C's +;;; meaning, for a type that came from a header or is laid out to +;;; match one. + +(include stdio.h) + +(record point ((x int) (y int))) + +(record named + "Fields of more than one kind, and a docstring." + ((id int) (first-name (* const char)))) + +(struct raw ((a int) (b int))) + +(fn shift ((p (* point)) (dx int) (dy int)) void + (+= (. p x) dx) + (+= (. p y) dy)) + +(fn area ((p point)) int + (return (* (. p x) (. p y)))) + +(fn origin () point + (return #(point : 0 0))) + +(pub fn main () int + (var p point #(point : 1 2)) + (shift (& p) 2 2) + + (var n named #(named : .id 7 .first-name "zoe")) + (var r (struct raw) #(struct raw : 1 2)) + + (var ps [point 2]) + (= [ps 0] p) + (= [ps 1] (origin)) + + (printf "p %d %d / n %d %s / area %d / sizes %zu %zu\n" + (. p x) (. p y) (. n id) (. n first-name) + (area [ps 0]) + (sizeof point) (sizeof (struct raw))) + (return (+ (. [ps 1] x) (- (. r a) 1)))) diff --git a/tests/sex-programs/serialize.sex b/tests/sex-programs/serialize.sex index 344d305..bce7653 100644 --- a/tests/sex-programs/serialize.sex +++ b/tests/sex-programs/serialize.sex @@ -19,7 +19,7 @@ ((* const char) "%s") (else (error "print-struct: unsupported field type" name type)))) - (-> v ,name)))))) + (. v ,name)))))) (if (not printers) (error "print-struct: no such struct" type-name) `(fn ,(cat 'print- type-name) ((v (* const struct ,type-name))) void diff --git a/tests/sex-programs/specs.sex b/tests/sex-programs/specs.sex new file mode 100644 index 0000000..93f6680 --- /dev/null +++ b/tests/sex-programs/specs.sex @@ -0,0 +1,68 @@ +(input) +(output "$12.34" + "(3, 4)" + "max 1234" + "realizes ord: money 1, point 0") +(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)) + +(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)) + (return 0)) diff --git a/tests/sex-programs/sums.sex b/tests/sex-programs/sums.sex new file mode 100644 index 0000000..5eb49db --- /dev/null +++ b/tests/sex-programs/sums.sex @@ -0,0 +1,97 @@ +(input) +(output "3.14 12.00 0.00" + "held once: a 1" + "nested: -(2 + 3) = -5" + "tagged only: 1" + "rows: 18 5") +(return 0) + +;;; A sum is a tag enum, a payload struct per variant that carries +;;; fields, and the record holding both; a constructor is the value +;;; itself, written in place. match is a switch over the tag whose arms +;;; bind the payload as locals, and the compiler refuses one that leaves +;;; a variant out -- which is the thing the form exists for. + +(include stdio.h) + +(sum shape + ((circle ((r float))) + (rect ((w float) (h float))) + (empty ()))) + +(fn area ((s shape)) float + (var out float 0.0) + (match s + ((circle (r)) (= out (* 3.14159 r r))) + ((rect (w h)) (= out (* w h))) + ((empty ()) (= out 0.0))) + (return out)) + +;;; Recursive through pointers, because a value cannot hold itself +(sum expr + ((lit ((v float))) + (neg ((e (* const expr)))) + (add ((l (* const expr)) (r (* const expr)))))) + +(fn eval ((self (* const expr))) float + (match (* self) + ((lit (v)) (return v)) + ((neg (e)) (return (- (eval e)))) + ((add (l r)) (return (+ (eval l) (eval r)))))) + +(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 ")")))) + +;;; No fields anywhere: the record is the tag alone, with no union +(sum light ((red ()) (green ()))) + +(fn mk-shape () shape (return (shape/circle 1.0))) + +(sum held ((a ((x int) (y int))) (b ()))) +(fn mk-held () held (return (held/a 1 2))) + +;;; An array field is handed elements, never an array: C copies neither +;;; into a parameter nor into another array, so both the constructor +;;; and the binder spell it out +(define N 4) +(sum row ((cells ((xs [int N]))) (none ()))) + +(pub fn main () int + (printf "%.2f %.2f %.2f\n" + (area (mk-shape)) + (area (shape/rect 3.0 4.0)) + (area (shape/empty))) + + ;; the scrutinee is a call, so it is read into a local once + (match (mk-held) + ((a (x _)) (printf "held once: a %d\n" x)) ; `_' drops y + (else (printf "held once: other\n"))) + + (var two expr (expr/lit 2.0)) + (var three expr (expr/lit 3.0)) + (var both expr (expr/add (& two) (& three))) + (var e expr (expr/neg (& both))) + (printf "nested: ") + (show (& e)) + (printf " = %g\n" (eval (& e))) + + (var l light (light/green)) + (match l + ((red ()) (printf "tagged only: 0\n")) + ((green ()) (printf "tagged only: 1\n"))) + + (var a [int N] #(5 6 7 8)) + (var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4)))) + (= [a 0] 50) ; the row holds a copy + (var sum int 0) + (for (var i int 0) (< i 2) (++ i) + (match [rows i] + ((cells (xs)) + (= [xs 0] 100) ; and so does the binder + (+= sum (+ [xs 1] [xs 2]))) + ((none ()) (+= sum 0)))) + (printf "rows: %d %d\n" sum (. [rows 0] u cells [xs 0])) + (return 0)) diff --git a/tests/sex-programs/threading.sex b/tests/sex-programs/threading.sex new file mode 100644 index 0000000..7cd2cb7 --- /dev/null +++ b/tests/sex-programs/threading.sex @@ -0,0 +1,50 @@ +(input) +(output "arithmetic: 26" + "a bare step needs no parens: 20" + "through a path: 1 4" + "mixed with a method: 25" + "one step is just the value: 7") +(return 0) + +;;; A step may be a call, a bare name, a member path or a method, and +;;; the value goes in as its first argument. + +(include stdio.h) +(import threading-macros) + +(struct point ((x int) (y int))) +(struct line ((a (* struct point)) (b (struct point)))) + +(fn double-it ((n int)) int + (return (* n 2))) + +(fn add ((n int) (m int)) int + (return (+ n m))) + +(ops point + (pub fn length-sq ((self (* const struct point))) int + (return (+ (* (. self x) (. self x)) + (* (. self y) (. self y)))))) + +(pub fn main () int + ;; (add (double-it 5) 3) doubled: inside out, written outside in + (printf "arithmetic: %d\n" + (-> 5 + double-it + (add 3) + double-it)) + (printf "a bare step needs no parens: %d\n" (-> 5 double-it double-it)) + + (var p (struct point) #(1 2)) + (var l (struct line) #(struct line : .a (& p) .b #(3 4))) + (var lp (* struct line) (& l)) + ;; a member path is an ordinary step, and reads through both pointers + (printf "through a path: %d %d\n" + (-> lp (. a x)) + (. lp b y)) + + (var q (struct point) #(3 4)) + (printf "mixed with a method: %d\n" (-> q .length-sq)) + + (printf "one step is just the value: %d\n" (-> 7)) + (return 0)) diff --git a/tests/sex-programs/wildcards.sex b/tests/sex-programs/wildcards.sex index 20b7752..1bf0764 100644 --- a/tests/sex-programs/wildcards.sex +++ b/tests/sex-programs/wildcards.sex @@ -42,7 +42,7 @@ (printf "members: %d %g\n" px py) (var pp _ (& p)) - (printf "pointers: %d %g\n" (-> pp x) (-> pp y)) + (printf "pointers: %d %g\n" (. pp x) (. pp y)) (var table (¤ int 3)) (= (¤ table 0) 10) @@ -77,7 +77,7 @@ ;; a wildcard inside a written type: only it is solved (var pp2 (* _) (& p)) - (printf "partial: %d %g\n" (-> pp2 x) (-> pp2 y)) + (printf "partial: %d %g\n" (. pp2 x) (. pp2 y)) ;; C's usual arithmetic conversions, far enough to answer `_' (var d double 1.5) diff --git a/tests/types.module.scm b/tests/types.module.scm index cf06139..7b0f366 100644 --- a/tests/types.module.scm +++ b/tests/types.module.scm @@ -9,6 +9,26 @@ type-pattern-matches? map-fields + add-sum! + get-sum + add-constructor! + get-constructor + variant-fields + reset-declarations! + + add-spec! + get-spec + spec-parameter + spec-methods + add-realization! + realizes? + normalize-fields + + add-method! + get-method + qualify-op + ops-key + add-name-type! get-name-type type-of diff --git a/types.module.scm b/types.module.scm index ed00b5c..e2a67c5 100644 --- a/types.module.scm +++ b/types.module.scm @@ -9,6 +9,26 @@ type-pattern-matches? map-fields + add-sum! + get-sum + add-constructor! + get-constructor + variant-fields + reset-declarations! + + add-spec! + get-spec + spec-parameter + spec-methods + add-realization! + realizes? + normalize-fields + + add-method! + get-method + qualify-op + ops-key + add-name-type! get-name-type type-of diff --git a/types.scm b/types.scm index f2cfd5e..78a183c 100644 --- a/types.scm +++ b/types.scm @@ -171,6 +171,123 @@ (and tag (or (get-tag-info tag) (get-type-info tag)))) info)))) +;;; The name methods, realizations and sums are filed under. A typedef +;;; is followed to the aggregate it names, and one that ends in anything +;;; else stops at the last typedef, so a scalar does not share them: +;;; +;;; (record v ...) (typedef alias v) alias -> v +;;; (typedef meters float) meters -> meters +;;; (typedef km meters) km -> meters +(define (type-key name) + (let follow ((name name) (seen (list))) + (let ((target (and (not (memq name seen)) (typedef-target name)))) + (cond ((not target) name) + ((symbol? target) + (if (typedef-target target) (follow target (cons name seen)) name)) + ((target-tag target)) + (else name))))) + +(define (typedef-target name) + (let ((info (and (symbol? name) (get-type-info name)))) + (and info (eq? (car info) 'typedef) (caddr info)))) + +;;; A sum's variants, in declaration order: +;;; +;;; (sum shape ((circle ((r float))) (empty ()))) +;;; -> shape -> ((circle (r float)) (empty)) +;;; +;;; Fields are normalized, so a caller counts them and reads their +;;; types without re-parsing the declaration. +(define +sum-db+ (make-hash-table)) + +(define (add-sum! name variants) + (hash-table-set! +sum-db+ (type-key name) variants)) + +(define (get-sum name) + (hash-table-ref/default +sum-db+ (type-key name) #f)) + +;;; shape/circle -> (shape . circle), for each variant of each sum +(define +constructor-db+ (make-hash-table)) + +(define (add-constructor! constructor sum variant) + (hash-table-set! +constructor-db+ constructor (cons sum variant))) + +(define (get-constructor name) + (hash-table-ref/default +constructor-db+ name #f)) + +(define (variant-fields variants name) + (let ((entry (assq name variants))) + (and entry (cdr entry)))) + +;;; Methods of an `ops' block: (type . method) -> the qualified name +;;; the call is rewritten to. +;;; +;;; (ops vec2 (fn length ((self (* const vec2))) float ...)) +;;; -> (vec2 . length) -> vec2/length +;;; +;;; The signature is not kept here; `vec2/length' is an ordinary +;;; function by the time anything asks, so +name-db+ already has it. +(define +ops-db+ (make-hash-table)) + +(define (add-method! type method qualified) + (hash-table-set! +ops-db+ (cons (type-key type) method) qualified)) + +(define (get-method type method) + (hash-table-ref/default +ops-db+ (cons (type-key type) method) #f)) + +;;; vec2 + length -> vec2/length, which `unkebabify' spells vec2ːlength +(define (qualify-op type name) + (string->symbol + (string-append (symbol->string type) "/" (symbol->string name)))) + +;;; The name an `ops' block was written against: `(struct point)' and a +;;; `const' wrapper both name `point', and anything else names nothing. +(define (ops-key type) + (cond ((symbol? type) (type-key type)) + ((not (and (pair? type) (symbol? (car type)))) #f) + ((memq (car type) '(struct union enum)) + (and (pair? (cdr type)) (symbol? (cadr type)) (cadr type))) + ((memq (car type) '(const volatile)) (ops-key (cadr type))) + (else #f))) + +;;; 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! +spec-db+ (make-hash-table)) + (set! +realize-db+ (make-hash-table))) + ;;; Type matcher macro ;;; (type-match type ;;; (int ...) diff --git a/utils.module.scm b/utils.module.scm index 79ec527..5b3463c 100644 --- a/utils.module.scm +++ b/utils.module.scm @@ -12,6 +12,7 @@ form-source form-file form-line + form-end-line copy-form-source! stamp-form-source! form-location diff --git a/utils.scm b/utils.scm index ee0a3a1..326b554 100644 --- a/utils.scm +++ b/utils.scm @@ -93,9 +93,12 @@ ;;; read-with-source-info / get-line-number, which only works when forms ;;; are produced by the built-in `read'. ;;; -;;; A location is (file . line). The file matters because imported +;;; A location is (file line end-line): where the form starts and the +;;; line its closing delimiter is on. The file matters because imported ;;; modules paste their public forms into the current unit: those forms -;;; originate in another file and must be reported as such +;;; originate in another file and must be reported as such. The end line +;;; tells the C writer whether two toplevel forms were written with a +;;; blank line between them (define +form-sources+ (make-hash-table eq?)) ;;; The file `parse-all' is currently reading. Bound by the reader @@ -114,8 +117,8 @@ (define (form-type form) (hash-table-ref/default +form-types+ form #f)) -(define (set-form-source! form file line) - (hash-table-set! +form-sources+ form (cons file line))) +(define (set-form-source! form file line #!optional (end-line line)) + (hash-table-set! +form-sources+ form (list file line end-line))) (define (form-source form) (hash-table-ref/default +form-sources+ form #f)) @@ -126,7 +129,11 @@ (define (form-line form) (let ((src (form-source form))) - (and src (cdr src)))) + (and src (cadr src)))) + +(define (form-end-line form) + (let ((src (form-source form))) + (and src (caddr src)))) (define (copy-form-source! from to) "Give TO the location of FROM, if FROM has one. Returns TO, so it can @@ -144,7 +151,7 @@ wrap a form-building expression." "\"file:line: \" for FORM, or \"\" when it has none" (let ((src (form-source form))) (if src - (string-append (car src) ":" (number->string (cdr src)) ": ") + (string-append (car src) ":" (number->string (cadr src)) ": ") ""))) (define (sex-error form message . args)