36 Commits

Author SHA1 Message Date
f9809c19c4 tell what a member path walked from the fields it has left 2026-10-14 20:09:49 +03:00
31b7046048 share reading a test source and catching its error
encapsulation.scm had copies of both from codegen.scm.
2026-10-14 20:09:17 +03:00
2cfce45935 parenthesise a conditional without a helper to do it for 2026-10-14 20:09:17 +03:00
bb252dc244 tell a grouped for header by its shape, not by a var in it
(for ((= s 0) (< s n) (++ s)) ...) passed the check and reached cc as
a call of (= s 0).
2026-10-14 20:08:39 +03:00
eeb5357fd4 read each module once per unit
A pub import chain had its interface check read every module below
again, so the deepest was parsed once per level above it.
2026-10-14 20:08:16 +03:00
1aed7cee4c compile the name spellings once, and skip a name that has none
Read from a table, the patterns were compiled again for every symbol
written; that tripled what unkebabify cost.
2026-10-14 20:07:20 +03:00
4ada1059a2 name the test for output going to stdout
-o - was taught to two copies of it.
2026-10-14 20:07:03 +03:00
9a6e2dcd83 keep the parameter-type rule in types, where both readers find it
sex-modules spelled out its own copy of named-arg-type, and its own
strip-pub; a parameter shape taught to one would not reach the other.
2026-10-14 20:06:51 +03:00
00e75dee48 declare an ops method ahead through the one prototype accessor
fn-prototype repeated sex-fn-prototype, and names? repeated mentions?;
each pair kept the better half.
2026-10-14 20:06:51 +03:00
2904be4499 drop walk-literal, which the rebase left without callers
walk-initializer took its place, but walked the values as statements;
a match among them is refused again wherever the literal stands.
2026-10-14 20:05:29 +03:00
ae9cdbbf31 check the constants a module's interface hands its importers
An array bound in a pub record, or a name in a pub define's body, is
the importer's to resolve too, and a private define, or one from an
import without pub, failed there as an undeclared identifier. Found in
vs-map-viewer once its units stopped importing everything. A constant
has no declaration short of itself, so it is an error at the pub form.
2026-10-14 19:22:34 +03:00
66d088f6fc write a double in the digits that read back as it
CHICKEN prints 15 significant digits unless told otherwise, too few to
name every double: 0.9871465422297019 reached the C as
0.987146542229702, a different constant. Found in vs-map-viewer, where
380 literals in a port that has to match .NET bit for bit changed this
way. The shortest spelling that reads back is written, up to 17 digits.
2026-10-14 19:22:34 +03:00
3737f90641 hand sexc every digit of a test program's doubles
sextest prints the program it read back to sexc, and printed doubles
in CHICKEN's default 15 digits: 0.16666666666666666 arrived as
0.166666666666667, another number.
2026-10-14 19:22:34 +03:00
58f145bd95 parenthesise what a subscript subscripts
The array was written at whatever level surrounded it, so [(* q) i]
came out *q[i] -- *(q[i]) to C, compiling with q an int ** and reading
the wrong int. The index now starts afresh too: inside a cast it had
taken the cast's level and gained parens, and so had a chain in the
else arm of ?:, which groups to the right and needs none.
2026-10-14 19:22:34 +03:00
e6b6ca799d print the public interface in declaration order
read-public-interface has returned the forms in order since 2512d52,
and --public-interface still reversed them as it had to before.
2026-10-14 19:22:34 +03:00
a6689b8c81 write a make rule for the modules a unit reads
An import pastes another file's forms into the output, so a Makefile
had to make every object depend on every .sex. --depfile names the
modules read, including those read only for an import's interface,
with an empty rule for each, as cc -MD -MP does.

Fixes #40.
2026-10-14 19:22:34 +03:00
b717aa808d check what a module's importers can see of its types
An importer is given the pub forms and nothing else, so a pub form
naming a private type, or one from an import without pub, compiled in
its module and failed in every importer with `unknown type name'.

The pub forms are checked as the module itself is compiled. A record,
struct, union or sum behind a pointer needs only declaring, so its
bodyless declaration goes out ahead of them -- the opaque handle that
(pub record T) already gave by hand. Held by value it needs its body,
and a typedef or an enum has no declaration short of its definition:
those are errors at the pub form, saying what would do instead. A name
Sex has no declaration for is left to C.

An importer may now be handed a declaration after the definition it
declares, so a bodyless aggregate no longer replaces known fields.

Fixes #57, #58.
2026-10-14 19:22:34 +03:00
b49bb8f716 let a method call one written below it
Each method was registered just before its own body was walked, so an
earlier one could not find it. All are registered first now, and one
called above its definition is declared ahead of the bodies, which C
needs as well.

Fixes #44.
2026-10-14 19:22:34 +03:00
a048925c7a resolve a relative SEX_MODULE_PATH entry from the working directory
make-absolute-pathname with no directory of its own put `src' under
the root, so SEX_MODULE_PATH=src searched /src/.

Fixes #48.
2026-10-14 19:22:34 +03:00
a14484d1dc take -o - as stdout
getopt-long reads a lone `-' as an option, so -o - died there asking
for a value, and --output=- got through only to create a file named
`-'.

Fixes #43.
2026-10-14 19:22:34 +03:00
42fe477e35 name what a member path could not type
Past a typed base, it is a field of a struct only C knows that has no
type, and the warning named the base anyway: `font' for what was
(. font handle), with font declared on the line before.

Fixes #41.
2026-10-14 19:22:34 +03:00
062cb18c60 walk what an initializer holds
The body walk passed a #(...) by as an atom, so nothing inside one was
typed, dispatched or lifted: (. self p) read as self.p with self a
pointer, where the same path outside the literal was right.

Fixes #45.
2026-10-14 19:22:32 +03:00
4e0938ab1f reject a for whose header is grouped
C's parens carried over, ((var i int 0) (< i 4) (++ i)), left the
writer short of slots, and it died in caddr with no location; with a
long enough body it would have compiled the body into the header.

Fixes #42.
2026-10-14 19:21:16 +03:00
2bad5db114 anchor an if's arms only where the if is a statement
Every if had its arms anchored, including one inside an argument that
the writer renders as ?:, so a #line landed between its parts and the
C did not compile. -C output, with no directives, hid it.

Fixes #54.
2026-10-14 19:21:16 +03:00
3e01fe41e8 make a declaring case body a block
A case body shared the switch's scope, so two cases could not each
declare `bits', and a label could not be followed by a declaration
before C23; inference shared the scope too, and typed a later case's
read of an outer name as the earlier case's local.

Fixes #51.
2026-10-14 19:21:13 +03:00
52228e6fc6 write arrays with brackets in tests
The tests spelled out (¤ ...), what [...] reads into, which nobody
writes. The reader's own tests keep it: there it is the point.
2026-10-14 19:12:47 +03:00
08853d2c77 read hex and binary literals
0x80 was not a number to string->number, so it became a symbol the
printer escaped as |0x80|, and #x was rejected outright. Both spellings
now read as the integer, which the C writes in decimal.

Fixes #47.
2026-10-14 19:12:47 +03:00
6fbeaedbe6 read -NAME as the negation of NAME
The reader took -INFINITY as one symbol, and the leading dash was then
mangled like any other: _INFINITY. -1 was always a number, so a name
gets the same reading.

Fixes #63.
2026-10-14 19:12:47 +03:00
9d4454afe3 let sizeof take a type that looks like an expression
(* char) is a pointer type and (* p) a dereference, and only the names
in scope tell them apart, so semen decides and marks a type for the
writer. Before, both were walked as expressions: sizeof(*char).

Fixes #52.
2026-10-14 19:12:47 +03:00
5a887c0654 spell ? and ! in names as letters C takes
A Lisp predicate came out as ident_start?, which no C compiler reads.
ʔ and ꜝ are letters that look the part; ǃ looks closer, but clang flags
it as a homoglyph of `!' at every use.

Fixes #49.
2026-10-14 19:12:47 +03:00
b5de28342b walk a define's body, and parenthesise it
The body was pasted as read, so `cast' stayed a call and names kept
their dashes; and fmt-c parenthesised only a function-like body, so
an object-like one regrouped with the operator it was pasted under.

Fixes #55.
2026-10-14 19:12:47 +03:00
dff4a5af53 convert enumerators written with a value
(wire-varint 0) is a pair, and both the writer and map-fields only
expected a name: the writer passed it out unconverted, and a macro
mapping over the enum was handed the pair.

Fixes #46.
2026-10-14 19:12:47 +03:00
f24adfa2db write a typedef's target as a type
It fell through to the expression walk, which read (* const char) as a
dereference and an array as a subscript, and died on a fn type.

Fixes #53.
2026-10-14 19:12:47 +03:00
82629867c1 spell an array bound as an expression
It went to fmt-c unwalked, so a bound named CHUNK-AREA kept its dash
while the same name in an expression became CHUNK_AREA.

Fixes #50.
2026-10-14 19:12:47 +03:00
b0dd2d9f94 tell an array's bound by the shape of its type
Whether a trailing name was the bound hinged on the word before it
being a typedef Sex had seen, which a header's pthread_t never is, and
a grouped (* T) never is either: [pthread-t N] became a two-word type.

Fixes #56, #60.
2026-10-14 19:12:47 +03:00
169933ff2e parenthesise casts and conditionals by precedence
Neither took part in it: a cast parenthesised its operand only from a
list of binary heads that missed `|', and never itself, so `->' took
it apart; `?:' was written bare under any operator, swallowing it into
the test. Three of the four still compiled, to wrong values.

Fixes #59, #61, #62.
2026-10-14 19:12:47 +03:00
90 changed files with 3375 additions and 3830 deletions

9
.gitignore vendored
View File

@@ -5,11 +5,10 @@
*.o *.o
*.import.scm *.import.scm
*.link *.link
/modules.mk sexc
/modules.stamp sex-tests
/sexc sextest
/sex-tests tools/sextest/sextest
/sextest
# Scrapped design docs, kept for reference # Scrapped design docs, kept for reference
/attic /attic

193
Makefile
View File

@@ -1,6 +1,6 @@
CHICKEN_C ?= csc CHICKEN_C ?= csc
# beside csc, whatever it is called: chicken-csc comes with chicken-csi CHICKEN_INSTALL ?= chicken-install
CSI ?= $(patsubst %csc,%csi,$(CHICKEN_C)) CHICKEN_STATUS ?= chicken-status
CSC_FLAGS += -K prefix -static CSC_FLAGS += -K prefix -static
# What and why: # What and why:
# -emit-all-import-libraries: Emit import-libraries for all defined modules. # -emit-all-import-libraries: Emit import-libraries for all defined modules.
@@ -33,68 +33,113 @@ SEX_LIB = $(wildcard lib/*.sex)
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
# Order matters, since module check correctness on compilation
MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc
OBJ = $(MODULES:%=%.o)
DEPSFILE = dependencies.txt
DEPSLOCK = eggs.lock
EGGS_DIR := $(abspath .eggs)
# Compiler's own repository (types.db, chicken.*), ignoring ambient venv vars.
SYSTEM_CHICKEN_REPO := $(shell env \
-u CHICKEN_INSTALL_REPOSITORY -u CHICKEN_REPOSITORY_PATH \
-u CHICKEN_EGG_CACHE -u CHICKEN_INSTALL_PREFIX \
$(CHICKEN_INSTALL) -repository 2>/dev/null)
CHICKEN_ABI := $(notdir $(SYSTEM_CHICKEN_REPO))
EGGS_STAMP := $(EGGS_DIR)/.installed-$(CHICKEN_ABI)
# Try project-local chicken repository first. In case it doesn't exist (packaging for distros),
# system-wide repository will be used.
unexport CHICKEN_INSTALL_REPOSITORY
unexport CHICKEN_EGG_CACHE
unexport CHICKEN_INSTALL_PREFIX
export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO)
all: sexc all: sexc
include eggs.mk sexc: $(OBJ) main.scm
$(CHICKEN_C) $(CSC_FLAGS) main.scm -o sexc-tmp -link sexc
# Each program, and the source it is built from # otherwise csc hangs, probably because it tries to compile to sexc.o first
PROGRAMS = sexc=main.scm sextest=tools/sextest/sextest.scm sex-tests=tests/run.scm mv sexc-tmp sexc
PROGRAM_NAMES = $(foreach p,$(PROGRAMS),$(firstword $(subst =, ,$(p))))
PROGRAM_OBJ = $(foreach p,$(PROGRAMS),$(patsubst %.scm,%.o,$(lastword $(subst =, ,$(p)))))
# MODULES, and a line for each module and program naming what it
# imports, read off the import forms. Not for clean, which has to work
# when they cannot be read
ifneq ($(MAKECMDGOALS),clean)
include modules.mk
endif
# The scan is redone whenever a source may have changed what it
# imports, or a NAME.scm may have come to be the module an import
# names; but modules.mk is rewritten only when that changed, since make
# starts over each time it is, and a source dated in the future would
# have it start over for good. A stamp without modules.mk stands for
# nothing, and is redone whatever its date
modules.mk: modules.stamp ;
modules.stamp: $(SOURCES) $(filter-out %.import.scm,$(wildcard *.scm)) \
tools/module-deps.scm dependencies.txt Makefile \
$(if $(wildcard modules.mk),,FORCE)
$(CSI) -s tools/module-deps.scm $(PROGRAMS) > modules.mk.tmp \
|| { rm -f modules.mk.tmp; exit 1; }
if cmp -s modules.mk.tmp modules.mk; then rm modules.mk.tmp; \
else mv modules.mk.tmp modules.mk; fi
touch $@
#------------------------------------------------------------------ #------------------------------------------------------------------
# A module is one file that declares its own exports, made a module by utils.o: utils.module.scm utils.scm
# -module, except the vendored sex-fmt-c, a (module ...) form of its own $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils
%.o: %.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< $(if $(filter sex-fmt-c,$*),,-module $*) -o $@ -unit $*
# A program's object is named after its source: csc names its own after types.o: types.module.scm types.scm
# -o, and sexc.o is the module's $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) types.module.scm -o types.o -unit types
$(PROGRAM_OBJ): %.o: %.scm
$(CHICKEN_C) $(CSC_FLAGS) -c $< -o $@
$(PROGRAM_NAMES): infer.o: infer.module.scm infer.scm types.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $< -o $@ $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) infer.module.scm -o infer.o -unit infer -link types,utils
# A program directly in tests/sex-programs is a test; lib/ holds what sex-macros.o: sex-macros.module.scm sex-macros.scm
# they import $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-macros.module.scm -o sex-macros.o -unit sex-macros
SEX_TEST_PROGRAMS = $(wildcard tests/sex-programs/*.sex)
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 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
sex-fmt-c.o: sex-fmt-c.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-fmt-c.scm -o sex-fmt-c.o -unit sex-fmt-c
fmt-c-writer.o: fmt-c-writer.module.scm fmt-c-writer.scm sex-fmt-c.o types.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) fmt-c-writer.module.scm -o fmt-c-writer.o -unit fmt-c-writer -link sex-fmt-c,types,utils
sexc.o: sexc.module.scm infer.o types.o sexc.scm fmt-c-writer.o sex-macros.o sex-modules.o reader.o semen.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sexc.module.scm -o sexc.o -unit sexc -link fmt-c-writer,sex-macros,sex-modules,reader,semen,infer,types,utils
# Unit testing
sex-tests:
$(MAKE) -C ./tests sex-tests
cp ./tests/sex-tests ./
sextest:
$(MAKE) -C ./tools/sextest sextest
cp ./tools/sextest/sextest .
SEX_TEST_PROGRAMS = c11 \
closure-signatures \
closures \
comments \
compound-literals \
feature-flags \
features \
fixpoint \
hello-world \
inference \
lambdas \
lists \
operators \
ops \
precedence \
records \
serialize \
specs \
sums \
threading \
type-shapes \
unicode \
unnamed-params \
wildcards \
worked-example
# Multi-module linking is checked end to end; see tests/modules/Makefile.
check-modules: sexc
@$(MAKE) --no-print-directory -C ./tests/modules check SEXC=../../sexc
# The failure paths are checked end to end; see tests/exit-code/Makefile.
check-exit-code: sexc
@$(MAKE) --no-print-directory -C ./tests/exit-code check SEXC=../../sexc
check run-tests: sexc sex-tests sextest check run-tests: sexc sex-tests sextest
./sex-tests ./sex-tests && ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS:%=./tests/sex-programs/%.sex) && $(MAKE) check-modules && $(MAKE) check-exit-code
./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS)
@$(MAKE) --no-print-directory check-modules
@$(MAKE) --no-print-directory check-exit-code
@$(MAKE) --no-print-directory check-command-line
# The end-to-end checks, each on its own: run with the eggs on the path
check-modules check-exit-code check-command-line: check-%: sexc
cd tests/$* && SEXC='$(CURDIR)/sexc' $(CSI) -s check.scm
install: all installdirs install: all installdirs
$(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc $(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc
@@ -111,10 +156,38 @@ uninstall:
rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%) rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%)
-rmdir $(DESTDIR)$(sexlibdir) -rmdir $(DESTDIR)$(sexlibdir)
clean: $(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache
rm -f *.o $(PROGRAM_OBJ) modules.mk modules.stamp $(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR)
rm -f *.import.scm $(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_PREFIX := $(EGGS_DIR)
rm -f *.link $(PROGRAM_OBJ:.o=.link) $(EGGS_STAMP) deps-update: export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO)
rm -f $(PROGRAM_NAMES)
.PHONY: all check run-tests check-modules check-exit-code check-command-line install install-strip installdirs uninstall clean FORCE $(EGGS_STAMP): $(DEPSLOCK)
mkdir -p $(CHICKEN_EGG_CACHE)
$(CHICKEN_INSTALL) -force -from-list $(DEPSLOCK)
touch $@
deps: $(EGGS_STAMP)
deps-update: $(DEPSFILE) deps-clean
mkdir -p $(CHICKEN_EGG_CACHE)
$(CHICKEN_INSTALL) -force $$(cat $(DEPSFILE))
# Local repo only: a system path here would leak distro eggs into the lock.
CHICKEN_REPOSITORY_PATH=$(EGGS_DIR) $(CHICKEN_STATUS) -list | sort > $(DEPSLOCK).tmp
mv $(DEPSLOCK).tmp $(DEPSLOCK)
touch $(EGGS_STAMP)
clean:
rm -f $(OBJ) main.o
rm -f *.import.scm
rm -f *.link
rm -f sexc sex-tests sextest
$(MAKE) -C ./tests clean
$(MAKE) -C ./tests/modules clean
$(MAKE) -C ./tools/sextest clean
deps-clean:
rm -rf $(EGGS_DIR)
.PHONY: all check run-tests check-modules check-exit-code \
install install-strip installdirs uninstall \
deps deps-update deps-clean clean sex-tests sextest

View File

@@ -90,8 +90,7 @@ sexc ./examples/hello-world.sex -o hello
That's it. Now you should have executable named ~hello~ in your That's it. Now you should have executable named ~hello~ in your
directory. Sex uses C under the hood, the default C compiler is ~cc~, directory. Sex uses C under the hood, the default C compiler is ~cc~,
but you can pass any using ~--c-compiler~ option, or by setting but you can pass any using ~--c-compiler~ option, or by setting
~SEX_CC~ environment variable. Either may carry the compiler's own ~SEX_CC~ environment variable.
options, as ~make~'s ~CC~ does: ~SEX_CC="ccache cc"~.
Everything after ~--~ is handed to the C compiler exactly as written: Everything after ~--~ is handed to the C compiler exactly as written:
@@ -177,9 +176,24 @@ same name wins over one of ours.
~sexc~ looks for them beside itself, so a work tree needs nothing set ~sexc~ looks for them beside itself, so a work tree needs nothing set
up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~. up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~.
Each module is documented in a file of its own beside it: There is one so far.
- [[file:lib/threading-macros.org][threading-macros]] --- ~->~, threading a value through a chain of calls *** 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)~.
** Read-time feature expressions ** Read-time feature expressions
Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that
@@ -317,15 +331,8 @@ best option.
*** sex-mode.el *** sex-mode.el
To harness the power of sex-mode, add the following lines to your To harness the power of sex-mode, add the following lines to your
~$HOME/.config/emacs/init.el~: ~$HOME/.config/emacs/init.el~:
#+begin_src emacs-lisp #+begin_src emacs-lisp
(use-package sex-mode (use-package sex-mode
:ensure nil :load-path "/path/to/sex"
:quelpa :mode ("\\.sex\\'"))
(sex-mode :fetcher git
:url "https://git.kotobank.ch/alex-eg/sex.git"
:files ("sex-mode.el")
:upgrade t))
#+end_src #+end_src
~.sex~ files then open in ~sex-mode~.

52
eggs.mk
View File

@@ -1,52 +0,0 @@
# The eggs sexc needs, in a project-local repository when there is one.
#
# make deps install the versions pinned in eggs.lock into .eggs
# make deps-update install the newest of dependencies.txt, and pin them
#
# Without .eggs (packaging for distros) the system repository is used.
CHICKEN_INSTALL ?= chicken-install
CHICKEN_STATUS ?= chicken-status
DEPSFILE = dependencies.txt
DEPSLOCK = eggs.lock
EGGS_DIR := $(abspath .eggs)
# Compiler's own repository (types.db, chicken.*), ignoring ambient venv vars.
SYSTEM_CHICKEN_REPO := $(shell env \
-u CHICKEN_INSTALL_REPOSITORY -u CHICKEN_REPOSITORY_PATH \
-u CHICKEN_EGG_CACHE -u CHICKEN_INSTALL_PREFIX \
$(CHICKEN_INSTALL) -repository 2>/dev/null)
CHICKEN_ABI := $(notdir $(SYSTEM_CHICKEN_REPO))
EGGS_STAMP := $(EGGS_DIR)/.installed-$(CHICKEN_ABI)
# The path replaces CHICKEN's own rather than extending it, so the
# system repository has to be on it too
unexport CHICKEN_INSTALL_REPOSITORY
unexport CHICKEN_EGG_CACHE
unexport CHICKEN_INSTALL_PREFIX
export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO)
$(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache
$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR)
$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_PREFIX := $(EGGS_DIR)
$(EGGS_STAMP): $(DEPSLOCK)
mkdir -p $(CHICKEN_EGG_CACHE)
$(CHICKEN_INSTALL) -force -from-list $(DEPSLOCK)
touch $@
deps: $(EGGS_STAMP)
deps-update: $(DEPSFILE) deps-clean
mkdir -p $(CHICKEN_EGG_CACHE)
$(CHICKEN_INSTALL) -force $$(cat $(DEPSFILE))
# Local repo only: a system path here would leak distro eggs into the lock.
CHICKEN_REPOSITORY_PATH=$(EGGS_DIR) $(CHICKEN_STATUS) -list | sort > $(DEPSLOCK).tmp
mv $(DEPSLOCK).tmp $(DEPSLOCK)
touch $(EGGS_STAMP)
deps-clean:
rm -rf $(EGGS_DIR)
.PHONY: deps deps-update deps-clean

View File

@@ -3,6 +3,12 @@
(fn sum ((a int) (b int)) int (fn sum ((a int) (b int)) int
(return (+ a b))) (return (+ a b)))
;;; A lambda captures nothing and is a bare function pointer; a closure
;;; captures and is a value carrying its own environment
(fn make-adder ((a int)) (closure ((int)) int)
(return (closure ((b int)) int (a)
(return (+ a b)))))
(pub fn main () int (pub fn main () int
(var a int 10) (var a int 10)
(var b int 20) (var b int 20)
@@ -35,4 +41,8 @@
(return (+ 60 a)))) (return (+ 60 a))))
(return (+ 600 (l-2 a))))) (return (+ 600 (l-2 a)))))
(printf "Calling nested lambdas: %d\n" (l-1 6)) (printf "Calling nested lambdas: %d\n" (l-1 6))
(var add-10 (closure ((int)) int) (make-adder 10))
(var add-20 (closure ((int)) int) (make-adder 20))
(printf "Calling closures: %d %d\n" (add-10 24) (add-20 24))
(return 0)) (return 0))

3
fmt-c-writer.module.scm Normal file
View File

@@ -0,0 +1,3 @@
(module fmt-c-writer (emit-c
sex-line-directives)
"fmt-c-writer.scm")

View File

@@ -4,24 +4,18 @@
scheme scheme
(scheme base) ; make-parameter (scheme base) ; make-parameter
(chicken base) (chicken base)
(chicken module)
(chicken string) (chicken string)
(chicken syntax) (chicken syntax)
brev-separate ; fn brev-separate ; fn, flatten
fmt fmt
sex-fmt-c sex-fmt-c
matchable matchable
(chicken irregex) ; unkebabify (chicken irregex) ; unkebabify
reader ; number-literal?
srfi-1 ; lists srfi-1 ; lists
srfi-13 ; strings srfi-13 ; strings
types ; array-bound?, named-arg? types ; array-bound?, named-arg?
utils) utils)
(export
emit-c
sex-line-directives)
;;; egg `tree' not ported to CHICKEN 6 yet ;;; egg `tree' not ported to CHICKEN 6 yet
(define (tree-map f tree) (define (tree-map f tree)
(cond ((null? tree) (list)) (cond ((null? tree) (list))
@@ -41,9 +35,8 @@
(define (line-directive src) (define (line-directive src)
;; `%line' is fmt-c's #line directive. cpp-line concatenates its ;; `%line' is fmt-c's #line directive. cpp-line concatenates its
;; second argument verbatim, so the file name arrives as the string ;; second argument verbatim, so the file name arrives already quoted.
;; literal C reads it as: a quote, a backslash or a ?? in it escaped. `(%line ,(cadr src) ,(fmt #f #\" (car src) #\")))
`(%line ,(cadr src) ,(fmt #f (c-in-expr (c-literal (car src))))))
(define (walk-body stmts) (define (walk-body stmts)
"Walk a statement list, re-anchoring each statement that has a known "Walk a statement list, re-anchoring each statement that has a known
@@ -134,7 +127,7 @@ forms, and what remains."
;;; because the compiler composes these names and the user does not: a ;;; because the compiler composes these names and the user does not: a
;;; hand-written vec2__length would collide, and an identifier holding ;;; hand-written vec2__length would collide, and an identifier holding
;;; `__' is reserved in C++, which a pub header may be included from. ;;; `__' is reserved in C++, which a pub header may be included from.
;;; Lifted lambdas carry a λ for the same reason. ;;; Lifted closures carry a ƛ for the same reason.
;;; ;;;
;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised ;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised
;;; exclamation mark, both letters. Not the retroflex click ǃ, which ;;; exclamation mark, both letters. Not the retroflex click ǃ, which
@@ -166,10 +159,6 @@ forms, and what remains."
((¤) 'vector-ref) ((¤) 'vector-ref)
((include) '%include) ((include) '%include)
((static-assert) '_Static_assert) ((static-assert) '_Static_assert)
;; fmt-c's own names for these: respelled bit_and they were calls
((bit-and bit-or bit-xor bit-not bit-or=
bitwise-and bitwise-ior bitwise-xor bitwise-not bitwise-ior=)
atom)
;; a `|' inside a symbol has to be escaped to be written in ;; a `|' inside a symbol has to be escaped to be written in
;; a Scheme source, so we just rename it in fmt-c compatible ;; a Scheme source, so we just rename it in fmt-c compatible
;; way ;; way
@@ -181,12 +170,6 @@ forms, and what remains."
(unkebabify atom) (unkebabify atom)
atom)))) atom))))
;;; A name as C spells it. Only at the head of a form are some words
;;; the writer's own: (array ...) is one, (var array int) declares
;;; `array', where it came out `%array'
(define (name-to-fmt-c atom)
(if (symbol? atom) (unkebabify atom) atom))
(define (maybe-unwrap-type type) (define (maybe-unwrap-type type)
(if (and (list? type) (if (and (list? type)
(= 1 (length type))) (= 1 (length type)))
@@ -227,18 +210,24 @@ forms, and what remains."
acc)))))) acc))))))
(else (loop (cdr fs) (cons (car fs) acc)))))) (else (loop (cdr fs) (cons (car fs) acc))))))
(define (walk-generic-toplevel form)
(cond ((atom? form) (atom-to-fmt-c form))
((list? form) (map walk-generic-toplevel form))
(else (sex-error form "malformed form" form))))
(define (walk-expr form) (define (walk-expr form)
(match form (match form
((? vector?) (walk-initializer (vector->list form))) ((? vector?) (walk-initializer (vector->list form)))
((? atom?) ((? atom?)
(name-to-fmt-c form)) (atom-to-fmt-c form))
;; (comment "text") -> /* text */. `%comment' is the fmt-c directive. ;; (comment "text") -> /* text */. `%comment' is the fmt-c directive.
(('comment . text) (walk-comment text)) (('comment . text) (walk-comment text))
;; (dot-access obj field ...) -> obj.field... member access. `%.' ;; (dot-access obj field ...) -> obj.field... member access. `%.'
;; is the fmt-c directive for the `.' operator (see sex-fmt-c). ;; is the fmt-c directive for the `.' operator (see sex-fmt-c).
(('dot-access . rest) (cons '%. (map walk-expr rest))) (('dot-access . rest) (cons '%. (map walk-expr rest)))
;; `%->' is the C arrow. Nothing writes it: it is what a member ;; `%->' is the C arrow. Nothing writes it: it is what a member
;; path lowers to where the thing it reads from is a pointer ;; path lowers to where the thing it reads from is a pointer, the
;; name `->' itself being the threading macro
(('%-> . rest) (cons '%-> (map walk-expr rest))) (('%-> . rest) (cons '%-> (map walk-expr rest)))
(('var . _) (walk-var form)) (('var . _) (walk-var form))
;; semen has told a type from an expression; only it knows the names ;; semen has told a type from an expression; only it knows the names
@@ -246,7 +235,7 @@ forms, and what remains."
(('sizeof ('%type type)) `(%sizeof-type ,(walk-type type))) (('sizeof ('%type type)) `(%sizeof-type ,(walk-type type)))
;; semen has already put the target first, the way C writes it ;; semen has already put the target first, the way C writes it
(('typedef type name) (('typedef type name)
`(typedef ,(walk-type type) ,(name-to-fmt-c name))) `(typedef ,(walk-type type) ,(atom-to-fmt-c name)))
;; An expression has no room for a statement, so a comment in a ;; An expression has no room for a statement, so a comment in a
;; cast is dropped rather than relocated. ;; cast is dropped rather than relocated.
(('cast . rest) (('cast . rest)
@@ -281,7 +270,6 @@ forms, and what remains."
;; clause to be a case/default form and errors on anything else. ;; clause to be a case/default form and errors on anything else.
(('switch . rest) (('switch . rest)
(let-values (((comments slots clauses) (take-slots rest 1))) (let-values (((comments slots clauses) (take-slots rest 1)))
(check-case-labels form clauses)
(with-comments (append comments (filter comment-form? clauses)) (with-comments (append comments (filter comment-form? clauses))
(cons* 'switch (walk-expr (car slots)) (cons* 'switch (walk-expr (car slots))
(map walk-expr (remove comment-form? clauses)))))) (map walk-expr (remove comment-form? clauses))))))
@@ -296,74 +284,7 @@ forms, and what remains."
(('default . body) (cons 'default (walk-case-body body))) (('default . body) (cons 'default (walk-case-body body)))
;; Drop comments so they will not generate additional comma ;; Drop comments so they will not generate additional comma
(else (else (map walk-expr (remove comment-form? form)))))
(check-arity form)
(let ((form (remove comment-form? form)))
(if (and (memq (car form) '(++ --)) (pair? (cdr form)) (pair? (cddr form)))
;; (++ a b) steps each in turn: statements where it is one,
;; C's comma where it is a value
(cons '%comma (map (lambda (operand) (walk-expr (list (car form) operand)))
(cdr form)))
(cons (if (symbol? (car form))
(atom-to-fmt-c (car form))
(walk-expr (car form)))
(map walk-expr (cdr form))))))))
(define +comparisons+ '(< > <= >= == !=))
;;; The operands each operator takes, as (fewest . most), most #f for no
;;; limit. Past them an operator was written as it came: (/ a) as `/a',
;;; (! a b) as `a ! b', (< a b c) as C's own chain, which compares a
;;; boolean with c
(define +operator-arity+
`((,+comparisons+ 2 . 2)
((+= -= *= /= %= &= ^= |\|=| <<= >>=) 2 . 2)
((! ~ bit-not bitwise-not) 1 . 1)
((- + * & ++ --) 1 . #f)
((/ % << >> && |\|\|| ^ |\|| = bit-and bit-or bit-xor
bitwise-and bitwise-ior bitwise-xor)
2 . #f)))
(define (operator-arity head)
(find (lambda (entry) (memq head (car entry))) +operator-arity+))
(define (check-arity form)
(let ((entry (operator-arity (car form)))
(given (count (lambda (part) (not (comment-form? part))) (cdr form))))
(when entry
(let ((fewest (cadr entry))
(most (cddr entry)))
(unless (and (>= given fewest) (or (not most) (<= given most)))
(sex-error form
(if (eq? (car entry) +comparisons+)
"a comparison takes two operands; chain them with &&"
(string-append "takes "
(if (= fewest 1) "one operand" "two operands")
(if most "" " or more")))
(car form)))))))
;;; (case (1 2) ...) is two labels, so anything but a value among them
;;; was taken for one: (case (+ 1 1) ...) came out `case +: case 1:
;;; case 1:'. A value written twice in one switch C reports too, but not
;;; where.
(define (check-case-labels form clauses)
(fold (lambda (clause seen)
(let ((parts (and (pair? clause) (memq (car clause) '(case case/fallthrough))
(remove comment-form? (cdr clause)))))
(if (pair? parts)
(fold (lambda (value seen)
(unless (or (number? value) (char? value)
(number-literal? value)
(and (symbol? value) (not (operator-arity value))))
(sex-error form "a case label is a value" (car parts)))
(when (member value seen)
(sex-error form "case label written twice" value))
(cons value seen))
seen
(if (pair? (car parts)) (car parts) (list (car parts))))
seen)))
(list)
clauses))
;;; #(a b c) is a brace initializer. A `:' inside one ends a type and ;;; #(a b c) is a brace initializer. A `:' inside one ends a type and
;;; turns the whole thing into a C99 compound literal: ;;; turns the whole thing into a C99 compound literal:
@@ -372,16 +293,13 @@ forms, and what remains."
;;; language. `:' is the separator because it is the one thing that can ;;; language. `:' is the separator because it is the one thing that can
;;; be neither a type word nor an expression -- a named form would be a ;;; be neither a type word nor an expression -- a named form would be a
;;; C identifier, and so shadowable (see issue #36). ;;; C identifier, and so shadowable (see issue #36).
;;;
;;; #() is all zeros, and C11 spells that {0}: {} came in only with C23
(define (walk-initializer elements) (define (walk-initializer elements)
(let ((parts (list-split (remove comment-form? elements) ':)) (let ((parts (list-split (remove comment-form? elements) ':)))
(filled (lambda (es) (if (null? es) (list 0) (walk-designators es)))))
(if (null? (cdr parts)) (if (null? (cdr parts))
(list->vector (filled (car parts))) (list->vector (walk-designators (car parts)))
(cons* '%compound (cons* '%compound
(walk-type (maybe-unwrap-type (car parts))) (walk-type (maybe-unwrap-type (car parts)))
(filled (cadr parts)))))) (walk-designators (cadr parts))))))
;;; `.field value' is a designated initializer; anything else is ;;; `.field value' is a designated initializer; anything else is
;;; positional. C lets the two be mixed, and nothing here stops it. A ;;; positional. C lets the two be mixed, and nothing here stops it. A
@@ -391,20 +309,14 @@ forms, and what remains."
(let loop ((es elements) (acc (list))) (let loop ((es elements) (acc (list)))
(match es (match es
(() (reverse acc)) (() (reverse acc))
(((or (? designator? d) (and ('¤ _) d))) (((? designator? d))
(sex-error elements "designated initializer without a value" d)) (sex-error elements "designated initializer without a value" d))
(((? designator? d) value . rest) (((? designator? d) value . rest)
(loop rest (loop rest
(cons (list '%designate (cons (list '%designate
(name-to-fmt-c (designator-field d)) (atom-to-fmt-c (designator-field d))
(walk-expr value)) (walk-expr value))
acc))) acc)))
;; [3] 1: an element named by its index. A subscript has two
;; operands, so one alone can be nothing else
((('¤ index) value . rest)
(loop rest
(cons (list '%designate-index (walk-expr index) (walk-expr value))
acc)))
((e . rest) (loop rest (cons (walk-expr e) acc)))))) ((e . rest) (loop rest (cons (walk-expr e) acc))))))
(define (designator? x) (define (designator? x)
@@ -427,7 +339,7 @@ forms, and what remains."
(let ((form (cons (car form) (remove comment-form? (cdr form))))) (let ((form (cons (car form) (remove comment-form? (cdr form)))))
`(%var `(%var
,(walk-type (third form)) ,(walk-type (third form))
,(name-to-fmt-c (second form)) ,(atom-to-fmt-c (second form))
. .
,(if (null? (drop form 3)) ,(if (null? (drop form 3))
(list) (list)
@@ -442,10 +354,9 @@ forms, and what remains."
;; (const * const * const char) -> (const char * const * const) ;; (const * const * const char) -> (const char * const * const)
;; (fn ((int) (float)) void) -> (%fun void ((int) (float))) ;; (fn ((int) (float)) void) -> (%fun void ((int) (float)))
(match form (match form
(('¤ . _) (('¤ . array-type)
(if (array-bound? form) (if (array-bound? form)
`(%array ,(walk-type (array-element-type form)) `(%array ,(walk-type (array-element-type form)) ,(walk-expr (last array-type)))
,(walk-expr (array-bound form)))
;; sugar for pointer... Do we really need it? Guess why not, ;; sugar for pointer... Do we really need it? Guess why not,
;; it's a strong semantic cue ;; it's a strong semantic cue
`(%array ,(walk-type (array-element-type form))))) `(%array ,(walk-type (array-element-type form)))))
@@ -469,7 +380,6 @@ forms, and what remains."
(define (has-pointer-star? form) (define (has-pointer-star? form)
(and (pair? form) (and (pair? form)
(not (structured-type? form)) (not (structured-type? form))
(not (inline-aggregate? form))
(or (memq '* form) (or (memq '* form)
(any has-pointer-star? (filter pair? form))))) (any has-pointer-star? (filter pair? form)))))
@@ -498,42 +408,22 @@ forms, and what remains."
;; (fn ...) is spelled as the pointer it already is in C ;; (fn ...) is spelled as the pointer it already is in C
(sex-error type "a fn type is a function pointer already: write (fn ...), not (* (fn ...))" type) (sex-error type "a fn type is a function pointer already: write (fn ...), not (* (fn ...))" type)
(sex-error type "a pointer to an array is not supported" type)))) (sex-error type "a pointer to an array is not supported" type))))
(if (atom? type) (name-to-fmt-c type) (if (atom? type) (atom-to-fmt-c type)
(type-words (list-join (reverse (list-split type '*)) '(*))))) (flatten
(tree-map atom-to-fmt-c
;;; A type's words, flat, except that an aggregate written out in full is (flatten
;;; one of them, walked: (* (struct ((c int)))) is `struct {...} *' (list-join (reverse (list-split type '*))
(define (type-words items) '(*)))))))
(append-map (lambda (item)
(cond ((inline-aggregate? item) (list (walk-type item)))
((pair? item) (type-words item))
((null? item) (list))
(else (list (name-to-fmt-c item)))))
items))
;;; (struct ((c int))), (union u (...)), (enum (red green)): a body, not
;;; just a tag
(define (inline-aggregate? form)
(and (pair? form) (memq (car form) '(struct union enum)) (any list? (cdr form))))
(define (walk-fn-def form) (define (walk-fn-def form)
(match form (match form
(('fn name args ret-type . maybe-body) (('fn name args ret-type . maybe-body)
`(%fun `(%fun
,(walk-type ret-type) ,(walk-type ret-type)
,(name-to-fmt-c name) ,(atom-to-fmt-c name)
,(walk-arglist args) ,(walk-arglist args)
. .
,(let ((body (walk-body maybe-body))) ,(walk-body maybe-body)))))
;; one that is empty blocks, and where they were, is nothing:
;; what a lifted empty lambda is given to be a definition
(if (every (lambda (s) (equal? s '(%block-begin)))
(remove line-directive? body))
(list)
body))))))
(define (line-directive? form)
(and (pair? form) (eq? (car form) '%line)))
;;; The type of one parameter ;;; The type of one parameter
(define (arg-type arg) (define (arg-type arg)
@@ -572,7 +462,7 @@ forms, and what remains."
(define (process-struct-fields fields) (define (process-struct-fields fields)
(map (fn (map (fn
(let ((type (walk-type (last x)))) (let ((type (walk-type (last x))))
(cons type (map name-to-fmt-c (drop-right x 1))))) (cons type (map atom-to-fmt-c (drop-right x 1)))))
(remove comment-form? fields))) (remove comment-form? fields)))
(define (walk-struct form) (define (walk-struct form)
@@ -581,9 +471,9 @@ forms, and what remains."
`(,type ,(process-struct-fields fields) `(,type ,(process-struct-fields fields)
. ,(tree-map atom-to-fmt-c attrs))) . ,(tree-map atom-to-fmt-c attrs)))
((type name) ; simple 'struct whatever', like in variable def ((type name) ; simple 'struct whatever', like in variable def
`(,type ,(name-to-fmt-c name))) `(,type ,(atom-to-fmt-c name)))
((type name (fields ...) . attrs) ((type name (fields ...) . attrs)
`(,type ,(name-to-fmt-c name) `(,type ,(atom-to-fmt-c name)
,(process-struct-fields fields) ,(process-struct-fields fields)
. ,(tree-map atom-to-fmt-c attrs))) . ,(tree-map atom-to-fmt-c attrs)))
(else (sex-error form "malformed aggregate definition" form)))) (else (sex-error form "malformed aggregate definition" form))))
@@ -595,24 +485,18 @@ forms, and what remains."
;; before the anonymous case, since `(enum (red green))' is also a ;; before the anonymous case, since `(enum (red green))' is also a
;; two-element form ;; two-element form
(('enum (? symbol? name)) (('enum (? symbol? name))
`(enum ,(name-to-fmt-c name))) `(enum ,(atom-to-fmt-c name)))
(('enum (values ...)) (('enum (values ...))
`(enum ,(map walk-enumerator values))) `(enum ,(map walk-enumerator values)))
(('enum name (values ...)) (('enum name (values ...))
`(enum ,(name-to-fmt-c name) ,(map walk-enumerator values))) `(enum ,(atom-to-fmt-c name) ,(map walk-enumerator values)))
(else (sex-error form "malformed enum" form)))) (else (sex-error form "malformed enum" form))))
;;; red -> red, (wire-varint 0) -> wire_varint = 0 ;;; red -> red, (wire-varint 0) -> wire_varint = 0
(define (walk-enumerator value) (define (walk-enumerator value)
(match value (match value
(((? enumerator-name? name) expr) (list (name-to-fmt-c name) (walk-expr expr))) ((name expr) (list (atom-to-fmt-c name) (walk-expr expr)))
((? enumerator-name?) (name-to-fmt-c value)) (_ (atom-to-fmt-c value))))
;; anything else was taken apart as if it were the pair: (! 1 2)
;; came out `! = 1'
(_ (sex-error value "an enumerator is a name, or (name value)" value))))
(define (enumerator-name? x)
(and (symbol? x) (not (operator-arity x))))
(define (walk-extern form) (define (walk-extern form)
(match form (match form

45
infer.module.scm Normal file
View File

@@ -0,0 +1,45 @@
(module infer
(;; The IR
tvar?
tvar-id
tvar-classes
tvar-rigid?
fresh-tvar
fresh-rigid-tvar
prim-type? prim-name prim-quals make-prim
ptr-type? ptr-target ptr-quals make-ptr
array-type? array-elt array-size make-array-type
fn-type? fn-ret fn-args fn-variadic? make-fn-type
agg-type? agg-kind agg-name agg-spelling agg-quals make-agg
alias-type? alias-name alias-expansion alias-quals make-alias
unknown-type? the-unknown-type
resolve
underlying
c-primitive?
type-quals
free-tvars
decay
;; The boundary
parse-type
unparse-type
;; Constraints
register-class!
add-instance!
entails?
default-tvar!
default-type-variables!
;; Unification
unify
;; Type schemes
scheme? scheme-vars scheme-constraints scheme-type
make-scheme
generalize
instantiate
substitute)
"infer.scm")

335
infer.scm
View File

@@ -1,8 +1,8 @@
;;; Type inference, layer 0: the type representation and unification. ;;; Type inference, layer 0: the type representation and unification.
;;; ;;;
;;; semen solves the wildcards of a declared type with it -- `(var n _ ;;; Nothing in the compiler calls this unit yet. It is the ground floor
;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand ;;; of the pass described in Type-inference.org -- built and tested on
;;; decays or promotes to. ;;; its own before a single form is routed through it.
;;; ;;;
;;; Two representations meet here. *Surface* types are the forms the ;;; Two representations meet here. *Surface* types are the forms the
;;; rest of the compiler passes around -- `int', `(* const char)', ;;; rest of the compiler passes around -- `int', `(* const char)',
@@ -25,49 +25,39 @@
scheme scheme
(scheme base) (scheme base)
(chicken base) (chicken base)
(chicken module)
matchable matchable
srfi-1 srfi-1
srfi-69
types types
utils) utils)
(export
;; The IR
tvar?
prim-type? prim-name
ptr-type?
array-type? array-elt
resolve
underlying
c-primitive?
decay
unqualified
;; The boundary
parse-type
unparse-type
unify)
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; The IR ;;; The IR
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; A type variable is a mutable cell. `ref' is #f while unsolved and ;;; A type variable is a mutable cell. `ref' is #f while unsolved and
;;; the type it stands for once bound -- union-find, with the path ;;; the type it stands for once bound -- union-find, with the path
;;; compression done in `resolve'. `quals' are the ones written on it -- ;;; compression done in `resolve'.
;;; `(const _)' -- and go onto whatever it is bound to. ;;;
;;; `classes' is the list of type classes the variable must satisfy
;;; (`numeric', and one day `ord'); see "constraints" below. `rigid?'
;;; marks a variable that must not unify with anything but itself --
;;; unused until a `fn' grows type parameters, and five lines now
;;; against an IR change later.
(define-record-type <tvar> (define-record-type <tvar>
(%make-tvar ref quals) (%make-tvar id ref classes rigid?)
tvar? tvar?
(id tvar-id)
(ref tvar-ref tvar-ref-set!) (ref tvar-ref tvar-ref-set!)
(quals tvar-quals tvar-quals-set!)) (classes tvar-classes tvar-classes-set!)
(rigid? tvar-rigid?))
;;; A primitive or otherwise nominal type. `name' is the list of words ;;; A primitive or otherwise nominal type. `name' is the list of words
;;; making it up, so `int', `(unsigned int)' and `(long long)' are all ;;; making it up, so `int', `(unsigned int)' and `(long long)' are all
;;; one node, and so is a name we have never parsed a declaration for ;;; one node, and so is a name we have never parsed a declaration for
;;; (`size-t', `GLuint'). The two cases are told apart by ;;; (`size-t', `GLuint'). The two cases are told apart by
;;; `c-primitive?'. ;;; `c-primitive?', which is what keeps a constraint over an unparsed C
;;; typedef from being an error.
(define-record-type <prim> (define-record-type <prim>
(make-prim name quals) (make-prim name quals)
prim-type? prim-type?
@@ -80,9 +70,8 @@
(target ptr-target) (target ptr-target)
(quals ptr-quals)) (quals ptr-quals))
;;; `size' is the length as written -- 4, N, (* 2 N) -- or #f for ;;; `size' is an integer, or #f for `(¤ int)' -- an array of unwritten
;;; `(¤ int)', an array of unwritten length. Two are one length when ;;; length.
;;; they are written alike.
(define-record-type <array> (define-record-type <array>
(make-array-type elt size) (make-array-type elt size)
array-type? array-type?
@@ -118,8 +107,25 @@
(expansion alias-expansion) (expansion alias-expansion)
(quals alias-quals)) (quals alias-quals))
(define (fresh-tvar) ;;; `?'. Sex has full C interop, so `printf', `SDL-CreateWindow' and
(%make-tvar #f (list))) ;;; `size-t' arrive from headers nobody parsed. Rather than reject
;;; every real program, the lattice gets a top element: `?' is
;;; consistent with every type and constrains nothing.
(define-record-type <unknown>
(%make-unknown)
unknown-type?)
(define the-unknown-type (%make-unknown))
(define tvar-counter 0)
(define (fresh-tvar . classes)
(set! tvar-counter (+ tvar-counter 1))
(%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #f))
(define (fresh-rigid-tvar . classes)
(set! tvar-counter (+ tvar-counter 1))
(%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #t))
;;; Follow a bound variable to what it stands for, compressing the path ;;; Follow a bound variable to what it stands for, compressing the path
;;; on the way out. Every procedure that looks at a type's shape starts ;;; on the way out. Every procedure that looks at a type's shape starts
@@ -155,15 +161,15 @@
((fn-type? t) (make-ptr t (list))) ((fn-type? t) (make-ptr t (list)))
(else (resolve type))))) (else (resolve type)))))
;;; TYPE as a value has it: qualifiers belong to an object, not to what (define (free-tvars type)
;;; is read out of one. `(const int)' -> `int', `(* const char)' as is. (let collect ((t type) (acc (list)))
(define (unqualified type) (let ((t (resolve t)))
(let ((t (resolve type))) (cond ((tvar? t) (if (memq t acc) acc (cons t acc)))
(cond ((prim-type? t) (make-prim (prim-name t) (list))) ((ptr-type? t) (collect (ptr-target t) acc))
((ptr-type? t) (make-ptr (ptr-target t) (list))) ((array-type? t) (collect (array-elt t) acc))
((agg-type? t) (make-agg (agg-kind t) (agg-name t) (agg-spelling t) (list))) ((alias-type? t) (collect (alias-expansion t) acc))
((alias-type? t) (make-alias (alias-name t) (alias-expansion t) (list))) ((fn-type? t) (fold collect (collect (fn-ret t) acc) (fn-args t)))
(else t)))) (else acc)))))
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; Surface -> IR ;;; Surface -> IR
@@ -213,7 +219,7 @@
;; The type-level wildcard. It is a fresh variable wherever it ;; The type-level wildcard. It is a fresh variable wherever it
;; appears, which is what makes partial types -- `(* _)', `(¤ _ 4)' ;; appears, which is what makes partial types -- `(* _)', `(¤ _ 4)'
;; -- fall out for free rather than needing their own grammar. ;; -- fall out for free rather than needing their own grammar.
((equal? words '(_)) (with-quals (fresh-tvar) quals)) ((equal? words '(_)) (fresh-tvar))
((and (null? (cdr words)) (get-underlying-type (car words))) ((and (null? (cdr words)) (get-underlying-type (car words)))
=> (lambda (target) => (lambda (target)
(make-alias (car words) (parse-type target) quals))) (make-alias (car words) (parse-type target) quals)))
@@ -225,15 +231,15 @@
(name (and (pair? (cdr words)) (symbol? (cadr words)) (cadr words)))) (name (and (pair? (cdr words)) (symbol? (cadr words)) (cadr words))))
(make-agg kind name words quals))) (make-agg kind name words quals)))
;;; (¤ elt ... size) -- the size is the bound `types' finds there: an ;;; (¤ elt ... size) -- the size is the last element when it is an
;;; integer, a name, an expression, or absent. The element words are ;;; integer, and absent otherwise. The element words are unwrapped the
;;; unwrapped the way the C writer unwraps them, so `[int 16]' and ;;; way the C writer unwraps them, so `[int 16]' and `[(int) 16]' are
;;; `[(int) 16]' are one type. ;;; one type.
(define (parse-array surface) (define (parse-array surface)
(let* ((nested (nest-array-type surface)) (let* ((rest (cdr surface))
(sized? (array-bound? nested)) (sized? (and (pair? rest) (integer? (last rest))))
(size (and sized? (array-bound nested))) (size (and sized? (last rest)))
(words (if sized? (drop-right (cdr nested) 1) (cdr nested)))) (words (if sized? (drop-right rest 1) rest)))
(when (null? words) (when (null? words)
(sex-error surface "array type without an element type" surface)) (sex-error surface "array type without an element type" surface))
(make-array-type (parse-type (maybe-unwrap words)) size))) (make-array-type (parse-type (maybe-unwrap words)) size)))
@@ -278,22 +284,20 @@
(if (list? s) s (list s)))) (if (list? s) s (list s))))
;;; Re-qualify a parsed type, for the grouping case `(const (struct s))' ;;; Re-qualify a parsed type, for the grouping case `(const (struct s))'
;;; where the qualifier is read before the thing it qualifies, and for a ;;; where the qualifier is read before the thing it qualifies.
;;; variable solved to a type: `(* const _)' against `(const int)' says
;;; const once.
(define (with-quals type quals) (define (with-quals type quals)
(define (plus written) (append quals (remove (lambda (q) (memq q quals)) written)))
(if (null? quals) (if (null? quals)
type type
(cond ((prim-type? type) (make-prim (prim-name type) (plus (prim-quals type)))) (cond ((prim-type? type) (make-prim (prim-name type)
((ptr-type? type) (make-ptr (ptr-target type) (plus (ptr-quals type)))) (append quals (prim-quals type))))
((ptr-type? type) (make-ptr (ptr-target type)
(append quals (ptr-quals type))))
((agg-type? type) (make-agg (agg-kind type) (agg-name type) ((agg-type? type) (make-agg (agg-kind type) (agg-name type)
(agg-spelling type) (agg-spelling type)
(plus (agg-quals type)))) (append quals (agg-quals type))))
((alias-type? type) (make-alias (alias-name type) ((alias-type? type) (make-alias (alias-name type)
(alias-expansion type) (alias-expansion type)
(plus (alias-quals type)))) (append quals (alias-quals type))))
((tvar? type) (tvar-quals-set! type (plus (tvar-quals type))) type)
(else type)))) (else type))))
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
@@ -307,6 +311,7 @@
(let ((t (resolve type))) (let ((t (resolve type)))
(cond (cond
((tvar? t) '_) ((tvar? t) '_)
((unknown-type? t) '?)
((alias-type? t) (qualify (alias-quals t) (list (alias-name t)))) ((alias-type? t) (qualify (alias-quals t) (list (alias-name t))))
((prim-type? t) (qualify (prim-quals t) (prim-name t))) ((prim-type? t) (qualify (prim-quals t) (prim-name t)))
((agg-type? t) (qualify (agg-quals t) (agg-spelling t))) ((agg-type? t) (qualify (agg-quals t) (agg-spelling t)))
@@ -346,9 +351,69 @@
(else surface))) (else surface)))
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; C's own types ;;; Constraints
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; `(numeric a)' is already a type class, so it is written as one from
;;; the start: one representation, one table, one entailment check. A
;;; trait bound `(ord (struct circle))' is the same shape, discharged
;;; the same way, and reported by the same procedure -- which is the
;;; whole reason to build it this way while there is only one kind of
;;; constraint to build.
;;;
;;; `default' is the type an unresolved constraint falls back to, the
;;; way Haskell defaults `Num a' to Integer. `test' is how the built-in
;;; classes say "every arithmetic type" without enumerating twenty
;;; spellings as instances; a user trait has no test and lives entirely
;;; in the instance table. `strict?' marks a class that must not be
;;; guessed at: static dispatch needs a real instance, so `?' fails it.
(define-record-type <type-class>
(%make-type-class name default test strict?)
type-class?
(name type-class-name)
(default type-class-default)
(test type-class-test)
(strict? type-class-strict?))
(define +classes+ (make-hash-table))
(define +instances+ (make-hash-table))
(define (register-class! name default test strict?)
(hash-table-set! +classes+ name (%make-type-class name default test strict?)))
(define (get-class name)
(or (hash-table-ref/default +classes+ name #f)
(error "no such type class" name)))
;;; Instances key on the *resolved* type, so `(impl show for size-t)'
;;; and `(impl show for unsigned long)' collide rather than quietly
;;; coexisting as two instances of one C type.
(define (instance-key type)
(unparse-type (underlying type)))
(define (add-instance! class-name type)
(hash-table-set! +instances+ (cons class-name (instance-key type)) #t))
(define (has-instance? class-name type)
(hash-table-exists? +instances+ (cons class-name (instance-key type))))
;;; #t, #f, or 'unknown -- and the third answer is the important one.
;;; A C name we never parsed a declaration for might well be numeric;
;;; saying #f there would reject working programs, and saying #t would
;;; invent knowledge. 'unknown means "do not constrain, do not
;;; complain".
(define (entails? class-name type)
(let ((cls (get-class class-name))
(t (underlying type)))
(cond
((tvar? t) 'unknown)
;; `?' is consistent with every type, but it entails nothing:
;; there is no instance to select and no name to mangle.
((unknown-type? t) (if (type-class-strict? cls) #f 'unknown))
((has-instance? class-name t) #t)
((type-class-test cls) => (lambda (test) (test t)))
(else #f))))
(define +integer-words+ '(char short int long signed unsigned bool _Bool)) (define +integer-words+ '(char short int long signed unsigned bool _Bool))
(define +float-words+ '(float double)) (define +float-words+ '(float double))
(define +known-words+ (append '(void) +integer-words+ +float-words+)) (define +known-words+ (append '(void) +integer-words+ +float-words+))
@@ -359,18 +424,97 @@
(and (prim-type? t) (and (prim-type? t)
(every (lambda (word) (memq word +known-words+)) (prim-name t)))) (every (lambda (word) (memq word +known-words+)) (prim-name t))))
(define (void-type? t)
(and (prim-type? t) (equal? (prim-name t) '(void))))
(define (arithmetic-type? t)
(cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t) ; an enum is an integer
((not (prim-type? t)) #f)
((not (c-primitive? t)) 'unknown)
((void-type? t) #f)
(else #t)))
(define (integral-type? t)
(cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t)
((not (prim-type? t)) #f)
((not (c-primitive? t)) 'unknown)
((void-type? t) #f)
((any (lambda (word) (memq word +float-words+)) (prim-name t)) #f)
(else #t)))
(define (floating-type? t)
(cond ((not (prim-type? t)) #f)
((not (c-primitive? t)) 'unknown)
(else (and (any (lambda (word) (memq word +float-words+)) (prim-name t))
#t))))
(define (scalar-type? t)
(cond ((ptr-type? t) #t)
((array-type? t) #t) ; decays to one
((fn-type? t) #t) ; likewise
(else (arithmetic-type? t))))
;;; The built-ins. They are ordinary classes, registered the same way a
;;; trait will be -- that is the point.
(register-class! 'numeric 'int arithmetic-type? #f)
(register-class! 'integral 'int integral-type? #f)
(register-class! 'floating 'double floating-type? #f)
(register-class! 'scalar #f scalar-type? #f)
;;; A constraint that survives to the end of a function is defaulted:
;;; `(numeric a)' with nothing else known is an `int'. A *strict*
;;; class has no default and no business guessing, so an unresolved one
;;; is an error -- the rule is worth stating while there is only one
;;; kind of constraint to state it about.
(define (default-tvar! v form)
(let ((strict (find (lambda (c) (type-class-strict? (get-class c)))
(tvar-classes v))))
(cond
(strict (sex-error form "unresolved constraint" (list strict (unparse-type v))))
((find (lambda (c) (type-class-default (get-class c))) (tvar-classes v))
=> (lambda (c)
(tvar-ref-set! v (parse-type (type-class-default (get-class c))))
#t))
(else #f))))
;;; Default every variable still open in TYPE. Returns #t when none is
;;; left unsolved, so a caller can tell "inferred" from "give up and
;;; ask for the type in writing".
(define (default-type-variables! type form)
(fold (lambda (v ok) (and (default-tvar! v form) ok))
#t
(free-tvars type)))
(define (check-classes classes type form)
(for-each
(lambda (c)
(when (eq? #f (entails? c type))
(sex-error form "type does not satisfy a constraint"
(list c (unparse-type type)))))
classes))
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; Unification ;;; Unification
;;; --------------------------------------------------------------- ;;; ---------------------------------------------------------------
;;; Consistency in the gradual-typing sense rather than equality: `?'
;;; succeeds against anything and binds nothing, which is what keeps
;;; the pass from rejecting every program that includes a C header.
;;;
;;; FORM is carried only so a failure can say where it was written. ;;; FORM is carried only so a failure can say where it was written.
(define (unify t1 t2 form) (define (unify t1 t2 form)
(let ((a (resolve t1)) (let ((a (resolve t1))
(b (resolve t2))) (b (resolve t2)))
(cond (cond
((eq? a b) #t) ((eq? a b) #t)
((tvar? a) (bind-tvar! a b form)) ((unknown-type? a) #t)
((tvar? b) (bind-tvar! b a form)) ((unknown-type? b) #t)
;; Whichever side is free takes the binding: `(unify a r)' and
;; `(unify r a)' both leave `a' bound to `r'. Two rigid and
;; distinct is the mismatch `eq?' above let through.
((and (tvar? a) (not (tvar-rigid? a))) (bind-tvar! a b form))
((and (tvar? b) (not (tvar-rigid? b))) (bind-tvar! b a form))
((or (tvar? a) (tvar? b)) (type-mismatch a b form))
;; A typedef unifies as what it stands for. Its name survives in ;; A typedef unifies as what it stands for. Its name survives in
;; whichever side is printed later, since neither side is rebuilt. ;; whichever side is printed later, since neither side is rebuilt.
((alias-type? a) (unify (alias-expansion a) b form)) ((alias-type? a) (unify (alias-expansion a) b form))
@@ -386,7 +530,7 @@
;; One of them may be `(¤ int)': an unwritten length constrains ;; One of them may be `(¤ int)': an unwritten length constrains
;; nothing, the way it does not in C either. ;; nothing, the way it does not in C either.
(when (and (array-size a) (array-size b) (when (and (array-size a) (array-size b)
(not (equal? (array-size a) (array-size b)))) (not (= (array-size a) (array-size b))))
(type-mismatch a b form)) (type-mismatch a b form))
(unify (array-elt a) (array-elt b) form)) (unify (array-elt a) (array-elt b) form))
((and (fn-type? a) (fn-type? b)) ((and (fn-type? a) (fn-type? b))
@@ -424,7 +568,16 @@
;; Without recursive types this cannot trigger. It is four lines, ;; Without recursive types this cannot trigger. It is four lines,
;; and the alternative to having it is a hang. ;; and the alternative to having it is a hang.
((occurs? v t) (sex-error form "recursive type" (unparse-type v))) ((occurs? v t) (sex-error form "recursive type" (unparse-type v)))
(else (tvar-ref-set! v (with-quals t (tvar-quals v))) #t))) ;; A rigid variable is a type *parameter*: inside a generic body it
;; stands for one specific unknown type and must not be solved.
((tvar-rigid? v) (type-mismatch v t form))
(else
(when (tvar? t)
(tvar-classes-set! t (lset-union eq? (tvar-classes t) (tvar-classes v))))
(tvar-ref-set! v t)
(unless (tvar? t)
(check-classes (tvar-classes v) t form))
#t)))
(define (occurs? v type) (define (occurs? v type)
(let ((t (resolve type))) (let ((t (resolve type)))
@@ -435,3 +588,57 @@
((fn-type? t) (or (occurs? v (fn-ret t)) ((fn-type? t) (or (occurs? v (fn-ret t))
(any (lambda (a) (occurs? v a)) (fn-args t)))) (any (lambda (a) (occurs? v a)) (fn-args t))))
(else #f)))) (else #f))))
;;; ---------------------------------------------------------------
;;; Type schemes
;;; ---------------------------------------------------------------
;;; Nothing generalizes yet -- every `fn' in Sex carries a written
;;; signature and there is no polymorphism to abstract over. These are
;;; here because they are ten lines on top of unification and because
;;; they are exactly what a `fn' with type parameters needs, and
;;; because a scheme without a constraint list is the wrong shape for
;;; every bounded generic. `(forall vars constraints type)' it is,
;;; from the start.
(define-record-type <scheme>
(make-scheme vars constraints type)
scheme?
(vars scheme-vars)
(constraints scheme-constraints)
(type scheme-type))
;;; Quantify over everything free in TYPE that is not also free in the
;;; environment, carrying each variable's class constraints along as
;;; the scheme's context.
(define (generalize type env-tvars)
(let ((vars (lset-difference eq? (free-tvars type) env-tvars)))
(make-scheme vars
(append-map (lambda (v)
(map (lambda (c) (cons c v)) (tvar-classes v)))
vars)
type)))
(define (instantiate scheme)
(let ((subst (map (lambda (v) (cons v (fresh-tvar (tvar-classes v))))
(scheme-vars scheme))))
(substitute (scheme-type scheme) subst)))
;;; Structural copy with the variables in SUBST replaced. Copying is
;;; how a generic body must be handled anyway -- `form-type' is keyed
;;; by cons cell, one form one type, so an instantiation gets fresh
;;; cells rather than a second type for the same cell.
(define (substitute type subst)
(let ((t (resolve type)))
(cond
((tvar? t) (let ((hit (assq t subst))) (if hit (cdr hit) t)))
((ptr-type? t) (make-ptr (substitute (ptr-target t) subst) (ptr-quals t)))
((array-type? t) (make-array-type (substitute (array-elt t) subst)
(array-size t)))
((alias-type? t) (make-alias (alias-name t)
(substitute (alias-expansion t) subst)
(alias-quals t)))
((fn-type? t) (make-fn-type (substitute (fn-ret t) subst)
(map (lambda (a) (substitute a subst))
(fn-args t))
(fn-variadic? t)))
(else t))))

View File

@@ -1,16 +0,0 @@
* 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)~.

6
reader.module.scm Normal file
View File

@@ -0,0 +1,6 @@
(module reader (read-from-file
read-raw-forms
current-features
platform-features)
"reader.scm")

View File

@@ -16,26 +16,11 @@
scheme scheme
(scheme base) ; make-parameter (scheme base) ; make-parameter
(chicken base) (chicken base)
(chicken condition)
(chicken irregex)
(chicken module)
(chicken pathname) (chicken pathname)
(chicken platform) ; software-version, machine-type (chicken platform) ; software-version, machine-type
(only (chicken string) substring-index)
(only srfi-1 every any) ; srfi-1 also has an append-reverse (only srfi-1 every any) ; srfi-1 also has an append-reverse
utils) utils)
(export
read-from-file
read-raw-forms
current-features
platform-features
number-literal?
number-literal-value
number-literal-suffix)
;;; Sentinels for structural tokens ;;; Sentinels for structural tokens
(define close-paren (list '%close-paren)) (define close-paren (list '%close-paren))
(define close-bracket (list '%close-bracket)) (define close-bracket (list '%close-bracket))
@@ -100,18 +85,18 @@
((char=? c #\() ((char=? c #\()
(let ((line (current-line))) (let ((line (current-line)))
(get-ch port) (get-ch port)
(stamp (read-list port close-paren line) line))) (stamp (read-list port close-paren) line)))
((char=? c #\[) ((char=? c #\[)
(let ((line (current-line))) (let ((line (current-line)))
(get-ch port) (get-ch port)
(stamp (cons '¤ (read-list port close-bracket line)) line))) (stamp (cons '¤ (read-list port close-bracket)) line)))
((char=? c #\)) (get-ch port) close-paren) ((char=? c #\)) (get-ch port) close-paren)
((char=? c #\]) (get-ch port) close-bracket) ((char=? c #\]) (get-ch port) close-bracket)
((char=? c #\;) ((char=? c #\;)
(let ((line (current-line))) (let ((line (current-line)))
(stamp (read-comment port) line))) (stamp (read-comment port) line)))
((char=? c #\") (read-string-lit port)) ((char=? c #\") (read-string-lit port))
((char=? c #\') (get-ch port) (list 'quote (read-quoted port))) ((char=? c #\') (get-ch port) (list 'quote (read-datum port)))
((char=? c #\`) (get-ch port) (list 'quasiquote (read-datum port))) ((char=? c #\`) (get-ch port) (list 'quasiquote (read-datum port)))
((char=? c #\,) ((char=? c #\,)
(get-ch port) (get-ch port)
@@ -149,14 +134,11 @@
;;; Read list elements up to close-paren or close-bracket, ;;; Read list elements up to close-paren or close-bracket,
;;; honoring dotted-pair notation (a b . c) ;;; honoring dotted-pair notation (a b . c)
(define (read-list port closer opened) (define (read-list port closer)
(let loop ((acc (list))) (let loop ((acc (list)))
(let ((tok (next-token port))) (let ((tok (next-token port)))
(cond (cond
((eof-object? tok) ((eof-object? tok) (error "Unexpected end of input inside list"))
(error (string-append
"Unexpected end of input inside a list opened on line "
(number->string opened))))
((eq? tok close-paren) ((eq? tok close-paren)
(if (eq? closer close-paren) (if (eq? closer close-paren)
(reverse acc) (reverse acc)
@@ -193,181 +175,35 @@
(finish-atom (list->string (reverse chars))) (finish-atom (list->string (reverse chars)))
(begin (get-ch port) (loop (cons c chars))))))) (begin (get-ch port) (loop (cons c chars)))))))
;;; ...except quoted, alone: '-fields is a name, as in (cat name '-fields).
;;; A quoted list is code a macro hands back as often as not, and keeps
;;; the rule
(define negating? (make-parameter #t))
(define (read-quoted port)
(if (memv (peek port) '(#\( #\[ #\' #\` #\, #\# #\" #\;))
(read-datum port)
(parameterize ((negating? #f)) (read-datum port))))
(define (finish-atom s) (define (finish-atom s)
(let ((digits (if (substring-index "_" s) (or (ungrouped s (or (c-radix s) 10)) s) s))) (cond
;; 017 is 17 to Scheme and 15 to C: whoever reads the Sex and whoever ((string=? s ".") dot-token)
;; reads the C would each take it for something else ((string->number s) => identity)
(when (irregex-match "-?0[0-9]+[uUlL]*" digits) ((radix-number s) => identity)
(error ((negated-name? s) (list '- (string->symbol (substring s 1))))
"a leading 0 is octal to C; write the number without it, or #o for octal" (else (string->symbol s))))
s))
(cond
((string=? s ".") dot-token)
((or (string->number digits) (radix-number digits))
=> (lambda (n) (c-number n s)))
((spelled-number digits s) => identity)
((negated-name? s) (list '- (string->symbol (substring s 1))))
(else (string->symbol s)))))
;;; 1_000_000, 0xFF_FF: `_' between two digits groups them, the way
;;; C23's ' does -- which in Sex is quote. S without them, or #f when a
;;; `_' stands anywhere else, where it is part of a name
(define (ungrouped s radix)
(let ((digit? (lambda (c) (string->number (string c) radix))))
(let loop ((cs (string->list s)) (previous #f) (acc (list)))
(cond ((null? cs) (list->string (reverse acc)))
((char=? (car cs) #\_)
(and previous (digit? previous) (pair? (cdr cs)) (digit? (cadr cs))
(loop (cdr cs) (car cs) acc)))
(else (loop (cdr cs) (car cs) (cons (car cs) acc)))))))
;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400,
;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide
;;; for long long is unsigned to C, which says so only by a warning
;;; unless it is written with a `u'; so it is. -9223372036854775808 is
;;; one too: C negates the unsigned 9223372036854775808, so it is
;;; spelled as LLONG_MIN is, -9223372036854775807 - 1.
(define +llong-min+ (- (expt 2 63)))
(define +llong-max+ (- (expt 2 63) 1))
(define +ullong-max+ (- (expt 2 64) 1))
(define (c-number n s)
(cond ((exact-integer? n)
(cond ((> (abs n) +ullong-max+)
(error "too large for any C integer type" s))
((> n +llong-max+) (make-number-literal n "u" #f))
((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f)))
((= n +llong-min+) (list '- (+ n 1) 1))
(else n)))
((and (real? n) (inexact? n) (finite? n)) n)
(else (error "C has no literal for this number" s))))
;;; 1u, 10L, 1ULL, 1.5f, 0.1L, 0x1.8p3: a number with C's suffix, or a
;;; hex float, which the C is written with.
;;;
;;; 0b101u -> 5u in decimal, so C23's 0b never reaches C11
;;; 0.1f -> 0.1f in the digits written: through a double, 0.1f
;;; could round to another float, and 0.1L would
;;; lose all it has over one
;;; -1u -> (- 1u) which is what C reads it as too
(define-record-type <number-literal>
(make-number-literal value suffix digits)
number-literal?
(value number-literal-value)
(suffix number-literal-suffix)
(digits number-literal-digits))
(set-record-printer! <number-literal>
(lambda (literal port)
(display (or (number-literal-digits literal)
(number->string (number-literal-value literal)))
port)
(display (number-literal-suffix literal) port)))
(define suffixed-integer
(irregex "(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9]+)([uU](?:ll|LL|l|L)?|(?:ll|LL|l|L)[uU]?)"))
(define suffixed-float
(irregex "((?:[0-9]+\\.[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)([fFlL])"))
(define hex-float
(irregex "(0[xX]([0-9a-fA-F]*)\\.?([0-9a-fA-F]*)[pP]([+-]?[0-9]+))([fFlL]?)"))
(define (spelled-number digits s)
(let* ((negative? (and (> (string-length digits) 1) (char=? #\- (string-ref digits 0))))
(body (if negative? (substring digits 1) digits))
;; each spelling begins with a digit or a point, and few names do
(literal (and (> (string-length body) 0)
(or (char-numeric? (string-ref body 0))
(char=? #\. (string-ref body 0)))
(or (suffixed-integer-literal body s)
(suffixed-float-literal body s)
(hex-float-literal body s)))))
(and literal (if negative? (list '- literal) literal))))
(define (suffixed-integer-literal body s)
(let ((m (irregex-match suffixed-integer body)))
(and m
(let* ((digits (irregex-match-substring m 1))
(suffix (irregex-match-substring m 2))
(n (or (radix-number digits) (string->number digits)))
(widest (if (irregex-search "[uU]" suffix) +ullong-max+ +llong-max+)))
(when (> n widest)
(error "too large for its suffix" s))
(make-number-literal n suffix #f)))))
;;; 0x1.8p3 is 0x18 sixteenths times 2^3
(define (hex-float-literal body s)
(let ((m (irregex-match hex-float body)))
(and m
(let ((whole (irregex-match-substring m 2))
(fraction (irregex-match-substring m 3))
(exponent (string->number (irregex-match-substring m 4)))
(suffix (irregex-match-substring m 5)))
(and (> (+ (string-length whole) (string-length fraction)) 0)
(float-literal
(if (> (abs exponent) 20000) ; past any C type
(if (> exponent 0) +inf.0 0.)
(exact->inexact
(* (string->number (string-append whole fraction) 16)
(expt 2 (- exponent (* 4 (string-length fraction)))))))
suffix (irregex-match-substring m 1) s))))))
(define (suffixed-float-literal body s)
(let ((m (irregex-match suffixed-float body)))
(and m
(let ((digits (irregex-match-substring m 1)))
(float-literal (string->number digits) (irregex-match-substring m 2)
digits s)))))
(define (float-literal n suffix digits s)
(unless (in-range? n suffix)
(error "C has no literal for this number" s))
(make-number-literal n suffix digits))
;;; A float overflows where it would round past FLT_MAX; a long double
;;; may be wider than any double, so whatever a double holds it does too
(define (in-range? n suffix)
(cond ((string-ci=? suffix "f") (< (abs n) (* (- 2 (expt 2. -24)) (expt 2. 127))))
((string-ci=? suffix "l") #t)
(else (finite? n))))
;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those ;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those
;;; numbers: the C written from them says 224 and 5 ;;; numbers: the C written from them says 224 and 5
(define (radix-number s) (define (radix-number s)
(let ((radix (c-radix s))) (let* ((negative? (and (> (string-length s) 0) (char=? #\- (string-ref s 0))))
(and radix (digits (if negative? (substring s 1) s)))
(let* ((negative? (char=? #\- (string-ref s 0))) (and (> (string-length digits) 2)
(body (substring s (if negative? 3 2)))) (char=? #\0 (string-ref digits 0))
(and (not (memv (string-ref body 0) '(#\+ #\-))) (let ((radix (case (string-ref digits 1)
((#\x #\X) 16)
((#\b #\B) 2)
(else #f)))
(body (substring digits 2)))
(and radix
(not (memv (string-ref body 0) '(#\+ #\-)))
(let ((n (string->number body radix))) (let ((n (string->number body radix)))
(and (exact-integer? n) (if negative? (- n) n)))))))) (and (exact-integer? n) (if negative? (- n) n))))))))
;;; 16 for 0xE0 and 2 for 0b101, a minus aside; #f for any other spelling
(define (c-radix s)
(let ((i (if (and (> (string-length s) 0) (char=? #\- (string-ref s 0))) 1 0)))
(and (> (string-length s) (+ i 2))
(char=? #\0 (string-ref s i))
(case (string-ref s (+ i 1))
((#\x #\X) 16)
((#\b #\B) 2)
(else #f)))))
;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with ;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with
;;; a dash, and an operator that does goes on with a non-letter: -> -- ;;; a dash, and an operator that does goes on with a non-letter: -> --
(define (negated-name? s) (define (negated-name? s)
(and (negating?) (and (> (string-length s) 1)
(> (string-length s) 1)
(char=? #\- (string-ref s 0)) (char=? #\- (string-ref s 0))
(let ((c (string-ref s 1))) (let ((c (string-ref s 1)))
(or (char-alphabetic? c) (char=? c #\_))))) (or (char-alphabetic? c) (char=? c #\_)))))
@@ -381,7 +217,7 @@
((or (char=? c #\t) (char=? c #\T)) (read-bool port #t)) ((or (char=? c #\t) (char=? c #\T)) (read-bool port #t))
((or (char=? c #\f) (char=? c #\F)) (read-bool port #f)) ((or (char=? c #\f) (char=? c #\F)) (read-bool port #f))
((char=? c #\\) (read-char-lit port)) ((char=? c #\\) (read-char-lit port))
((char=? c #\() (list->vector (read-list port close-paren (current-line)))) ((char=? c #\() (list->vector (read-list port close-paren)))
((memv c '(#\x #\X)) (read-radix port 16)) ((memv c '(#\x #\X)) (read-radix port 16))
((memv c '(#\b #\B)) (read-radix port 2)) ((memv c '(#\b #\B)) (read-radix port 2))
((memv c '(#\o #\O)) (read-radix port 8)) ((memv c '(#\o #\O)) (read-radix port 8))
@@ -441,7 +277,7 @@
;;; #x80, #b101, #o10 ;;; #x80, #b101, #o10
(define (read-radix port radix) (define (read-radix port radix)
(let* ((digits (read-atom-string port)) (let* ((digits (read-atom-string port))
(n (string->number (or (ungrouped digits radix) digits) radix))) (n (string->number digits radix)))
(if (exact-integer? n) (if (exact-integer? n)
n n
(error "Malformed number" digits)))) (error "Malformed number" digits))))
@@ -469,15 +305,10 @@
("delete" . #\delete) ("escape" . #\escape) ("alarm" . #\alarm) ("delete" . #\delete) ("escape" . #\escape) ("alarm" . #\alarm)
("backspace" . #\backspace))) ("backspace" . #\backspace)))
;;; A char is C's, one byte: #\λ was a multi-character constant, whose
;;; value is the C compiler's to choose
(define (read-char-lit port) (define (read-char-lit port)
(let ((first (get-ch port))) (let ((first (get-ch port)))
(when (eof-object? first) (when (eof-object? first)
(error "Unexpected end of input in character literal")) (error "Unexpected end of input in character literal"))
(when (> (char->integer first) 127)
(error "a char is one byte, and this is not: write its code point, or a string"
first))
(if (char-alphabetic? first) (if (char-alphabetic? first)
(let ((rest (read-atom-string port))) (let ((rest (read-atom-string port)))
(if (string=? rest "") (if (string=? rest "")
@@ -497,65 +328,22 @@
(cond (cond
((eof-object? c) (error "Unterminated string literal")) ((eof-object? c) (error "Unterminated string literal"))
((char=? c #\") (list->string (reverse chars))) ((char=? c #\") (list->string (reverse chars)))
((char=? c #\\) (let ((escaped (read-escape port))) ((char=? c #\\) (loop (cons (read-escape port) chars)))
(loop (if escaped (cons escaped chars) chars))))
(else (loop (cons c chars))))))) (else (loop (cons c chars)))))))
;;; C's escapes, each one character of the string, or #f for a backslash
;;; ending a line, which joins it to the next. A string is text, so \x
;;; and octal, bytes to C, reach only as far as ASCII: past it the
;;; character is written as itself or its \u.
;;;
;;; \x41 \101 A -> A \012 -> newline é -> é
(define (read-escape port) (define (read-escape port)
(let ((c (get-ch port))) (let ((c (get-ch port)))
(cond (cond
((eof-object? c) (error "Unterminated string literal")) ((eof-object? c) (error "Unterminated string literal"))
((assv c simple-escapes) => cdr) ((char=? c #\n) #\newline)
((char=? c #\newline) #f) ((char=? c #\t) #\tab)
((digit-in 8 c) => (lambda (d) (ascii (more-digits port 8 2 d)))) ((char=? c #\r) #\return)
((char=? c #\x) ((char=? c #\a) #\alarm)
(let ((d (digit-in 16 (peek port)))) ((char=? c #\b) #\backspace)
(unless d (error "\\x needs a hex digit")) ((char=? c #\f) (integer->char 12))
(get-ch port) ((char=? c #\v) (integer->char 11))
(ascii (more-digits port 16 #f d)))) ((char=? c #\0) #\nul)
((char=? c #\u) (code-point port 4)) (else c)))) ; \" \\ and anything else: literal
((char=? c #\U) (code-point port 8))
(else (error "unknown escape" (string #\\ c))))))
(define simple-escapes
(list (cons #\n #\newline) (cons #\t #\tab) (cons #\r #\return)
(cons #\a #\alarm) (cons #\b #\backspace)
(cons #\f (integer->char 12)) (cons #\v (integer->char 11))
(cons #\\ #\\) (cons #\" #\") (cons #\' #\') (cons #\? #\?)))
(define (digit-in radix c)
(and (char? c) (string->number (string c) radix)))
;;; N, with up to MOST more digits of RADIX read onto it; any number of
;;; them for MOST #f
(define (more-digits port radix most n)
(let loop ((n n) (left most))
(let ((d (and (or (not left) (> left 0)) (digit-in radix (peek port)))))
(if d
(begin (get-ch port) (loop (+ (* n radix) d) (and left (- left 1))))
n))))
(define (ascii n)
(if (> n 127)
(error "a byte past ASCII is not text; write the character or \\u, or a [u8 N] array for bytes")
(integer->char n)))
(define (code-point port digits)
(let loop ((n 0) (left digits))
(if (= left 0)
(if (or (<= #xD800 n #xDFFF) (> n #x10FFFF))
(error "no character has this code point")
(integer->char n))
(let ((d (digit-in 16 (peek port))))
(unless d (error "\\u takes four hex digits and \\U eight"))
(get-ch port)
(loop (+ (* n 16) d) (- left 1))))))
(define (skip-block-comment port depth) (define (skip-block-comment port depth)
(if (= depth 0) (if (= depth 0)
@@ -570,31 +358,21 @@
(else (skip-block-comment port depth)))))) (else (skip-block-comment port depth))))))
;;; Read every top-level form from `port'. Locations are recorded by ;;; Read every top-level form from `port'. Locations are recorded by
;;; next-token, for every form rather than only these. An error says ;;; next-token, for every form rather than only these
;;; where it was met, the way a later stage's says where its form was
;;; written: file:line: what
(define (parse-all port) (define (parse-all port)
(parameterize ((current-line 1)) (parameterize ((current-line 1))
(handle-exceptions e (let loop ((acc (list)))
(let ((message ((condition-property-accessor 'exn 'message #f) e))) (skip-whitespace port)
(if message (let ((tok (next-token port)))
(apply error (cond
(string-append (current-source-file) ":" ((eof-object? tok) (reverse acc))
(number->string (current-line)) ": " message) ((or (eq? tok close-paren)
((condition-property-accessor 'exn 'arguments (list)) e)) (eq? tok close-bracket))
(abort e))) (error "Unmatched closing bracket at top level"))
(let loop ((acc (list))) ((eq? tok dot-token)
(skip-whitespace port) (error "Unexpected . at top level"))
(let ((tok (next-token port))) (else
(cond (loop (cons tok acc))))))))
((eof-object? tok) (reverse acc))
((or (eq? tok close-paren)
(eq? tok close-bracket))
(error "Unmatched closing bracket at top level"))
((eq? tok dot-token)
(error "Unexpected . at top level"))
(else
(loop (cons tok acc)))))))))
;;; Entry point: read all forms from a file, or from the current input ;;; Entry point: read all forms from a file, or from the current input
;;; port when the source is 'stdin ;;; port when the source is 'stdin

2
semen.module.scm Normal file
View File

@@ -0,0 +1,2 @@
(module semen ()
"semen.scm")

1243
semen.scm

File diff suppressed because it is too large Load Diff

View File

@@ -212,24 +212,14 @@
(define (c-format-string x) (define (c-format-string x)
(lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st))) (lambda (st) ((cat #\" (apply-cat (c-string-escaped x)) #\") st)))
;; MODIFIED FROM UPSTREAM fmt-c: a `?' after a `?' is escaped, so no
;; two stand together for C to read a trigraph off -- under -std=c11
;; "??=" is "#", and "??/" before the closing quote is \", which
;; leaves the string open.
(define (c-string-escaped x) (define (c-string-escaped x)
(define (special? i)
(let ((c (string-ref x i)))
(or (c-needs-string-escape? c)
(and (eqv? c #\?) (> i 0) (eqv? (string-ref x (- i 1)) #\?)))))
(let loop ((parts '()) (idx (string-length x))) (let loop ((parts '()) (idx (string-length x)))
(cond ((let find ((i (- idx 1))) (cond ((string-index-right x c-needs-string-escape? 0 idx)
(cond ((< i 0) #f) ((special? i) i) (else (find (- i 1)))))
=> (lambda (special-idx) => (lambda (special-idx)
(let ((c (string-ref x special-idx))) (loop (cons (c-escape-char (string-ref x special-idx) #\")
(loop (cons (if (eqv? c #\?) "\\?" (c-escape-char c #\")) (cons (substring/shared x (+ special-idx 1) idx)
(cons (substring/shared x (+ special-idx 1) idx) parts))
parts)) special-idx)))
special-idx))))
(else (else
(cons (substring/shared x 0 idx) parts))))) (cons (substring/shared x 0 idx) parts)))))
@@ -304,7 +294,6 @@
((%prototype) ((apply c-prototype (cdr x)) st)) ((%prototype) ((apply c-prototype (cdr x)) st))
((%var) ((apply c-var (cdr x)) st)) ((%var) ((apply c-var (cdr x)) st))
((%begin) ((apply c-begin (cdr x)) st)) ((%begin) ((apply c-begin (cdr x)) st))
((%comma) ((apply c-comma (cdr x)) st))
((%attribute) ((apply c-attribute (cdr x)) st)) ((%attribute) ((apply c-attribute (cdr x)) st))
((%line) ((apply cpp-line (cdr x)) st)) ((%line) ((apply cpp-line (cdr x)) st))
((%pragma %error %warning) ((%pragma %error %warning)
@@ -322,7 +311,6 @@
((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st)) ((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st))
((%compound) ((apply c-compound (cdr x)) st)) ((%compound) ((apply c-compound (cdr x)) st))
((%designate) ((apply c-designate (cdr x)) st)) ((%designate) ((apply c-designate (cdr x)) st))
((%designate-index) ((apply c-designate-index (cdr x)) st))
((+ - & * / % ! ~ ^ && < > <= >= == != << >> ((+ - & * / % ! ~ ^ && < > <= >= == != << >>
= *= /= %= &= ^= >>= <<=) ; |\|| |\|\|| |\|=| = *= /= %= &= ^= >>= <<=) ; |\|| |\|\|| |\|=|
((apply c-op x) st)) ((apply c-op x) st))
@@ -620,33 +608,16 @@
(define (c-braced-block . args) (define (c-braced-block . args)
(apply c-braced-block/aux 0 args)) (apply c-braced-block/aux 0 args))
;; MODIFIED FROM UPSTREAM fmt-c: a block of nothing is `{}', where
;; c-begin had nothing to begin with and died on its arity.
(define (c-braced-block/aux offset header . body) (define (c-braced-block/aux offset header . body)
(lambda (st) (lambda (st)
((if (null? body) ((cat (if header header "") (c-open-brace st) (c-indent st offset)
(cat (if header (cat header " ") "") "{}") (apply c-begin body) fl
(cat (if header header "") (c-open-brace st) (c-indent st offset) (c-current-indent-string st offset) (c-close-brace st))
(apply c-begin body) fl
(c-current-indent-string st offset) (c-close-brace st)))
st))) st)))
(define (c-begin . args) (define (c-begin . args)
(apply c-begin/aux #f args)) (apply c-begin/aux #f args))
;; MODIFIED FROM UPSTREAM fmt-c, which has no comma operator: as a
;; statement, statements; as a value, the expressions in parens, since
;; bare they would be an initializer's next declarator or a call's next
;; argument -- except where a for header says it may stand bare.
(define (c-comma . exprs)
(lambda (st)
((if (fmt-expression? st)
(let ((joined (fmt-join (lambda (e) (c-with-op 'comma (c-expr e)))
exprs ", ")))
(if (eq? (fmt-op st) 'comma) joined (cat "(" joined ")")))
(apply c-begin exprs))
st)))
(define (c-begin/aux ret? body0 . body) (define (c-begin/aux ret? body0 . body)
(if (null? body) (if (null? body)
(c-expr body0) (c-expr body0)
@@ -693,13 +664,7 @@
"") "")
(if (not (null? body)) (if (not (null? body))
(cat body) (cat body)
"") ""))))))
(c-type-words o))))))
;; MODIFIED FROM UPSTREAM fmt-c: what follows the first star of a
;; tagged type, `* const' in (struct what * const), was dropped
(define (c-type-words words)
(fmt-join (lambda (word) (cat " " word)) words ""))
(define (c-struct . args) (apply c-struct/aux "struct" args)) (define (c-struct . args) (apply c-struct/aux "struct" args))
(define (c-union . args) (apply c-struct/aux "union" args)) (define (c-union . args) (apply c-struct/aux "union" args))
@@ -714,15 +679,13 @@
(if (pair? x) (cat (car x) " = " (c-expr (cadr x))) (dsp x))) (if (pair? x) (cat (car x) " = " (c-expr (cadr x))) (dsp x)))
(let* ((name (if (null? o) (if (or (symbol? x) (string? x)) x #f) x)) (let* ((name (if (null? o) (if (or (symbol? x) (string? x)) x #f) x))
(vals (if name (if (null? o) #f (car o)) x))) (vals (if name (if (null? o) #f (car o)) x)))
;; MODIFIED FROM UPSTREAM fmt-c: (enum mood * const) is a (if vals
;; pointer, and its star was taken for the list of values
(if (pair? vals)
(c-wrap-stmt (c-wrap-stmt
(cat (cat
(c-braced-block (c-braced-block
(if name (cat "enum " name) (dsp "enum")) (if name (cat "enum " name) (dsp "enum"))
(c-in-expr (apply c-begin (map c-enum-one vals)))))) (c-in-expr (apply c-begin (map c-enum-one vals))))))
(c-wrap-stmt (cat "enum " name (or vals "") (c-type-words (if vals (cdr o) '()))))))) (c-wrap-stmt (cat "enum " name)))))
(define (c-attribute . args) (define (c-attribute . args)
(cat "__attribute__ ((" (fmt-join c-expr args ", ") "))")) (cat "__attribute__ ((" (fmt-join c-expr args ", ") "))"))
@@ -738,24 +701,15 @@
(c-in-stmt (apply c-begin body))) (c-in-stmt (apply c-begin body)))
fl)))) fl))))
;; MODIFIED FROM UPSTREAM fmt-c: a header's first and last slots are
;; the one place a comma expression goes bare, so they say so. A slot
;; written () is empty, where c-expr would say NULL -- for (;;), not a
;; loop whose test is false. And a loop with no body has the empty
;; block.
(define (c-for init check update . body) (define (c-for init check update . body)
(define (slot x lead show) (c-reset-newline
(if (null? x) "" (cat lead (show (c-expr x))))) (cat
(define (bare e) (c-with-op 'comma e)) (c-block
(let ((header (c-in-expr (c-in-expr
(cat "for (" (slot init "" bare) ";" (cat "for (" (c-expr init) "; " (c-in-test (c-expr check)) "; "
(slot check " " c-in-test) ";" (c-expr update ) ")"))
(slot update " " bare) ")")))) (c-in-stmt (apply c-begin body)))
(c-reset-newline fl)))
(cat (if (null? body)
(c-braced-block header)
(c-block header (c-in-stmt (apply c-begin body))))
fl))))
(define (c-param x) (define (c-param x)
(cond (cond
@@ -784,20 +738,14 @@
(c-type 'void) (c-type 'void)
(c-in-expr (fmt-join/dot c-param (lambda (dot) (dsp "...")) ls ", ")))) (c-in-expr (fmt-join/dot c-param (lambda (dot) (dsp "...")) ls ", "))))
;; MODIFIED FROM UPSTREAM fmt-c: a function of no statements is `{}'
(define (c-fun type name params . body) (define (c-fun type name params . body)
(cat (if (null? body) (cat (c-block (c-in-expr (c-prototype type name params))
(c-braced-block (c-in-expr (c-prototype type name params))) (c-in-stmt (apply c-begin body)))
(c-block (c-in-expr (c-prototype type name params))
(c-in-stmt (apply c-begin body))))
fl)) fl))
;; MODIFIED FROM UPSTREAM fmt-c: the name and parameters are the
;; return type's declarator, so a function returning a function pointer
;; is int (*get (void))(int), not int (*)(int) get (void)
(define (c-prototype type name params . o) (define (c-prototype type name params . o)
(c-wrap-stmt (c-wrap-stmt
(cat (c-type type (cat (c-expr name) " (" (c-param-list params) ")")) (cat (c-type type) " " (c-expr name) " (" (c-param-list params) ")"
(fmt-join/prefix c-expr o " ")))) (fmt-join/prefix c-expr o " "))))
(define (c-static x) (cat "static " (c-expr x))) (define (c-static x) (cat "static " (c-expr x)))
@@ -815,14 +763,10 @@
(cond (cond
((pair? type) ((pair? type)
(case (car type) (case (car type)
;; MODIFIED FROM UPSTREAM fmt-c: the declarator goes round the
;; name, inside the return type's own, so a function type
;; returning one nests: void (*(*g)(int))()
((%fun) ((%fun)
(c-type (cadr type) (cat (c-type (cadr type) #f)
(cat "(*" (or name "") ")(" " (*" (or name "") ")("
(fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") ")"))
")")))
;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an ;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an
;; array parameter of a function type, where C has no room ;; array parameter of a function type, where C has no room
;; for a name -- arrives as #f, and upstream printed it ;; for a name -- arrives as #f, and upstream printed it
@@ -858,14 +802,10 @@
(cond (cond
((pair? type) ((pair? type)
(case (car type) (case (car type)
;; MODIFIED FROM UPSTREAM fmt-c: the declarator goes round the
;; name, inside the return type's own, so a function type
;; returning one nests: void (*(*g)(int))()
((%fun) ((%fun)
(c-type (cadr type) (cat (c-type (cadr type) #f)
(cat "(*" (or name "") ")(" " (*" (or name "") ")("
(fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") (fmt-join (lambda (x) (c-type x #f)) (caddr type) ", ") ")"))
")")))
;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an ;; MODIFIED FROM UPSTREAM fmt-c: a nameless declarator -- an
;; array parameter of a function type, where C has no room ;; array parameter of a function type, where C has no room
;; for a name -- arrives as #f, and upstream printed it ;; for a name -- arrives as #f, and upstream printed it
@@ -931,10 +871,6 @@
(define (c-designate field value) (define (c-designate field value)
(cat "." (c-expr field) " = " (c-expr value))) (cat "." (c-expr field) " = " (c-expr value)))
;; MODIFIED FROM UPSTREAM fmt-c, which designates fields only
(define (c-designate-index index value)
(cat "[" (c-expr index) "] = " (c-expr value)))
(define (c-typedef type alias . o) (define (c-typedef type alias . o)
(c-wrap-stmt (c-wrap-stmt
(cat "typedef " (c-type type alias) (fmt-join/prefix c-expr o " ")))) (cat "typedef " (c-type type alias) (fmt-join/prefix c-expr o " "))))
@@ -1131,16 +1067,10 @@
;; Parenthesises the whole expression rather than the operand: the ;; Parenthesises the whole expression rather than the operand: the
;; other way round, `(. (* p) x)' came out `*(p).x', which C reads as ;; other way round, `(. (* p) x)' came out `*(p).x', which C reads as
;; `*(p.x)'. ;; `*(p.x)'.
;; MODIFIED FROM UPSTREAM fmt-c: a negative literal is one token in
;; Sex and two in C, so (- -1) is -(-1), not the decrement --1.
(define (c-unary-op op x) (define (c-unary-op op x)
(c-wrap-stmt (c-wrap-stmt
(c-maybe-paren (unary-operator op) (c-maybe-paren (unary-operator op)
(cat (display-to-string op) (cat (display-to-string op) (c-expr x)))))
(if (and (number? x)
(char=? #\- (string-ref (number->string x) 0)))
(c-paren x)
(c-expr x))))))
;; some convenience definitions ;; some convenience definitions

9
sex-macros.module.scm Normal file
View File

@@ -0,0 +1,9 @@
(module sex-macros
(register-macro
cat
comment
get-macro
macro?
apply-macro
defmacro)
"sex-macros.scm")

View File

@@ -2,21 +2,8 @@
scheme scheme
(only fmt fmt) (only fmt fmt)
(chicken base) (chicken base)
(chicken condition)
(chicken irregex)
(chicken module)
(chicken plist) (chicken plist)
(chicken string) (chicken string))
utils)
(export
cat
comment
macro?
apply-macro
defmacro
macro-definition
restore-macro!)
(define (cat-syms s-1 s-2) (define (cat-syms s-1 s-2)
(fmt #f s-1 s-2)) (fmt #f s-1 s-2))
@@ -46,7 +33,10 @@
get-underlying-type type-match type-pattern-matches? get-underlying-type type-match type-pattern-matches?
map-fields map-fields
get-name-type get-return-type type-of get-name-type get-return-type type-of
get-method)) ;; what a generic asks before it expands:
;; (realizes? 'ord type) beats a wall of C
;; errors two stages downstream
realizes? get-method))
,@body))) ,@body)))
(define (get-macro name) (define (get-macro name)
@@ -57,47 +47,11 @@
(symbol? (car form)) (symbol? (car form))
(get (car form) 'sex-macro))) (get (car form) 'sex-macro)))
;;; CHICKEN would report a wrong argument count about a procedure with
;;; no name, and an error raised in a macro's body without the call: both
;;; are told here, where the call is known
(define (apply-macro form) (define (apply-macro form)
(assert (macro? form) (assert (macro? form)
(fmt #f (car form) " is not a macro")) (fmt #f (car form) " is not a macro"))
(let ((name (car form))) (apply (get-macro (car form))
(check-macro-arity form name (cadr (get name 'sex-macro)) (length (cdr form))) (cdr form)))
(handle-exceptions e
(let ((message ((condition-property-accessor 'exn 'message #f) e)))
;; one raised about a form of its own already says where
(if (and message (not (irregex-search "^[^ ]+:[0-9]+: " message)))
(apply sex-error form
(string-append "expanding " (symbol->string name)
": " message)
((condition-property-accessor 'exn 'arguments (list)) e))
(abort e)))
(apply (get-macro name) (cdr form)))))
;;; (defmacro (one x) ...) takes one; (defmacro (many x . more) ...) one
;;; or more
(define (check-macro-arity form name arglist given)
(let count ((args arglist) (required 0))
(cond ((pair? args) (count (cdr args) (+ required 1)))
((null? args)
(unless (= given required)
(sex-error form "macro takes this many arguments" name required)))
((< given required)
(sex-error form "macro takes at least this many arguments"
name required)))))
;;; What a name is defined as a macro to, or #f; and putting that back,
;;; for a macro lent for a while -- a module's, while its interface is
;;; read
(define (macro-definition name)
(get name 'sex-macro))
(define (restore-macro! name definition)
(if definition
(put! name 'sex-macro definition)
(remprop! name 'sex-macro)))
(define (defmacro form) (define (defmacro form)
(let ((arglist (car form)) (let ((arglist (car form))

View File

@@ -1,40 +1,8 @@
;;; sex-mode.el --- Major mode for Sex code -*- lexical-binding: t -*-
;; Copyright (C) 2025-2026 alex-eg
;; Author: alex-eg <alexey.e.egorov@gmail.com>
;; Version: 0.1.0
;; Package-Requires: ((emacs "28.1"))
;; Keywords: languages
;; URL: https://git.kotobank.ch/alex-eg/sex
;; This file is not part of GNU Emacs.
;;; Commentary:
;; Major mode for Sex, a compiled language with S-expression syntax.
;; The mode derives from `lisp-data-mode' and fontifies Sex
;; declarations and keywords.
;;
;; `sex-mode' is one file in the Sex repository. Quelpa installs it
;; from that git remote:
;;
;; (use-package sex-mode
;; :ensure nil
;; :quelpa
;; (sex-mode :fetcher git
;; :url "https://git.kotobank.ch/alex-eg/sex.git"
;; :files ("sex-mode.el")
;; :upgrade t))
;;
;; Visiting a .sex file turns the mode on.
;;; Code:
(require 'scheme) (require 'scheme)
(defgroup sex-mode nil (defgroup sex-mode nil
"Major mode for Sex code." "Major mode for Sex code."
:prefix "sex-" :prefix 'sex-
:group 'languages) :group 'languages)
(define-abbrev-table 'sex-mode-abbrev-table () (define-abbrev-table 'sex-mode-abbrev-table ()
@@ -43,8 +11,8 @@ It has `scheme-mode-abbrev-table' as its parent."
:parents (list scheme-mode-abbrev-table)) :parents (list scheme-mode-abbrev-table))
(defvar sex-mode-syntax-table (defvar sex-mode-syntax-table
(make-syntax-table lisp-data-mode-syntax-table) (let ((table (make-syntax-table lisp-data-mode-syntax-table)))
"Syntax table used in Sex mode.") table))
(defvar sex-mode-map (defvar sex-mode-map
(let ((map (make-sparse-keymap))) (let ((map (make-sparse-keymap)))
@@ -53,72 +21,58 @@ It has `scheme-mode-abbrev-table' as its parent."
"Keymap for Sex mode. "Keymap for Sex mode.
All commands in `lisp-mode-shared-map' are inherited by this map.") All commands in `lisp-mode-shared-map' are inherited by this map.")
(defvar sex-mode-line-process "" (defvar sex-mode-line-process "")
"Mode-line process string for Sex mode.")
(defconst sex-font-lock-keywords (defconst sex-font-lock-keywords
(eval-when-compile (eval-when-compile
(list (list
;; Declarations. `pub' and `extern' are optional prefixes, so ;; Declarations
;; `(pub fn main' highlights both keywords and the name.
(list (concat "(" (list (concat "("
"\\(?:\\(pub\\|extern\\)[[:space:]]+\\)?" (regexp-opt '("chicken-define"
(regexp-opt '("define" "chicken-define-syntax"
"chicken-import"
"chicken-load"
"define"
"defmacro" "defmacro"
"enum" "extern"
"fn"
"import" "import"
"include" "include"
"fn"
"ops" "ops"
"pub"
"record" "record"
"realize"
"spec"
"struct" "struct"
"sum" "sum"
"typedef" "var"
"union" "union")
"var") 'word)
'words) "\\>"
"[[:space:]]*" "[[:space:]]*"
"\\([[:word:]]*\\)") "\\([[:word:]]*\\)")
'(1 font-lock-keyword-face nil t) '(1 font-lock-keyword-face)
'(2 font-lock-keyword-face) '(2 font-lock-function-name-face))
'(3 font-lock-function-name-face nil t)) ;; Keywords
;; Statement and expression heads, plus the macro-language forms
;; that appear in `defmacro' bodies.
(list (concat "(" (list (concat "("
(regexp-opt '("break" (regexp-opt '(
"c-bit-or" "do"
"c-bit-or="
"c-or"
"case" "case"
"case/fallthrough"
"cast"
"continue"
"default" "default"
"do" "do"
"else"
"for"
"get-method"
"goto"
"if" "if"
"lambda" "for"
"map-fields" "goto"
"match" "match"
"return" "return"
"sizeof"
"static-assert"
"switch" "switch"
"type-match" "var"
"type-of" "while")
"while" 'word)
"$" "\\>")
"." '(1 'font-lock-builtin-face)))))
":")
'words))
'(1 font-lock-builtin-face))))
"Font-lock keywords for Sex mode.")
(defun sex-mode-set-variables () (defun sex-mode-set-variables ()
"Set up buffer-local variables for Sex mode."
(set-syntax-table sex-mode-syntax-table) (set-syntax-table sex-mode-syntax-table)
(setq local-abbrev-table sex-mode-abbrev-table) (setq local-abbrev-table sex-mode-abbrev-table)
(setq mode-line-process '("" sex-mode-line-process)) (setq mode-line-process '("" sex-mode-line-process))
@@ -135,6 +89,8 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
(put 'defmacro 'lisp-indent-function 'defun) (put 'defmacro 'lisp-indent-function 'defun)
(put 'record 'lisp-indent-function 'defun) (put 'record 'lisp-indent-function 'defun)
(put 'sum '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 'ops 'lisp-indent-function 'defun)
(put 'match 'lisp-indent-function 1) (put 'match 'lisp-indent-function 1)
(put 'struct 'lisp-indent-function 'defun) (put 'struct 'lisp-indent-function 'defun)
@@ -157,8 +113,6 @@ Blank lines separate paragraphs. Semicolons start comments.
(sex-mode-set-variables)) (sex-mode-set-variables))
;;;###autoload ;;;###autoload
(add-to-list 'auto-mode-alist '("\\.sex\\'" . sex-mode)) (add-to-list 'auto-mode-alist '("\\.\\(sex\\|hsex\\)\\'" . sex-mode))
(provide 'sex-mode) (provide 'sex-mode)
;;; sex-mode.el ends here

7
sex-modules.module.scm Normal file
View File

@@ -0,0 +1,7 @@
(module sex-modules
(get-modules-public-forms
load-persistent-module-paths
check-public-interface
module-dependencies
read-public-interface)
"sex-modules.scm")

View File

@@ -1,71 +1,48 @@
(import (import
scheme scheme
brev-separate
(chicken base) (chicken base)
(chicken condition)
(chicken file) (chicken file)
(chicken load) (chicken load)
(chicken module)
(chicken pathname) (chicken pathname)
(chicken process-context) (chicken process-context)
(chicken string) (chicken string)
fmt
matchable matchable
reader reader
sex-macros
srfi-1 srfi-1
types types
utils) utils)
(export
get-modules-public-forms
mark-imported!
load-persistent-module-paths
check-public-interface
module-dependencies
read-public-interface)
(define +persistent-module-paths+ (list)) (define +persistent-module-paths+ (list))
;;; for guarding against multiple imports (sort of mandatory #pragma ;;; for guarding against multiple imports (sort of mandatory #pragma
;;; once) ;;; once)
(define +imported-modules+ (list)) (define +imported-modules+ (list))
;;; The unit is one of its own imports from the start: two modules that (define (get-modules-public-forms module-list)
;;; import each other with pub hand it its own interface back otherwise, ;; Module list is a list of symbols
;;; and its types are defined twice
(define (mark-imported! path)
(set! +imported-modules+ (cons (normalize-pathname path) +imported-modules+)))
(define (get-modules-public-forms import-form)
;; How Sex handles modules: ;; How Sex handles modules:
;; For each module IMPORT-FORM names, construct path, find module by ;; For each module in a list, construct path, find module by path in
;; path in module path directories, extract public definitions from ;; module path directories, extract public definitions from the
;; the module, paste them in current one in emulation of C include ;; module, paste them in current one in emulation of C include
;; directives. ;; directives.
(append-map (lambda (name) (import-module (symbol->string name) import-form)) (fold-right append (list)
(cdr (strip-pub import-form)))) (map (fn (import-module (symbol->string x)))
module-list)))
(define (import-module name form) (define (import-module name)
(let* ((directory (import-directory form)) (let ((module-path (locate-module name)))
(module-path (locate-module name directory))) (assert module-path (fmt #f "Failed to find module " name " in "
(unless module-path (get-module-paths)))
(sex-error form "Failed to find module" name (get-module-paths directory))) (if (member module-path +imported-modules+)
(if (member (normalize-pathname module-path) +imported-modules+)
(list) (list)
(begin (begin
(set! +imported-modules+ (cons (normalize-pathname module-path) (set! +imported-modules+ (cons module-path +imported-modules+))
+imported-modules+))
(read-public-interface module-path))))) (read-public-interface module-path)))))
;;; An import is looked for beside the file it is written in, so a (define (get-module-paths)
;;; module's imports are its neighbours wherever the unit importing it (cons (current-directory)
;;; is. One with no file to be beside -- stdin's, a macro's -- is looked
;;; for from the working directory, which is the unit's
(define (import-directory form)
(let ((file (form-file form)))
(or (and file (pathname-directory file)) (current-directory))))
(define (get-module-paths #!optional (directory (current-directory)))
(cons directory
(append +persistent-module-paths+ (standard-library-paths)))) (append +persistent-module-paths+ (standard-library-paths))))
;;; Where the modules shipped with the compiler live. Asked of the ;;; Where the modules shipped with the compiler live. Asked of the
@@ -81,12 +58,12 @@
(make-pathname (list (pathname-directory bin) "share") "sex"))) (make-pathname (list (pathname-directory bin) "share") "sex")))
(list)))) (list))))
(define (locate-module name directory) (define (locate-module name)
;; Module locations: relative to DIRECTORY, or in what was in ;; Module locations: relative to file being compiled, or in what was
;; SEX_MODULE_PATH env var at the start of the process (see ;; in SEX_MODULE_PATH env var at the start of the process (see
;; load-persistent-module-paths function) ;; load-persistent-module-paths function)
(let ((search-paths (get-module-paths directory))) (let ((search-paths (get-module-paths)))
(let loop ((paths search-paths)) (let loop ((paths search-paths))
(if (null? paths) (if (null? paths)
#f #f
@@ -120,133 +97,12 @@
;; pub fn taking it has to paste them that way round, or the prototype ;; pub fn taking it has to paste them that way round, or the prototype
;; names a type C has not seen. The declarations of the types its ;; names a type C has not seen. The declarations of the types its
;; importers see only behind a pointer go first. ;; importers see only behind a pointer go first.
(let ((forms (module-forms (read-module module-path)))) (let ((raw-forms (read-module module-path)))
(append (check-public-interface forms) (append (check-public-interface raw-forms)
(interface-forms forms)))) (interface-forms raw-forms))))
;;; A module's forms with its toplevel macro calls expanded, so that the
;;; pub forms a macro writes reach importers as written ones do:
;;; (getter forty-two 42) gives them (pub fn forty-two () int). The
;;; macros are the module's own and those its imports give it, lent for
;;; the expanding and taken back after, so the importer is left with the
;;; pub ones alone. One that reads the type database sees what the
;;; importer knows, which no declaration of the module's is yet; a call
;;; that fails after asking for one -- (field-count box), box being the
;;; module's record -- gives importers nothing, as before, and is the
;;; module's own compile's to check. Any other failure is the importer's
;;; too: (boom) raising "nope" says so wherever it is read
(define +modules-expanded+ (list))
(define (module-forms raw-forms)
(cond ((assq raw-forms +modules-expanded+) => cdr)
(else (let ((forms (expanded raw-forms)))
(set! +modules-expanded+
(cons (cons raw-forms forms) +modules-expanded+))
forms))))
(define (expanded raw-forms)
(let ((lent (list))
(declared (declared-names raw-forms)))
(define (lend! form)
(let ((name (macro-name form)))
(unless (assq name lent)
(set! lent (cons (cons name (macro-definition name)) lent)))
(defmacro (if (pub-form? form) (cddr form) (cdr form)))))
(define (expand form)
(cond ((macro-name form) (lend! form) (list form))
((splice? form) (append-map expand (cdr form)))
((macro? form)
(let ((result (expand-call form declared)))
(cond ((or (not result) (null? result)) (list))
(else (stamp-form-source! result (form-source form))
(expand result)))))
(else (list form))))
(dynamic-wind
void
(lambda ()
(for-each lend! (imported-macro-forms raw-forms))
(append-map expand raw-forms))
(lambda ()
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry)))
lent)))))
(define (expand-call form declared)
(let ((unknown (list)))
(handle-exceptions exn
(if (any (lambda (name) (memq name declared)) unknown) #f (abort exn))
(parameterize ((unknown-name (lambda (name) (set! unknown (cons name unknown)))))
(apply-macro form)))))
;;; The names FORMS declare, types and all
(define (declared-names forms)
(append (map car (declared-types forms))
(filter-map (lambda (form)
(match form
((or ('pub (or 'fn 'var) (? symbol? name) . _)
((or 'fn 'var) (? symbol? name) . _))
name)
(_ #f)))
forms)))
(define (splice? form)
(and (pair? form) (eq? (car form) '$) (list? form)))
;;; The macros importing FORMS' modules gives: each one's pub macros and
;;; their helpers, and those of the modules it imports with pub
(define (imported-macro-forms forms)
(let next ((paths (append (imported-modules forms #t)
(imported-modules forms #f)))
(seen (list))
(acc (list)))
(cond ((null? paths) (concatenate (reverse acc)))
((member (car paths) seen) (next (cdr paths) seen acc))
(else
(let* ((raw (read-module (car paths)))
(helpers (helper-macros raw)))
(next (append (cdr paths) (imported-modules raw #t))
(cons (car paths) seen)
(cons (filter (lambda (form)
(and (macro-name form)
(or (pub-form? form) (memq form helpers))))
raw)
acc)))))))
(define (macro-name form)
(match form
(('defmacro (name . _) . _) name)
(('pub 'defmacro (name . _) . _) name)
(_ #f)))
(define (interface-forms raw-forms) (define (interface-forms raw-forms)
(let ((helpers (helper-macros raw-forms))) (reverse (fold process-public-interface-form (list) raw-forms)))
(reverse (fold (lambda (form acc)
(if (memq form helpers)
(cons form acc)
(process-public-interface-form form acc)))
(list)
raw-forms))))
;;; The private macros a pub one expands into, and the ones those do:
;;; the importer expands them all, the way a C header that defines a
;;; macro has to define what it uses too
(define (helper-macros raw-forms)
(let* ((private (filter (lambda (form)
(and (macro-name form) (not (pub-form? form))))
raw-forms))
(mentions (lambda (form name)
(let walk ((x (cdr form)))
(or (eq? x name) (and (pair? x) (or (walk (car x)) (walk (cdr x)))))))))
(let grow ((needed (list))
(users (filter (lambda (form) (and (macro-name form) (pub-form? form)))
raw-forms)))
(let ((more (filter (lambda (form)
(and (not (memq form needed))
(any (lambda (user) (mentions user (macro-name form)))
users)))
private)))
(if (null? more)
needed
(grow (append needed more) more))))))
;;; What importers can see of a module's types ;;; What importers can see of a module's types
;;; ;;;
@@ -269,7 +125,6 @@
(reverse (reverse
(fold (fold
(lambda (form acc) (lambda (form acc)
(check-written-out form)
(fold (lambda (use acc) (check-type-use form use visible hidden acc)) (fold (lambda (use acc) (check-type-use form use visible hidden acc))
acc acc
(append-map (lambda (type) (type-uses type #f)) (append-map (lambda (type) (type-uses type #f))
@@ -277,20 +132,6 @@
(list) (list)
forms)))) forms))))
;;; Importers declare a pub var from its type, not its initializer, so
;;; there is nothing on their side to solve a `_' with
(define (check-written-out form)
(match form
(('pub 'var . _)
(match (strip-header-comments form 4)
(('pub 'var name type . _)
(when (let wildcard? ((t type))
(or (eq? t '_) (and (pair? t) (any wildcard? t))))
(sex-error form "a pub var's type is what importers declare it with; write it out"
name)))
(_ #f)))
(_ #f)))
;;; USE is (name . behind-a-pointer?) ;;; USE is (name . behind-a-pointer?)
(define (check-type-use form use visible hidden acc) (define (check-type-use form use visible hidden acc)
(let* ((name (car use)) (let* ((name (car use))
@@ -339,13 +180,16 @@
(('pub 'define name . body) body) (('pub 'define name . body) body)
(('pub (or 'record 'struct 'union) name . rest) (('pub (or 'record 'struct 'union) name . rest)
(field-types (find list? (remove comment-form? rest)))) (field-types (find list? (remove comment-form? rest))))
((or ('pub 'sum name (variants ...)) (('pub 'sum name (variants ...))
('pub 'sum name (? string?) (variants ...)))
(append-map (lambda (v) (append-map (lambda (v)
(if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list))) (if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list)))
(remove comment-form? variants))) (remove comment-form? variants)))
(('ops type . methods) (('ops type . methods)
(append-map interface-types (filter pub-form? methods))) (append-map interface-types
(filter (lambda (m) (and (pair? m) (eq? (car m) 'pub))) methods)))
(('pub 'realize spec . methods)
(append-map (lambda (m) (interface-types (cons 'pub m)))
(remove comment-form? methods)))
(_ (list)))) (_ (list))))
(define (field-types fields) (define (field-types fields)
@@ -358,10 +202,7 @@
;;; ;;;
;;; (* const cell) -> ((const . #t) (cell . #t)) ;;; (* const cell) -> ((const . #t) (cell . #t))
;;; [cell 4] -> ((cell . #f)) ;;; [cell 4] -> ((cell . #f))
;;; (fn ((cell)) int) -> ((cell . #f) (int . #f)) ;;; (fn ((cell)) int) -> ((cell . #t) (int . #t)) ; declaring is enough
;;;
;;; A function type takes and returns by value whatever it is held
;;; through: C wants the body to define or call one of its functions.
(define (type-uses type behind?) (define (type-uses type behind?)
(cond (cond
((symbol? type) (list (cons type behind?))) ((symbol? type) (list (cons type behind?)))
@@ -371,10 +212,10 @@
((*) (append-map (lambda (t) (type-uses t #t)) (cdr type))) ((*) (append-map (lambda (t) (type-uses t #t)) (cdr type)))
((¤) (let ((element (array-element-type type))) ((¤) (let ((element (array-element-type type)))
(append (if element (type-uses element behind?) (list)) (append (if element (type-uses element behind?) (list))
(if (array-bound? type) (bound-uses (array-bound type)) (list))))) (if (array-bound? type) (bound-uses (last type)) (list)))))
((fn) ((fn closure)
(if (and (pair? (cdr type)) (list? (second type))) (if (and (pair? (cdr type)) (list? (second type)))
(append-map (lambda (t) (type-uses t #f)) (append-map (lambda (t) (type-uses t #t))
(signature-types (second type) (last type))) (signature-types (second type) (last type)))
(list))) (list)))
((struct union enum) ((struct union enum)
@@ -400,16 +241,14 @@
(and (pair? form) (and (pair? form)
(let* ((core (strip-pub form)) (let* ((core (strip-pub form))
(name (and (pair? core) (pair? (cdr core)) (name (and (pair? core) (pair? (cdr core))
(if (and (eq? (car core) 'define) (if (and (eq? (car core) 'define) (pair? (second core)))
(pair? (second core)))
(car (second core)) (car (second core))
(second core))))) (second core)))))
(and (memq (car core) (and (memq (car core) '(record struct union enum sum typedef define))
'(record struct union enum sum typedef define))
(symbol? name) (symbol? name)
(list name (list name
(car core) (car core)
(or (memq (car core) '(typedef define spec)) (or (memq (car core) '(typedef define))
(any list? (remove comment-form? (cddr core))))))))) (any list? (remove comment-form? (cddr core)))))))))
forms)) forms))
@@ -430,44 +269,28 @@
(map (lambda (entry) (append entry (list #t))) (map (lambda (entry) (append entry (list #t)))
(append-map exported-types (imported-modules forms #f))))) (append-map exported-types (imported-modules forms #f)))))
;;; The files of the modules FORMS import, with pub or without ;;; The names of the modules FORMS import, with pub or without
(define (imported-modules forms pub?) (define (imported-modules forms pub?)
(append-map (lambda (form) (append-map (lambda (form)
(match form (match form
(('pub 'import . modules) (if pub? (located form modules) (list))) (('pub 'import . modules) (if pub? modules (list)))
(('import . modules) (if pub? (list) (located form modules))) (('import . modules) (if pub? (list) modules))
(_ (list)))) (_ (list))))
forms)) forms))
(define (located form modules)
(let ((directory (import-directory form)))
(filter-map (lambda (name) (locate-module (symbol->string name) directory))
modules)))
;;; The types a module gives its importers, its pub imports' included. ;;; The types a module gives its importers, its pub imports' included.
;;; Two modules may import each other, so each is read once ;;; Two modules may import each other, so each is read once
(define (exported-types path) (define (exported-types module)
(let next ((paths (list path)) (seen (list)) (acc (list))) (let next ((modules (list module)) (seen (list)) (acc (list)))
(cond ((null? paths) (concatenate (reverse acc))) (if (null? modules)
((member (car paths) seen) (next (cdr paths) seen acc)) (concatenate (reverse acc))
(else (let ((path (locate-module (symbol->string (car modules)))))
(let ((exports (module-exports (car paths)))) (if (or (not path) (member path seen))
(next (append (cdr paths) (cdr exports)) (next (cdr modules) seen acc)
(cons (car paths) seen) (let ((forms (interface-forms (read-module path))))
(cons (car exports) acc))))))) (next (append (cdr modules) (imported-modules forms #f))
(cons path seen)
;;; The types the module at PATH declares to its importers, and the (cons (declared-types forms) acc))))))))
;;; modules its interface imports; worked out once, though the check of
;;; every module above it on a pub import chain walks there
(define +module-exports+ (list))
(define (module-exports path)
(cond ((assoc path +module-exports+) => cdr)
(else (let* ((forms (interface-forms (module-forms (read-module path))))
(exports (cons (declared-types forms)
(imported-modules forms #f))))
(set! +module-exports+ (cons (cons path exports) +module-exports+))
exports))))
(define (public-fn-interface raw-form) (define (public-fn-interface raw-form)
;; (pub fn name args ret . body) -> prototype, keeping a docstring so ;; (pub fn name args ret . body) -> prototype, keeping a docstring so
@@ -499,6 +322,19 @@
(copy-form-source! form (copy-form-source! form
`(ops ,type ,@(map public-fn-interface methods)))))) `(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 ;;; TODO: use semen facilities to analyze modules
(define (process-public-interface-form form acc) (define (process-public-interface-form form acc)
(match form (match form
@@ -509,11 +345,13 @@
(('pub 'var . _) (('pub 'var . _)
(match-let ((('pub 'var name type . _) (strip-header-comments form 4))) (match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
(cons (copy-form-source! form `(extern var ,name ,type)) acc))) (cons (copy-form-source! form `(extern var ,name ,type)) acc)))
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _) (('pub (or 'define 'defmacro 'enum 'import 'include 'record 'spec 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc)) (cons (copy-form-source! form (cdr form)) acc))
(('ops . _) (('ops . _)
(let ((exported (ops-public-interface form))) (let ((exported (ops-public-interface form)))
(if exported (cons exported acc) acc))) (if exported (cons exported acc) acc)))
(('pub 'realize . _)
(cons (realize-public-interface form) acc))
(('pub . _) (('pub . _)
(sex-error form "pub must be followed by a definition" form)) (sex-error form "pub must be followed by a definition" form))
(_ acc))) (_ acc)))

1
sexc.module.scm Normal file
View File

@@ -0,0 +1 @@
(module sexc (main) "sexc.scm")

134
sexc.scm
View File

@@ -4,8 +4,6 @@
(chicken base) (chicken base)
(chicken condition) ; handle-exceptions (chicken condition) ; handle-exceptions
(chicken file) (chicken file)
(chicken module)
(only (chicken pathname) normalize-pathname)
(chicken plist) (chicken plist)
(chicken pretty-print) (chicken pretty-print)
(chicken process) (chicken process)
@@ -22,9 +20,6 @@
srfi-1 ; list routines srfi-1 ; list routines
utils) utils)
(export
main)
;;; Main function facilities ;;; Main function facilities
(define opts-grammar (define opts-grammar
@@ -64,8 +59,8 @@
(value #f) (value #f)
(single-char #\m)) (single-char #\m))
(output ,(fmt #f "Write output to file. Default file name is a.out." nl (output ,(fmt #f "Write output to file. Default file name is a.out." nl
(pad padding) "With -C, -m or --public-interface, defaults to stdout," nl (pad padding) "If -C or -m options are provided, defaults to stdout;" nl
(pad padding) "which `-' names too") (pad padding) "`-' is stdout too")
(required #f) (required #f)
(value #t) (value #t)
(single-char #\o)) (single-char #\o))
@@ -122,12 +117,6 @@
(loop (cddr as) (cons "--output=-" acc))) (loop (cddr as) (cons "--output=-" acc)))
(else (loop (cdr as) (cons (car as) acc)))))) (else (loop (cdr as) (cons (car as) acc))))))
;;; ...and a lone `-' left after that is the input, which is stdin: one
;;; getopt-long would read as an option it did not know, so it is taken
;;; out before
(define (stdin-dash? argv)
(and (member "-" argv) #t))
(define (get-rest-args args) (define (get-rest-args args)
(cdr (assoc '@ args))) (cdr (assoc '@ args)))
@@ -147,39 +136,20 @@
(map string->symbol (string-split (cdr entry) ","))) (map string->symbol (string-split (cdr entry) ",")))
(filter (lambda (entry) (eq? (car entry) 'features)) args))) (filter (lambda (entry) (eq? (car entry) 'features)) args)))
(define (get-input-file args dash?) (define (get-input-file args)
(let ((inputs (append (if dash? (list "-") (list)) (get-rest-args args)))) (let ((rest-args (get-rest-args args)))
(cond ((null? inputs) 'stdin) (if (null? rest-args)
;; any after the first were never read, and nothing said so 'stdin
((pair? (cdr inputs)) (car rest-args))))
(apply error "sexc compiles one input file at a time; given" inputs))
(dash? 'stdin)
(else (car inputs)))))
;;; Whether OUTPUT is the file INPUT, spelled however it is
(define (same-file? input output)
(and (string? input) (string? output) (not (stdout-output? output))
(equal? (normalize-pathname (to-absolute-pathname input))
(normalize-pathname (to-absolute-pathname output)))))
(define (stdout-output? output) (define (stdout-output? output)
(or (eq? output 'default) (equal? output "-"))) (or (eq? output 'default) (equal? output "-")))
;;; Whether ARGS ask for text, which `-o -' can send to stdout. An
;;; executable or an object goes to cc's -o, where `-' is a file name
(define (text-output? args)
(any (lambda (option) (get-arg args option #f))
'(emit-c macro-expand public-interface)))
(define (write-to-file-or-stdout output what) (define (write-to-file-or-stdout output what)
(if (stdout-output? output) (if (stdout-output? output)
(what) (what)
;; a failure part way through leaves none of the file, which make (with-output-to-file output
;; would take for done (fn (what)))))
(handle-exceptions exn
(begin (delete-file* output) (abort exn))
(with-output-to-file output
(fn (what))))))
(define (emit-c-or-sex sex-forms output args) (define (emit-c-or-sex sex-forms output args)
(write-to-file-or-stdout output (write-to-file-or-stdout output
@@ -213,11 +183,9 @@
(define (compile-to-file sex-forms output args cc-args) (define (compile-to-file sex-forms output args cc-args)
"Hand the generated C to the C compiler. Returns the compiler's exit "Hand the generated C to the C compiler. Returns the compiler's exit
status, which is ours to pass on." status, which is ours to pass on."
;; named with its own options, as make's CC is: "ccache cc", "cc -O2" (let ((compiler (or (get-arg args 'c-compiler #f)
(let ((compiler (let ((words (string-split (or (get-arg args 'c-compiler #f) (get-env-var "SEX_CC")
(get-env-var "SEX_CC") "cc"))
"cc"))))
(if (null? words) (list "cc") words)))
(out-file (if (eq? output 'default) (out-file (if (eq? output 'default)
"a.out" "a.out"
output)) output))
@@ -231,14 +199,12 @@ status, which is ours to pass on."
(begin (delete-file* c-file) (abort exn)) (begin (delete-file* c-file) (abort exn))
(with-output-to-file c-file (with-output-to-file c-file
(lambda () (emit-c sex-forms))) (lambda () (emit-c sex-forms)))
(let ((proc (process (car compiler) (let ((proc (process compiler (append (list "-o" out-file)
(append (cdr compiler) (if (get-arg args 'compile-object #f)
(list "-o" out-file) (list "-c")
(if (get-arg args 'compile-object #f) (list))
(list "-c") (list c-file)
(list)) cc-args))))
(list c-file)
cc-args))))
(call-with-values (lambda () (process-wait proc)) (call-with-values (lambda () (process-wait proc))
(lambda (pid normal-exit? status) (lambda (pid normal-exit? status)
(delete-file* c-file) (delete-file* c-file)
@@ -247,8 +213,6 @@ status, which is ours to pass on."
;;; The unit's own forms are checked for what its importers will need, ;;; The unit's own forms are checked for what its importers will need,
;;; the prelude's not: every unit has those ;;; the prelude's not: every unit has those
(define (semantic-process-forms unit-forms input-source) (define (semantic-process-forms unit-forms input-source)
(when (string? input-source)
(mark-imported! (to-absolute-pathname input-source)))
(let ((process (lambda () (let ((process (lambda ()
(check-public-interface unit-forms) (check-public-interface unit-forms)
(semen-process (append prelude unit-forms))))) (semen-process (append prelude unit-forms)))))
@@ -257,61 +221,39 @@ status, which is ours to pass on."
(with-directory input-source (process))))) (with-directory input-source (process)))))
(define prelude (define prelude
'((include inttypes.h) (append
(include stdbool.h) '((include inttypes.h)
(include stddef.h) (include stdbool.h)
(typedef u8 uint8-t) (include stddef.h) ; max_align_t, for closure environments
(typedef i8 int8-t) (typedef u8 uint8-t)
(typedef u16 uint16-t) (typedef i8 int8-t)
(typedef i16 int16-t) (typedef u16 uint16-t)
(typedef u32 uint32-t) (typedef i16 int16-t)
(typedef i32 int32-t) (typedef u32 uint32-t)
(typedef u64 uint64-t) (typedef i32 int32-t)
(typedef i64 int64-t))) (typedef u64 uint64-t)
(typedef i64 int64-t))
;; The closure environment is the part of the ABI, so include it in
;; every module
(list (closure-env-declaration))))
;;; An error is told by its message, file:line first where it has one.
;;; CHICKEN's call history after it is for working on sexc itself, and
;;; SEXC_DEBUG asks for it
(define (main) (define (main)
(if (get-environment-variable "SEXC_DEBUG")
(run)
(handle-exceptions exn
(let ((message ((condition-property-accessor 'exn 'message #f) exn))
(port (current-error-port)))
(unless message (abort exn))
(display "Error: " port)
(display message port)
(let ((arguments
((condition-property-accessor 'exn 'arguments (list)) exn)))
(unless (null? arguments)
(display ":" port)
(for-each (lambda (a) (display " " port) (write a port))
arguments)))
(newline port)
(exit 70))
(run))))
(define (run)
(let* ((argv (command-line-arguments)) (let* ((argv (command-line-arguments))
(raw-args (spell-stdout-output (args-before-separator argv))) (raw-args (args-before-separator argv))
(cc-args (args-after-separator argv)) (cc-args (args-after-separator argv))
(args (getopt-long (delete "-" raw-args) opts-grammar)) (args (getopt-long (spell-stdout-output raw-args)
opts-grammar))
(output (get-arg args 'output 'default)) (output (get-arg args 'output 'default))
(help (help-arg? args)) (help (help-arg? args))
(input (get-input-file args (stdin-dash? raw-args))) (input (get-input-file args))
(current-dir (current-directory))) (current-dir (current-directory)))
(call/cc (call/cc
(lambda (return) (lambda (return)
(when help (when help
(print-help) (print-help)
(return #f)) (return #f))
(when (and (equal? output "-") (not (text-output? args)))
(error "-o - is stdout, which takes only -C, -m or --public-interface"))
(when (same-file? input output)
(error "-o names the input, and would overwrite its source" input))
(when (and (string? input) (not (file-exists? input)))
(error (string-append input ": no such file")))
;; Read time comes before everything, so the features have to be ;; Read time comes before everything, so the features have to be
;; in place before the first form is read ;; in place before the first form is read
(current-features (current-features

53
tests/Makefile Normal file
View File

@@ -0,0 +1,53 @@
CHICKEN_C = csc
CSC_FLAGS += -K prefix -static
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc
SEX_OBJ = $(MODULES:%=%.o)
TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args module-path types infer
TEST_SRCS = $(TESTS:%=%.scm)
sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ)
$(CHICKEN_C) $(CSC_FLAGS) run.scm -o sex-tests -link sexc
#------------------------------------------------------------------
utils.o: utils.module.scm ../utils.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils
types.o: types.module.scm ../types.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) types.module.scm -o types.o -unit types
infer.o: infer.module.scm ../infer.scm types.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) infer.module.scm -o infer.o -unit infer -link types,utils
sex-macros.o: sex-macros.module.scm ../sex-macros.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-macros.module.scm -o sex-macros.o -unit sex-macros
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 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
sex-fmt-c.o: ../sex-fmt-c.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) ../sex-fmt-c.scm -o sex-fmt-c.o -unit sex-fmt-c
fmt-c-writer.o: fmt-c-writer.module.scm ../fmt-c-writer.scm sex-fmt-c.o types.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) fmt-c-writer.module.scm -o fmt-c-writer.o -unit fmt-c-writer -link sex-fmt-c,types,utils
sexc.o: sexc.module.scm infer.o types.o ../sexc.scm fmt-c-writer.o sex-macros.o sex-modules.o reader.o semen.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sexc.module.scm -o sexc.o -unit sexc -link fmt-c-writer,sex-macros,sex-modules,reader,semen,infer,types,utils
clean:
rm -f $(SEX_OBJ)
rm -f *.import.scm
rm -f *.link
rm -f sex-tests
.PHONY: clean

83
tests/args.scm Normal file
View File

@@ -0,0 +1,83 @@
;;; Splitting the command line at `--'.
;;;
;;; getopt-long cannot do this: it consumes the separator and merges
;;; everything after it into `@' alongside the input file. So sexc
;;; splits the raw argv first, and only the head is parsed as options.
;;; Everything else reaches the C compiler exactly as written --
;;; including the words that do not start with a dash, which a previous
;;; leading-dash heuristic used to drop.
(import sexc)
(define full '("foo.sex" "-o" "bar" "--" "-framework" "OpenGL" "-Wall"))
(test-group "argument separator"
(test "options and input file stay with sexc"
'("foo.sex" "-o" "bar")
(args-before-separator full))
(test "the tail reaches the compiler verbatim"
'("-framework" "OpenGL" "-Wall")
(args-after-separator full))
;; The case that motivated this: `OpenGL' has no leading dash and was
;; silently dropped, leaving `-framework' to swallow whatever flag
;; came next.
(test "a word without a dash survives"
'("-framework" "OpenGL")
(args-after-separator '("x.sex" "--" "-framework" "OpenGL")))
(test "no separator means nothing for the compiler"
'()
(args-after-separator '("foo.sex" "-o" "bar")))
(test "no separator leaves every argument with sexc"
'("foo.sex" "-o" "bar")
(args-before-separator '("foo.sex" "-o" "bar")))
(test "a trailing separator is allowed"
'()
(args-after-separator '("foo.sex" "--")))
(test "a leading separator leaves no input file"
'()
(args-before-separator '("--" "-lm")))
;; Only the first `--' separates; a later one is an ordinary compiler
;; argument (ld takes several).
(test "only the first separator counts"
'("-Wl,--as-needed" "--" "-lm")
(args-after-separator '("x.sex" "--" "-Wl,--as-needed" "--" "-lm")))
(test "an empty command line is handled"
'()
(args-before-separator '()))
;; getopt-long reads a lone `-' as an option and refused `-o -', so
;; it is handed the one spelling it takes a dash in
(test "-o - reaches getopt-long as a value"
'("x.sex" "--output=-" "-C")
(spell-stdout-output '("x.sex" "-o" "-" "-C")))
(test "and so does --output -"
'("--output=-")
(spell-stdout-output '("--output" "-")))
(test "any other output is left alone"
'("-o" "out" "-")
(spell-stdout-output '("-o" "out" "-"))))
;;; --depfile: an import pastes another file's forms into the output, so
;;; the output depends on that file as a C object does on a header
(test-group "dependency rule"
(test "the target, the source and the modules, then a rule per module"
"app.o: app.sex /m/greet.sex /m/ledger.sex\n\n/m/greet.sex:\n\n/m/ledger.sex:\n"
(dependency-rule "app.o" "app.sex" '("/m/greet.sex" "/m/ledger.sex")))
(test "no modules, no rules of their own"
"app.o: app.sex\n"
(dependency-rule "app.o" "app.sex" '()))
(test "a space is escaped, the way make reads it"
"a\\ b.o: a\\ b.sex\n"
(dependency-rule "a b.o" "a b.sex" '()))
(test "stdin is no file to depend on"
"app.o: /m/greet.sex\n\n/m/greet.sex:\n"
(dependency-rule "app.o" #f '("/m/greet.sex"))))

58
tests/basic.scm Normal file
View File

@@ -0,0 +1,58 @@
(import fmt-c-writer)
(test-group "basic"
;; unkebabify
(test '- (unkebabify '-))
(test '-- (unkebabify '--))
(test '-> (unkebabify '->))
(test '-= (unkebabify '-=))
(test 'kebab_case (unkebabify 'kebab-case))
(test '_what_ (unkebabify '-what-))
(test 'this->member (unkebabify 'this->member))
(test '_this_->_member_ (unkebabify '-this-->-member-))
(test '__->>> (unkebabify '--->>>))
;; A Lisp predicate and mutator, in letters C takes. The operators
;; spelled with the same characters are not names
(test 'ident_startʔ (unkebabify 'ident-start?))
(test 'resetꜝ (unkebabify 'reset!))
(test '! (unkebabify '!))
(test '!= (unkebabify '!=))
;; Non-ASCII identifiers must survive intact. The `regex' egg's
;; string-substitute drops one trailing character per multi-byte
;; character, which renames things silently -- the C still compiles,
;; just under a different name than was written.
(test 'naïve_count (unkebabify 'naïve-count))
(test 'aï_b (unkebabify 'aï-b))
(test 'ïï (unkebabify 'ïï))
;; atom-to-fmt-c
(test '%fun (atom-to-fmt-c 'fn))
(test '%prototype (atom-to-fmt-c 'prototype))
(test '%block-begin (atom-to-fmt-c 'do))
(test '%define (atom-to-fmt-c 'define))
(test '%pointer (atom-to-fmt-c 'pointer))
(test '%array (atom-to-fmt-c 'array))
(test 'vector-ref (atom-to-fmt-c '¤))
(test '%include (atom-to-fmt-c 'include))
;; C99 onwards, true C spellings for bool
(test 'bool (atom-to-fmt-c 'bool))
(test 'true (atom-to-fmt-c 'true))
(test 'false (atom-to-fmt-c 'false))
;; dot-access -> %. member-access directive (kebab-converted operands)
(test '(%. a b) (walk-expr '(dot-access a b)))
(test '(%. a b c) (walk-expr '(dot-access a b c)))
(test '(%. a_b c) (walk-expr '(dot-access a-b c)))
;; comment -> %comment directive (rendered as /* ... */)
;; The reader eats only the `;' that introduced the line, so ";;; Foo"
;; arrives as ";; Foo"; and c-comment puts nothing between /* */ and
;; the text. Both are handled on the way out.
(test '(%comment " hi ") (walk-expr '(comment " hi")))
(test '(%comment " hi ") (process-toplevel-form '(comment " hi")))
(test '(%comment " Foo ") (walk-expr '(comment ";; Foo")))
(test '(%comment " Foo ") (walk-expr '(comment ";;; Foo "))))

View File

@@ -1,24 +1,72 @@
;;; Codegen details that are easy to get subtly wrong: precedence, ;;; Codegen details that are easy to get subtly wrong, and that the
;;; scopes, comments in odd places, and the shapes no earlier test ;;; walk-* unit tests cannot see: they check the intermediate form we
;;; program happened to use. ;;; hand to fmt-c, not the C that fmt-c renders from it.
;;;
;;; Both cases below were found by writing an OpenGL example, not by
;;; the existing suite, because both need an operand shape that no
;;; earlier test program happened to use.
(import srfi-13) (import (chicken condition)
(chicken port)
(chicken string)
srfi-13
fmt-c-writer
reader
semen
utils)
;;; A record reached through a typedef of a pointer to it (define (read-source source)
(define pt-ref-src (with-input-from-string source
(string-append (lambda ()
"(record pt ((x int)))" (parameterize ((current-source-file "codegen.sex"))
"(ops pt (fn get ((self (* pt))) int (return (. self x))))" (parse-all (current-input-port))))))
"(typedef pt-ref (* pt))"
"(fn f ((q pt-ref)) int (return (+ (. q x) (. (* q) x) (.get q))))"))
;;; Paths through arrays of a struct and of pointers to one (define (sex->c source)
(define poly-src "Compile SOURCE, a string of Sex, and return the generated C."
(string-append (let ((forms (read-source source)))
"(struct pt ((x int) (y int)))" (with-output-to-string
"(struct poly ((pts [(struct pt) 4]) (pp [* struct pt 4]) (grid [(struct pt) 2 3])))" (lambda ()
"(fn f ((q (* struct poly))) int" (parameterize ((sex-line-directives 'none))
" (return (+ (. q [pts 2] y) (. q [pp 0] y) (. q [grid 1 2] x))))")) (emit-c (semen-process forms)))))))
;;; Warnings are what `warns?' is for; a test that happens to trip one
;;; should not print it
(define (silently thunk)
"THUNK's value, with whatever it wrote to stderr dropped."
(let ((value #f))
(with-error-output-to-string (lambda () (set! value (thunk))))
value))
(define (emits? source fragment)
(and (string-contains (silently (lambda () (sex->c source))) fragment) #t))
(define (failure-message thunk)
"The error THUNK raises as the user sees it -- message plus arguments,
the way CHICKEN prints it -- or #f if it raises none."
(handle-exceptions e
(with-output-to-string
(lambda ()
(display ((condition-property-accessor 'exn 'message) e))
(for-each (lambda (a) (display " ") (write a))
((condition-property-accessor 'exn 'arguments) e))))
(begin (thunk) #f)))
(define (error-message source)
"Compile SOURCE and return its error text, or #f if it compiles."
(failure-message (lambda () (sex->c source))))
(define (reports? source fragment)
(let ((m (error-message source)))
(and m (string-contains m fragment) #t)))
(define (followed-by? source first then)
"Is FIRST in the C compiled from SOURCE, and the next thing past it,
whitespace aside, THEN?"
(let* ((c (silently (lambda () (sex->c source))))
(at (string-contains c first)))
(and at
(let ((next (string-skip c char-whitespace? (+ at (string-length first)))))
(and next (string-prefix? then (substring c next)))))))
(define (in-fn body) (define (in-fn body)
(string-append "(fn f ((a int) (b int)) void " body ")")) (string-append "(fn f ((a int) (b int)) void " body ")"))
@@ -33,8 +81,18 @@
" (var p (struct point)) (var pp (* struct point) (& p))" " (var p (struct point)) (var pp (* struct point) (& p))"
" (var l (struct line)) " body ")")) " (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" (test-group "codegen"
;; c-switch handed its scrutinee straight to `cat', which only works
;; when it is an atom. Anything else was displayed as a raw
;; s-expression: `switch ((%. e type))'.
;; A case body shared the switch's scope, so two cases could not ;; A case body shared the switch's scope, so two cases could not
;; declare one name, and a label could not be followed by a ;; declare one name, and a label could not be followed by a
;; declaration before C23. Only a body that declares needs a block ;; declaration before C23. Only a body that declares needs a block
@@ -51,26 +109,6 @@
(not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))") (not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))")
"{" "{")))) "{" "{"))))
;; (case (1 2) ...) is two labels, so (case (+ 1 1) ...) came out as
;; three, the first of them `case +:'
(test-group "case labels"
(test-assert "a list of them is a case each"
(followed-by? (in-fn "(switch a (case (1 B) (g a)))") "case 1:" "case B:"))
(test-assert "an operator is not one"
(reports? (in-fn "(switch a (case (+ 1 1) (g a)))") "a case label is a value"))
(test-assert "nor is an expression in the list"
(reports? (in-fn "(switch a (case (1 (- 2)) (g a)))") "a case label is a value"))
(test-assert "a value is written once"
(reports? (in-fn "(switch a (case (1 2 1) (g a)))") "case label written twice"))
(test-assert "in the whole switch"
(reports? (in-fn "(switch a (case 1 (g a)) (case/fallthrough (2 1)) (default (g b)))")
"case label written twice"))
(test-assert "each switch apart"
(emits? (in-fn "(switch a (case 1 (g a))) (switch b (case 1 (g b)))") "case 1:")))
;; c-switch handed its scrutinee straight to `cat', which only works
;; when it is an atom. Anything else was displayed as a raw
;; s-expression: `switch ((%. e type))'.
(test-group "switch scrutinee" (test-group "switch scrutinee"
(test-assert "member access" (test-assert "member access"
(emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))" (emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))"
@@ -142,18 +180,7 @@
"a ? a : b ? b : 0")) "a ? a : b ? b : 0"))
(test-assert "but an assignment there is not" (test-assert "but an assignment there is not"
(emits? (in-fn "(var x int (if a a (= b 1)))") (emits? (in-fn "(var x int (if a a (= b 1)))")
"a ? a : (b = 1)")) "a ? a : (b = 1)")))
;; with nothing for the false case it came out `a || 1', a boolean
(test-assert "a value needs an else"
(reports? (in-fn "(var x int (if a 1))") "an if used as a value needs an else"))
(test-assert "so does a chain"
(reports? (in-fn "(var x int (if a 1 b 2))") "an if used as a value needs an else"))
(test-assert "and an if in a value's branch"
(reports? (in-fn "(var x int (if a 1 (if b 2)))") "an if used as a value needs an else"))
(test-assert "a chain with one is a chain"
(emits? (in-fn "(var x int (if a 1 b 2 3))") "a ? 1 : b ? 2 : 3"))
(test-assert "and a statement needs none"
(emits? (in-fn "(if a (g a))") "if (a)")))
;; A subscript binds tighter than anything, so what it subscripts is ;; A subscript binds tighter than anything, so what it subscripts is
;; parenthesised whenever it is an operator: `*q[i]' is *(q[i]) ;; parenthesised whenever it is an operator: `*q[i]' is *(q[i])
@@ -246,14 +273,6 @@
"enum color m = red")) "enum color m = red"))
(test-assert "a malformed enum is rejected with its location" (test-assert "a malformed enum is rejected with its location"
(reports? "(enum)" "codegen.sex:1:")) (reports? "(enum)" "codegen.sex:1:"))
;; anything else in the list was the name its head was and the
;; value its second element: (! 1 2) came out `! = 1'
(test-assert "an enumerator is a name, or a name and a value"
(reports? "(enum color (red (! 1 2)))" "an enumerator is a name, or (name value)"))
(test-assert "and an operator is no name"
(reports? "(enum color (red (! 1)))" "an enumerator is a name, or (name value)"))
(test-assert "nor a value with no name"
(reports? "(enum color (red 7))" "an enumerator is a name, or (name value)"))
;; c-type handed the declarator's name to c-enum as the enum tag, ;; c-type handed the declarator's name to c-enum as the enum tag,
;; so this emitted `enum m { up, down }' with no variable at all ;; so this emitted `enum m { up, down }' with no variable at all
(test-assert "an anonymous enum keeps the variable" (test-assert "an anonymous enum keeps the variable"
@@ -290,14 +309,7 @@
(test-assert "c-or is still accepted" (test-assert "c-or is still accepted"
(emits? (in-fn "(var x int (c-or a b))") "a || b")) (emits? (in-fn "(var x int (c-or a b))") "a || b"))
(test-assert "c-bit-or is still accepted" (test-assert "c-bit-or is still accepted"
(emits? (in-fn "(var x int (c-bit-or a b))") "a | b")) (emits? (in-fn "(var x int (c-bit-or a b))") "a | b")))
;; the names fmt-c has cases for were respelled bit_and before it
;; saw them, and called as functions
(test-assert "and so are the named ones"
(emits? (in-fn "(var x _ (bit-and a b)) (var y _ (bit-or a b)) (var z _ (bit-xor a b))")
"int z = a ^ b"))
(test-assert "bit-not among them"
(emits? (in-fn "(var x _ (bit-not a))") "int x = ~a")))
;; A `;' comment is a form. In a macro body `comment' is a no-op ;; A `;' comment is a form. In a macro body `comment' is a no-op
;; that swallows the comment itself. Inside a quasiquoted payload ;; that swallows the comment itself. Inside a quasiquoted payload
@@ -322,31 +334,10 @@
(test-assert "the offending form is shown too" (test-assert "the offending form is shown too"
(reports? "(include stdio.h)\n(wat 1 2)" "(wat 1 2)")) (reports? "(include stdio.h)\n(wat 1 2)" "(wat 1 2)"))
(test-assert "pub with nothing to define" (test-assert "pub with nothing to define"
(reports? "(pub 1)" "codegen.sex:1:")) (reports? "(pub 1)" "codegen.sex:1:")))
;; a macro's arity was CHICKEN's to report, about a procedure with
;; no name; and an error in its body said nothing of the call
(test-assert "a macro given the wrong number of arguments"
(reports? "(defmacro (one x) x)\n(fn f () int\n (return (one 1 2)))"
"codegen.sex:3: macro takes this many arguments one 1"))
(test-assert "at toplevel too"
(reports? "(defmacro (one x) x)\n(one)" "codegen.sex:2: macro takes this many arguments"))
(test-assert "and one taking the rest, too few"
(reports? "(defmacro (many x . more) x)\n(fn f () int (return (many)))"
"macro takes at least this many arguments many 1"))
(test-assert "while it may take any more"
(emits? "(defmacro (many x . more) x) (fn f () int (return (many 1 2 3)))" "return 1;"))
;; a call before the macro is defined is a function call, and the
;; macro defined after it went unused there without a word
(test-assert "a macro defined after a call to it is refused"
(reports? "(fn f () int (return (later 1)))\n(defmacro (later x) x)"
"codegen.sex:2: a macro defined after a call to it"))
(test-assert "naming where the call is"
(reports? "(fn f () int\n (return (later 1)))\n(defmacro (later x) x)"
"/codegen.sex:2\""))
(test-assert "an error in a macro's body names the call"
(reports? "(defmacro (boom x) (error \"no good\" x))\n(fn f () int (return (boom 1)))"
"codegen.sex:2: expanding boom: no good")))
;; A nested pointer chain used to silently lose a level:
;; (var p (* (* char))) emitted `char *p'
;; A grouped header, C's parens carried over, died in the writer with ;; A grouped header, C's parens carried over, died in the writer with
;; `(caddr) bad argument type' and no location ;; `(caddr) bad argument type' and no location
(test-group "malformed for" (test-group "malformed for"
@@ -366,56 +357,6 @@
(reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))" (reports? "(fn f () void\n (for ((var i int 0) (< i 4) (++ i)) (g i)))"
"codegen.sex:2:"))) "codegen.sex:2:")))
;; each of these died in the writer, in CHICKEN's words about a
;; procedure of the writer's, and with no location
(test-group "malformed forms"
(test-assert "a goto names one label"
(reports? (in-fn "(goto)") "malformed goto: write (goto label)"))
(test-assert "and only one"
(reports? (in-fn "(goto a b)") "malformed goto"))
(test-assert "so does a label"
(reports? (in-fn "(: a b)") "malformed :: write (: label)"))
(test-assert "a var has a name and a type"
(reports? (in-fn "(var q)") "malformed var"))
(test-assert "and a value at most"
(reports? (in-fn "(var q int 1 2)") "malformed var"))
(test-assert "a cast a value and a type"
(reports? (in-fn "(var n int (cast a))") "malformed cast: write (cast value type)"))
(test-assert "a while its test"
(reports? (in-fn "(while)") "malformed while"))
(test-assert "an if its test and what it does"
(reports? (in-fn "(if a)") "malformed if"))
(test-assert "a return one value at most"
(reports? (in-fn "(return 1 2)") "malformed return"))
(test-assert "a break none"
(reports? (in-fn "(while a (break 1))") "malformed break"))
(test-assert "a sizeof one operand"
(reports? (in-fn "(var n size-t (sizeof a b))") "malformed sizeof"))
(test-assert "a global var is held to the same"
(reports? "(var q)" "malformed var"))
(test-assert "each naming its line"
(reports? "(fn f () void\n (goto))" "codegen.sex:2: malformed goto")))
;; a block of nothing had nothing for c-begin to begin with, and the
;; writer died on its arity
(test-group "empty bodies"
(test-assert "an empty block is a pair of braces"
(followed-by? (in-fn "(do) (g a)") "{}" "g(a);"))
(test-assert "inside another too"
(followed-by? (in-fn "(do (do) (g a))") "{}" "g(a);"))
(test-assert "and a for with no body has them"
(emits? (in-fn "(for (var i int 0) (< i a) (++ i))") "for (int i = 0; i < a; ++i) {}")))
;; an empty slot was the empty list, which C was told as NULL: the
;; test of (for () () ()) was false, and the loop never ran
(test-group "empty for slots"
(test-assert "are empty"
(emits? (in-fn "(for () () () (g a))") "for (;;) {"))
(test-assert "any of them"
(emits? (in-fn "(for () (< a 1) () (g a))") "for (; a < 1;) {")))
;; A nested pointer chain used to silently lose a level:
;; (var p (* (* char))) emitted `char *p'
(test-group "malformed types are rejected" (test-group "malformed types are rejected"
(test-assert "nested pointer chain" (test-assert "nested pointer chain"
(reports? (in-fn "(var p (* (* char)))") "pointer chains are written flat")) (reports? (in-fn "(var p (* (* char)))") "pointer chains are written flat"))
@@ -430,13 +371,6 @@
;; A string as the first body form (or after the name of a struct, ;; A string as the first body form (or after the name of a struct,
;; union or enum) is a docstring: it becomes a comment immediately ;; union or enum) is a docstring: it becomes a comment immediately
;; before the declaration, not a statement inside it. ;; before the declaration, not a statement inside it.
(test-group "a sum's docstring"
;; record, struct and enum took one, and sum read it as its variants
(test-assert "is a comment ahead of it"
(emits? "(sum shape \"A shape.\" ((dot ()) (box ((w int)))))" "/* A shape. */"))
(test-assert "and the sum is still one"
(emits? "(sum shape \"A shape.\" ((dot ()) (box ((w int)))))" "shapeǂbox")))
(test-group "docstrings" (test-group "docstrings"
(test-assert "appears before the function" (test-assert "appears before the function"
(emits? "(fn greet ((name (* char))) void \"Greet NAME.\" (printf \"hi\" name))" (emits? "(fn greet ((name (* char))) void \"Greet NAME.\" (printf \"hi\" name))"
@@ -474,20 +408,127 @@
(not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")") (not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")")
"static_assert(")))) "static_assert("))))
(test-group "lambdas" ;; A closure is a code pointer beside its captures. The struct is
;; a definition names every parameter before C23, so one written as a ;; named from the signature, so separate translation units agree on
;; type alone gets a name nothing reads ;; it, and calling one goes through `code' with `env' passed first.
(test-assert "a lambda's unnamed parameter is named in its definition" ;;
(emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))" ;; A closure struct, and the helper its calls go through, are each
"λ0_f (int λu0, int b)")) ;; emitted once per signature; the registries deciding that are
(test-assert "and a variadic one keeps its ..." ;; compile-time state like the type databases, and outlive a single
(emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))" ;; `sex->c' here. So every case below that looks for a *definition*
"λ0_f (int n, ...)")) ;; uses a signature of its own -- cases looking at a call site can
;; a lifted function with no body was a declaration of one, and ;; share one.
;; nothing defined it (test-group "closures"
(test-assert "an empty lambda is an empty function" (test-assert "the type becomes a struct named for its signature"
(emits? "(fn f () void (var g (fn () void) (lambda () void)))" (emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"static void λ0_f (void) {}"))) "struct ƛint_int"))
;; The environment is one shared union, declared in the prelude --
;; its layout is part of the ABI two units agree on, so it cannot
;; depend on what either file contains. `sex->c' has no prelude, so
;; what is visible here is the member
(test-assert "whose environment is the shared union"
(emits? "(fn f ((c (closure ((float)) int))) int (return (c 1.0)))"
"union ƛenv env;"))
;; The receiver goes through a helper rather than being written
;; out twice, so that `[table (++ i)]' evaluates its index once,
;; exactly as it would for an array of function pointers
(test-assert "a call passes the receiver to a helper"
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"ƛint_int_call(c, 1)"))
(test-assert "and the helper is what dereferences it"
(emits? "(fn f ((c (closure ((long)) int))) int (return (c 1)))"
"ƛc.code(&ƛc.env, ƛa0)"))
(test-assert "a subscript receiver is evaluated once"
(emits? "(fn f ((t [(closure ((int)) int) 4]) (i int)) int (return ([t (++ i)] 1)))"
"ƛint_int_call(t[++i], 1)"))
(test-assert "so is a member receiver"
(emits? "(struct h ((cb (closure ((int)) int))))
(fn f ((s (struct h))) int (return ((. s cb) 1)))"
"ƛint_int_call(s.cb, 1)"))
(test-assert "a captured name is rebound in the lifted body"
(emits? "(fn f ((n int)) (closure ((char)) int) (return (closure ((x char)) int (n) (return n))))"
"int n = ƛcaptures->n;"))
(test-assert "captures are checked against the environment"
(emits? "(fn f ((n int)) (closure ((short)) int) (return (closure ((x short)) int (n) (return n))))"
"_Static_assert(sizeof(struct"))
;; A closure over nothing has no record to point at, and C has no
;; empty struct to declare for it
(test-assert "no captures means no capture record"
(not (emits? "(fn f () (closure () int) (return (closure () int () (return 7))))"
"_captures {")))
;; `(name expr)' names a capture and gives what it holds, so the
;; expression is evaluated once, where the closure is written
(test-assert "a named capture takes its type from the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"int sum;"))
(test-assert "and the constructor is handed the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"_make(s.x + s.y)"))
(test-assert "capturing a pointer is how by-reference is spelled"
(emits? "(struct p ((x int)))
(fn f ((s (* (struct p)))) (closure () int)
(return (closure () int ((q s)) (return (-> q x)))))"
"struct p* q;"))
;; A bare function is a closure that captures nothing, so it
;; converts wherever one is expected -- the pointer goes in the
;; environment and one thunk per signature reads it back out
(test-assert "a named function in a var initializer"
(emits? "(fn g ((n int)) int (return n))
(fn f () void (var c (closure ((int)) int) g))"
"ƛint_int_fromfn(g)"))
(test-assert "a lambda, which is a bare function too"
(emits? "(fn f () void (var c (closure ((int)) int)
(lambda ((n int)) int (return n))))"
"ƛint_int_fromfn(λ0_f)"))
(test-assert "an argument, against the parameter that signature wrote"
(emits? "(fn g ((n int)) int (return n))
(fn h ((c (closure ((int)) int))) int (return (c 1)))
(fn f () int (return (h g)))"
"h(ƛint_int_fromfn(g))"))
(test-assert "a return, against the declared return type"
(emits? "(fn g ((n int)) int (return n))
(fn f () (closure ((int)) int) (return g))"
"return ƛint_int_fromfn(g)"))
(test-assert "the thunk reads the pointer out of the environment"
(emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((float)) int) g))"
"return ƛcaptures->f(ƛa0)"))
;; a signature that does not match is left alone, and C rejects it
(test-assert "a function of the wrong signature does not convert"
(not (emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((int)) int) g))"
"_fromfn(g)")))
;; a closure is lifted into the function it was written in, so
;; there has to be one
(test-assert "a closure at toplevel is refused"
(reports? "(var c (closure () int) (closure () int () (return 1)))"
"only be written inside a function"))
(test-assert "and so is one in a struct field"
(reports? "(struct s ((f (closure () int) (closure () int () (return 1)))))"
"only be written inside a function"))
;; A block opens a scope, so what it declares ends with it
(test-assert "a name shadowed in a block does not escape it"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"ƛvoid_int_call(c)"))
(test-assert "and the shadowing declaration is what the block sees"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"g(c)"))
;; The receiver is written twice, so a name used as an argument
;; must not be mistaken for a call of its own
(test-assert "a closure passed as an argument stays a value"
(emits? "(fn g ((c (closure ((int)) int))) int (return 0))
(fn f ((c (closure ((int)) int))) int (return (g c)))"
"g(c)")))
;; An include target is a path, so none of the identifier mangling ;; 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. ;; applies to it: GL/gl.h is a file and GLːgl.h is not.
@@ -543,16 +584,16 @@
(defmacro (t x) (type-match (type-of x) (float 1) (else 0))) (defmacro (t x) (type-match (type-of x) (float 1) (else 0)))
(fn f () int (return (t (g))))" (fn f () int (return (t (g))))"
"return 1;")) "return 1;"))
;; a macro is shown the written spelling, not a generated name ;; a macro is shown the written spelling, not the generated struct
(test-assert "a function pointer, spelled the way it was written" (test-assert "a closure, spelled the way it was written"
(emits? "(fn mk () (fn ((int)) int) (emits? "(fn mk () (closure ((int)) int)
(return (lambda ((b int)) int (return b)))) (return (closure ((b int)) int () (return b))))
(defmacro (t x) (type-match (type-of x) ((fn _ _) 1) (else 0))) (defmacro (t x) (type-match (type-of x) ((closure _ _) 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t c)))" (fn f () int (var c _ (mk)) (return (t c)))"
"return 1;")) "return 1;"))
(test-assert "and calling one has the function's return type" (test-assert "and calling one has the closure's return type"
(emits? "(fn mk () (fn ((int)) int) (emits? "(fn mk () (closure ((int)) int)
(return (lambda ((b int)) int (return b)))) (return (closure ((b int)) int () (return b))))
(defmacro (t x) (type-match (type-of x) (int 1) (else 0))) (defmacro (t x) (type-match (type-of x) (int 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t (c 1))))" (fn f () int (var c _ (mk)) (return (t (c 1))))"
"return 1;")) "return 1;"))
@@ -594,113 +635,6 @@
"struct p* x = &s")) "struct p* x = &s"))
(test-assert "a wildcard inside an array" (test-assert "a wildcard inside an array"
(emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]")) (emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]"))
;; each `_' is its own variable: solving one leaves the rest open
(test-assert "every wildcard in a signature is its own"
(emits? "(fn g ((x int)) char (return 0))
(fn f () void (var h (fn ((_)) _) g))"
"char (*h)(int) = g"))
(test-assert "and the signature's arity has to match"
(reports? "(fn g ((x int) (y int)) int (return 0))
(fn f () void (var h (fn ((_)) _) g))"
"type mismatch"))
(test-assert "a typedef answers as itself"
(emits? "(typedef count int) (fn g () count (return 0))
(fn f () void (var x _ (g)))"
"count x = g()"))
;; only an integer was taken for a length; a name was read as part
;; of the element's
(test-assert "of a named length"
(emits? "(define N 3) (fn f () void (var t [_ N] #(1 2 3)))" "int t[N]"))
(test-assert "which an array of decays from as any other"
(emits? "(define N 3) (fn f () void (var a [int N]) (var p _ (+ a 1)))"
"int * p = a + 1"))
(test-assert "while a length left to work out is not one"
(reports? (in-fn "(var t [_ _] #(1 2))") "cannot infer"))
;; an array as a value is a pointer to its first element, where `_'
;; declared a copy, which C cannot initialize from it
(test-assert "an array decays into `_'"
(emits? (in-fn "(var s [char 6]) (var t _ s)") "char * t = s"))
(test-assert "a row of one too"
(emits? (in-fn "(var m [int 2 3]) (var r _ [m 1])") "int * r = m[1]"))
(test-assert "and a field"
(emits? "(struct h ((xs [int 4]))) (fn f ((v (struct h))) void (var p _ (. v xs)))"
"int * p = v.xs"))
;; nothing solves a `_' in a signature: it reached C as one
(test-assert "a parameter's type is written out"
(reports? "(fn id ((x _)) int (return x))" "a function's types are written out"))
(test-assert "and so is the return type"
(reports? "(fn id ((x int)) _ (return x))" "a function's types are written out"))
(test-assert "a lambda's as well"
(reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))")
"a function's types are written out"))
;; a call was typed by asking the global table what a function of
;; that name returns, which a local pointer is not
;; a value if had no rule either: it is the join of its values
(test-assert "a value if joins its branches"
(emits? (in-fn "(var x _ (if a 1 2.5))") "double x = a ? 1 : 2.5"))
(test-assert "every one of a chain"
(emits? (in-fn "(var x _ (if a 1 b 2 3.5f))") "float x"))
(test-assert "an aggregate as itself"
(emits? "(struct pt ((x int))) (fn f ((a int) (p (struct pt))) void (var q _ (if a p p)))"
"struct pt q = a ? p : p"))
(test-assert "and none when a branch says nothing"
(reports? (in-fn "(var x _ (if a (unheard-of) 1))") "infer"))
;; none of these had a rule
(test-assert "#t is a bool, as true is"
(emits? (in-fn "(var t _ #t)") "bool t = 1"))
(test-assert "an enum's constant is the enum, whose ops it can call"
(emits? "(enum color (red green)) (fn f () void (var c _ green))" "enum color c = green"))
(test-assert "a bit-not is its operand, promoted"
(emits? (in-fn "(var u (unsigned int) 1) (var v _ (~ u))") "unsigned int v = ~u"))
(test-assert "a char's to an int"
(emits? (in-fn "(var c char 1) (var w _ (bit-not c))") "int w = ~c"))
(test-assert "a call through a local function pointer"
(emits? (string-append "(fn area ((w int) (h int)) int (return (* w h)))"
"(fn f () void (var p (fn ((int) (int)) int) area) (var r _ (p 3 4)))")
"int r = p(3, 4)"))
(test-assert "through a parameter"
(emits? "(fn ap ((g (fn ((int)) double)) (x int)) void (var r _ (g x)))" "double r = g(x)"))
(test-assert "through a field"
(emits? (string-append "(struct ops ((op (fn ((int)) float))))"
"(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))")
"float r = o.op(1)"))
(test-assert "while a function is the pointer it already is"
(emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))"
"int (*p)(int) = g"))
;; a variable had nowhere to keep a qualifier written on it, and
;; what it was solved to came out without
(test-assert "a qualified wildcard keeps its qualifier"
(emits? (in-fn "(var k (const _) 5)") "const int k = 5"))
(test-assert "behind a pointer too"
(emits? (in-fn "(var p (* const _) (& a))") "const int * p = &a"))
(test-assert "and says it once, solved to a type already saying it"
(emits? (in-fn "(var k (const int) 1) (var p (* const _) (& k))")
"const int * p = &k"))
;; an operator's result is a value, which has no qualifier -- the
;; spelling was the first operand's, so it had one only that way round
(test-assert "a sum is unqualified"
(emits? (in-fn "(var k (const int) 1) (var j _ (+ k 1))") " int j = k + 1"))
(test-assert "whichever side the qualified operand is on"
(emits? (in-fn "(var k (const int) 1) (var j _ (+ 1 k))") " int j = 1 + k"))
(test-assert "and so is a pointer it gives"
(emits? (in-fn "(var s (* char) 0) (var p (const * char) s) (var q _ (+ p 1))")
"char * q = p + 1"))
;; the join took the first pointer, and declared the distance one
(test-assert "one pointer from another is a distance"
(emits? (in-fn "(var p (* int) 0) (var q (* int) 0) (var d _ (- p q))")
"ptrdiff_t d = p - q"))
(test-assert "an array decays to one for it"
(emits? (in-fn "(var xs [int 4]) (var p (* int) xs) (var d _ (- p xs))")
"ptrdiff_t d = p - xs"))
(test-assert "a number from a pointer is still a pointer"
(emits? (in-fn "(var p (* int) 0) (var r _ (- p 1))") "int * r = p - 1"))
;; one operand was a join with nothing, which left it unpromoted
(test-assert "a negation promotes its operand"
(emits? (in-fn "(var c char 1) (var n _ (- c))") "int n = -c"))
(test-assert "so does a unary plus"
(emits? (in-fn "(var h short 1) (var n _ (+ h))") "int n = +h"))
(test-assert "and leaves a wide one as it is"
(emits? (in-fn "(var l long 1) (var n _ (- l))") "long n = -l"))
;; a compound literal carries its own type, where a brace ;; a compound literal carries its own type, where a brace
;; initializer has none and takes one from its context ;; initializer has none and takes one from its context
(test-assert "a compound literal answers a bare wildcard" (test-assert "a compound literal answers a bare wildcard"
@@ -716,17 +650,18 @@
(emits? (in-fn "(var t [_ 10] #(1 2))") "int t[10] = {1, 2}")) (emits? (in-fn "(var t [_ 10] #(1 2))") "int t[10] = {1, 2}"))
(test-assert "and they have to agree with each other" (test-assert "and they have to agree with each other"
(reports? (in-fn "(var t [_ 2] #(1 \"s\"))") "type mismatch")) (reports? (in-fn "(var t [_ 2] #(1 \"s\"))") "type mismatch"))
;; a function pointer type reaches the solver as itself ;; a closure type reaches the solver as the struct that stands for
(test-assert "a lambda, from the signature that produced it" ;; it, which is the spelling `parse-type' knows
(emits? "(fn mk () (fn ((int)) int) (test-assert "a closure, from the signature that produced it"
(return (lambda ((b int)) int (return b)))) (emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(fn f () void (var c _ (mk)))" (fn f () void (var c _ (mk)))"
"int (*c)(int) = mk()")) "struct ƛint_int c = mk()"))
(test-assert "and it is callable once inferred" (test-assert "and it is callable once inferred"
(emits? "(fn mk () (fn ((int)) int) (emits? "(fn mk () (closure ((int)) int)
(return (lambda ((b int)) int (return b)))) (return (closure ((b int)) int () (return b))))
(fn f () int (var c _ (mk)) (return (c 1)))" (fn f () int (var c _ (mk)) (return (c 1)))"
"return c(1)")) "ƛint_int_call(c, 1)"))
;; C's usual arithmetic conversions, far enough to answer `_' ;; C's usual arithmetic conversions, far enough to answer `_'
(test-assert "floating beats integral" (test-assert "floating beats integral"
(emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d")) (emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d"))
@@ -780,36 +715,19 @@
(test-assert "and ($) is nothing at all" (test-assert "and ($) is nothing at all"
(emits? "(defmacro (quiet) (list '$)) (quiet) (fn f () int (return 1))" (emits? "(defmacro (quiet) (list '$)) (quiet) (fn f () int (return 1))"
"return 1;")) "return 1;"))
;; only the outermost was spliced: an inner one was an unknown
;; toplevel form, and in a body a call of `$'
(test-assert "a $ inside one splices too"
(emits? "(defmacro (pairs) (list '$ (list '$ '(fn a () int (return 1)))
'(fn b () int (return 2))))
(pairs)"
"a (void)"))
(test-assert "in a body as well"
(let ((c (silently
(lambda ()
(sex->c "(defmacro (twice) (list '$ (list '$ '(g 1)) '(g 2)))
(fn f () void (twice))")))))
(and (string-contains c "g(1);") (string-contains c "g(2);")
(not (string-contains c "$")))))
(test-assert "and an inner ($) is nothing"
(emits? "(defmacro (quiet) (list '$ (list '$))) (quiet) (fn f () int (return 1))"
"return 1;"))
;; without `$' a list is one form, so a head that is itself a form ;; without `$' a list is one form, so a head that is itself a form
;; stays a call rather than becoming two statements ;; stays a call rather than becoming two statements
(test-assert "a computed callee stays one form" (test-assert "a computed callee stays one form"
(emits? "(fn mk () (fn ((int)) int) (emits? "(fn mk () (closure ((int)) int)
(return (lambda ((b int)) int (return b)))) (return (closure ((b int)) int () (return b))))
(defmacro (apply-it x) `((mk) ,x)) (defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))" (fn f () int (return (apply-it 5)))"
"mk()(5)")) "ƛint_int_call(mk(), 5)"))
;; spliced, it would have become two forms in the `return' -- the ;; spliced, it would have become two forms in the `return' -- the
;; comma operator, and the wrong answer ;; comma operator, and the wrong answer
(test-assert "rather than two forms in its context" (test-assert "rather than two forms in its context"
(not (emits? "(fn mk () (fn ((int)) int) (not (emits? "(fn mk () (closure ((int)) int)
(return (lambda ((b int)) int (return b)))) (return (closure ((b int)) int () (return b))))
(defmacro (apply-it x) `((mk) ,x)) (defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))" (fn f () int (return (apply-it 5)))"
"return mk(), 5")))) "return mk(), 5"))))
@@ -824,8 +742,7 @@
(not (emits? "(struct pt ((x int))) (fn f ((p (* (struct pt)))) int (return (. (* p) x)))" (not (emits? "(struct pt ((x int))) (fn f ((p (* (struct pt)))) int (return (. (* p) x)))"
"*(p).x"))) "*(p).x")))
(test-assert "member access through a cast" (test-assert "member access through a cast"
(emits? (string-append "(struct s ((f int)))" (emits? (in-fn "(var n int (. (* (cast a (* (struct s)))) f))")
(in-fn "(var n int (. (* (cast a (* (struct s)))) f))"))
"(*(struct s*)a).f")) "(*(struct s*)a).f"))
;; ...without gaining parens where none are due ;; ...without gaining parens where none are due
(test-assert "a bare dereference is left alone" (test-assert "a bare dereference is left alone"
@@ -835,88 +752,6 @@
(test-assert "and negation beside a binary operator" (test-assert "and negation beside a binary operator"
(emits? (in-fn "(var n int (+ (- a) b))") "-a + b"))) (emits? (in-fn "(var n int (+ (- a) b))") "-a + b")))
;; A type was flattened word by word, a struct written out in it
;; included: (* (struct ((c int)))) came out `struct c{ int; } *'
(test-group "a pointer to an aggregate written in place"
(test-assert "keeps its fields"
(followed-by? "(struct h ((b (* (struct ((c int)))))))" "int c;" "} * b;"))
(test-assert "a pointer among them as well"
(emits? "(struct h ((b (* (struct ((p (* int)) (n int)))))))" "int * p;"))
(test-assert "and a qualifier before it"
(emits? "(struct h ((e (* const (union ((u int) (v float)))))))" "const union{"))
(test-assert "behind as many stars as are written"
(emits? "(struct h ((f (* * (struct ((c int)))))))" "} * * f;")))
;; A function type's return was written ahead of its declarator, so a
;; function returning one came out `int (*)(int) get (void)'
(test-group "a function type returning one"
(test-assert "a function returning a function pointer"
(emits? "(fn inc ((x int)) int (return x)) (fn get () (fn ((int)) int) (return inc))"
"int (*get (void))(int)"))
(test-assert "and its prototype"
(emits? "(pub fn get () (fn ((int)) int))" "int (*get (void))(int);"))
(test-assert "a variable of one"
(emits? "(var g (fn ((int)) (fn () void)))" "void (*(*g)(int))()"))
(test-assert "and a parameter"
(emits? "(fn take ((f (fn ((int)) (fn () void)))) void (return))"
"take (void (*(*f)(int))())")))
;; the writer's own words were its own wherever they stood, so a
;; name spelled like one came out `%array'
(test-group "names the writer has words for"
(test-assert "as variables"
(emits? (in-fn "(var array int 1) (var define int 2) (var include int 3) (g array define include)")
"g(array, define, include)"))
(test-assert "as parameters"
(emits? "(fn sum ((array (* int)) (pointer int)) int (return (+ [array 0] pointer)))"
"sum (int * array, int pointer)"))
(test-assert "as fields"
(emits? "(struct s ((prototype int) (attribute int)))" "int prototype;"))
(test-assert "as a typedef's name, and used as a type"
(emits? "(typedef array int) (fn f () void (var a array 1))" " array a = 1;"))
(test-assert "while at a form's head they are the writer's still"
(emits? "(include stdio.h) (fn f () void (static-assert (== 1 1) \"x\"))"
"_Static_assert(1 == 1, \"x\")")))
;; Operands past what an operator takes were written as they came:
;; (< a b c) as C's own chain, which compares a boolean with c
(test-group "operator arity"
(test-assert "a comparison takes two operands"
(reports? (in-fn "(var x bool (< a b a))") "a comparison takes two operands"))
(test-assert "equality too"
(reports? (in-fn "(var x bool (== a b a))") "a comparison takes two operands"))
(test-assert "and not one"
(reports? (in-fn "(var x bool (>= a))") "a comparison takes two operands"))
(test-assert "two is a comparison"
(emits? (in-fn "(var x bool (<= a b))") "x = a <= b;"))
;; ...and (/ a) as `/a', (! a b) as `a ! b'
(test-assert "a division takes two or more"
(reports? (in-fn "(var x int (/ a))") "takes two operands or more"))
(test-assert "so does &&"
(reports? (in-fn "(var x bool (&& a))") "takes two operands or more"))
(test-assert "a compound assignment takes two"
(reports? (in-fn "(+= a b a)") "takes two operands"))
(test-assert "a negation takes one"
(reports? (in-fn "(var x bool (! a b))") "takes one operand"))
(test-assert "a bit-not too"
(reports? (in-fn "(var x int (~ a b))") "takes one operand"))
(test-assert "minus takes one or more"
(reports? (in-fn "(var x int (-))") "takes one operand or more"))
(test-assert "and with more than one is still a subtraction"
(emits? (in-fn "(var x int (- a b a))") "x = a - b - a;"))
;; ++ and -- step each operand in turn
(test-assert "a statement steps each operand"
(followed-by? (in-fn "(++ a b)") "++a;" "++b;"))
(test-assert "so does a for's step, which is one expression"
(emits? (in-fn "(for (var i int 0) (< i a) (++ i b) (g i))") "; ++i, ++b)"))
(test-assert "and a value is one too, in parens"
(emits? (in-fn "(var x int (-- a b))") "x = (--a, --b);"))
;; a define's body is pasted, not walked, so it is looked at apart
(test-assert "a define's body is held to the same"
(reports? "(define BAD (< 1 2 3))" "a comparison takes two operands"))
(test-assert "and steps each operand the same way"
(emits? "(define (STEP a b) (++ a b))" "#define STEP(a, b) ((++(a), ++(b)))")))
;; An array bound was taken only when it was an integer literal, so a ;; An array bound was taken only when it was an integer literal, so a
;; symbolic one fell into the type: `[int N]' came out `int N a[]'. ;; symbolic one fell into the type: `[int N]' came out `int N a[]'.
(test-group "array bounds" (test-group "array bounds"
@@ -939,41 +774,9 @@
(test-assert "nor is an aggregate tag" (test-assert "nor is an aggregate tag"
(emits? "(struct t ((z int))) (struct s ((a [struct t])))" "struct t a[]")) (emits? "(struct t ((z int))) (struct s ((a [struct t])))" "struct t a[]"))
(test-assert "nor one behind a pointer" (test-assert "nor one behind a pointer"
(emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]")) (emits? "(struct t ((z int))) (struct s ((a [* struct t])))" "struct t* a[]")))
;; a qualifier waits for a type name only when none came before it
(test-assert "a name after a qualified type is a bound"
(emits? (in-fn "(var b [int const N])") "int const b[N]"))
(test-assert "after a qualified name too"
(emits? (in-fn "(var b [mytype const N])") "mytype const b[N]"))
(test-assert "but a qualifier alone still waits for the type"
(emits? "(typedef mytype int) (struct s ((a [const mytype])))" "const mytype a[]"))
;; [m 1 2] is m[1][2], so [int 2 3] declares what it indexes. A
;; second bound was taken for the last word of the element type
(test-assert "every trailing bound is a dimension"
(emits? (in-fn "(var m [int 2 3])") "int m[2][3];"))
(test-assert "however many there are"
(emits? (in-fn "(var c [u8 2 3 4])") "u8 c[2][3][4];"))
(test-assert "named ones too"
(emits? "(define N 2) (struct s ((a [* char N 3])))" "char * a[N][3]"))
;; a list after a tag's keyword is the aggregate's body
(test-assert "an inline aggregate's fields are not one"
(emits? "(struct s ((a [struct ((x int)) 2 3])))" "a[2][3]"))
(test-assert "but an expression after a tag is"
(emits? "(define N 2) (struct t ((z int))) (struct s ((a [struct t (* 2 N)])))"
"struct t a[2 * N]")))
;; ...and an index after the first was dropped ;; `sizeof' takes a type or an expression, and `(* x)' is either.
(test-group "subscripts"
(test-assert "each index subscripts what the one before it gave"
(emits? (in-fn "(var m [int 2 3]) (= [m 1 2] a)") "m[1][2] = a;"))
(test-assert "which is an element to inference"
(emits? (in-fn "(var m [int 2 3]) (var e _ [m 1 2])") "int e = m[1][2];"))
(test-assert "and an expression to sizeof"
(emits? (in-fn "(var m [int 2 3]) (var n size-t (sizeof [m 1 1]))") "sizeof(m[1][1])"))
(test-assert "nested by hand it is the same"
(emits? (in-fn "(var m [int 2 3]) (= [[m 1] 2] a)") "m[1][2] = a;")))
;; `sizeof' takes a type or an expression, and `(* x)' is either.
;; What is in scope says which: a name C alone knows is a type ;; What is in scope says which: a name C alone knows is a type
(test-group "sizeof" (test-group "sizeof"
(test-assert "a pointer type" (test-assert "a pointer type"
@@ -1006,31 +809,6 @@
(test-assert "sixteen when that is enough" (test-assert "sixteen when that is enough"
(emits? (in-fn "(var d double 0.9871465422297019)") "d = 0.9871465422297019;"))) (emits? (in-fn "(var d double 0.9871465422297019)") "d = 0.9871465422297019;")))
;; A suffix is C's, and reached C inside |pipes|, the way CHICKEN
;; writes a symbol that starts with a digit
(test-group "suffixed literals"
(test-assert "an integer keeps its suffix"
(emits? (in-fn "(var n (unsigned long long) 1ULL)") "n = 1ULL;"))
(test-assert "and is written in decimal, which C11 has a suffix for"
(emits? (in-fn "(var n (unsigned int) 0b101u)") "n = 5u;"))
(test-assert "a float keeps its digits, which a double would round"
(emits? (in-fn "(var x (long double) 3.14159265358979323846264338327950288L)")
"x = 3.14159265358979323846264338327950288L;"))
(test-assert "a hex float is written as it was"
(emits? (in-fn "(var x double 0x1.8p3)") "x = 0x1.8p3;"))
(test-assert "suffix and all"
(emits? (in-fn "(var x float -0x1p-2f)") "x = -0x1p-2f;"))
(test-assert "grouped digits reach C ungrouped"
(emits? (in-fn "(var x float 1_000.5f)") "x = 1000.5f;"))
(test-assert "a minus is C's own"
(emits? (in-fn "(var n (unsigned int) -1u)") "n = -1u;"))
(test-assert "a number too wide for long long is unsigned, and says so"
(emits? (in-fn "(var n (unsigned long long) 0xFFFFFFFFFFFFFFFF)")
"n = 18446744073709551615u;"))
(test-assert "the least long long is spelled as LLONG_MIN, and typed"
(emits? (in-fn "(var n _ -9223372036854775808)")
"long long n = -9223372036854775807 - 1;")))
;; A define's body was pasted unwalked, and unparenthesised: `cast' ;; A define's body was pasted unwalked, and unparenthesised: `cast'
;; stayed a call, and (* x D) regrouped with D's own operator ;; stayed a call, and (* x D) regrouped with D's own operator
(test-group "defines" (test-group "defines"
@@ -1073,52 +851,11 @@
"{pp->x, pp->y}")) "{pp->x, pp->y}"))
(test-assert "designated" (test-assert "designated"
(emits? (in-line "(var q (struct point) #(.y (. pp x)))") (emits? (in-line "(var q (struct point) #(.y (. pp x)))")
"{.y = pp->x}")) "{.y = pp->x}")))
;; [3] reached the writer as a subscript of one operand, and died
(test-assert "an element designated by its index"
(emits? (in-fn "(var xs [int 5] #([3] 1 [1] 2))") "{[3] = 1, [1] = 2}"))
(test-assert "among positional ones"
(emits? (in-fn "(var xs [int 5] #(7 [3] 1 9))") "{7, [3] = 1, 9}"))
(test-assert "and one with no value is an error"
(reports? (in-fn "(var xs [int 5] #(1 [3]))") "designated initializer without a value")))
(test-group "member access" (test-group "member access"
(test-assert "a value reads with a dot" (test-assert "a value reads with a dot"
(emits? (in-line "(= (. p x) 1)") "p.x = 1")) (emits? (in-line "(= (. p x) 1)") "p.x = 1"))
;; an indexed step was looked up as a field whole, so its type was
;; lost and the step after it guessed
(test-assert "an indexed step is its field's element"
(emits? poly-src "q->pts[2].y"))
(test-assert "and says so without a warning"
(not (warns? poly-src "cannot type")))
(test-assert "so a pointer element is read through"
(emits? poly-src "q->pp[0]->y"))
(test-assert "and every index of one is written"
(emits? poly-src "q->grid[1][2].x"))
;; a pointer to a pointer has no fields, so a path reads through
;; every pointer to the aggregate, where it wrote pp->x
(test-assert "a pointer to a pointer is read through"
(emits? "(struct pt ((x int))) (fn f ((pp (* * struct pt))) int (return (. pp x)))"
"(*pp)->x"))
(test-assert "however many there are"
(emits? "(struct pt ((x int))) (fn f ((p3 (* * * struct pt))) int (return (. p3 x)))"
"(*(*p3))->x"))
(test-assert "and typed through"
(emits? "(struct pt ((x float))) (fn f ((pp (* * struct pt))) void (var v _ (. pp x)))"
"float v = (*pp)->x"))
(test-assert "a method's receiver too"
(emits? (string-append "(record pt ((x int)))"
"(ops pt (fn get ((self (* pt))) int (return (. self x))))"
"(fn f ((pp (* * pt))) int (return (.get pp)))")
"ptːget(*pp)"))
;; only a written (* T) was a pointer, so a typedef of one read as a
;; value, and a method could not find its receiver's type
(test-assert "a typedef of a pointer reads with an arrow"
(emits? pt-ref-src "q->x"))
(test-assert "dereferences to what it points at"
(not (warns? pt-ref-src "cannot type")))
(test-assert "and calls its target's methods"
(emits? pt-ref-src "ptːget(q)"))
(test-assert "a pointer reads with an arrow" (test-assert "a pointer reads with an arrow"
(emits? (in-line "(= (. pp x) 1)") "pp->x = 1")) (emits? (in-line "(= (. pp x) 1)") "pp->x = 1"))
;; each step asks the type in hand, so one path may be both ;; each step asks the type in hand, so one path may be both
@@ -1147,14 +884,6 @@
(test-assert "which one step through it does not need" (test-assert "which one step through it does not need"
(not (warns? (in-fn "(var t (* struct tm) 0) (= (. t a) 1)") (not (warns? (in-fn "(var t (* struct tm) 0) (= (. t a) 1)")
"cannot type"))) "cannot type")))
(test-assert "but a struct declared here has only the fields it names"
(reports? (in-line "(= (. p z) 1)") "no field of this name"))
(test-assert "the last step included"
(reports? (in-line "(= (. lp a z) 1)") "no field of this name"))
(test-assert "an indexed one by its name"
(reports? (string-append "(struct v ((xs [int 2])))"
(in-fn "(var w (struct v)) (= (. w [ys 0]) 1)"))
"no field of this name"))
;; the arrow is `%->' and nothing else writes one, so a bare `->' ;; the arrow is `%->' and nothing else writes one, so a bare `->'
;; is an ordinary head -- a threading macro that nobody imported, ;; is an ordinary head -- a threading macro that nobody imported,
;; and a call like any other unknown ;; and a call like any other unknown
@@ -1175,53 +904,7 @@
(test-assert "ahead of it" (test-assert "ahead of it"
(let ((c (sex->c "(var f (fn ((x int)) int) (lambda ((x int)) int (return x)))"))) (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 "static int λ0_f (int x)")
(string-contains c "(*f)(int) = λ0_f")))) (string-contains c "(*f)(int) = λ0_f")))))
;; every compound literal lost its type at file scope, which is right
;; for a value and not for an array a pointer is set to: that is the
;; address of a static object, and its braces alone the pointer's own
(test-assert "an array a pointer is set to keeps its type"
(emits? "(var gp (* int) #([int 3] : 1 2 3))" "int * gp = (int [3]){1, 2, 3}"))
(test-assert "in a field named for it"
(emits? (string-append "(struct h ((p (* int)) (n int)))"
"(var g (struct h) #(.p #([int 2] : 1 2) .n 3))")
"{.p = (int [2]){1, 2}, .n = 3}"))
(test-assert "or one in its place"
(emits? (string-append "(struct h ((n int) (p (* int))))"
"(var g (struct h) #((struct h) : 3 #([int 2] : 1 2)))")
"{3, (int [2]){1, 2}}"))
;; #() is all zeros; {} says so only from C23, and {0} in C11
(test-assert "empty braces are zeros"
(emits? "(struct pt ((x int))) (var g (struct pt) #())" "struct pt g = {0};"))
(test-assert "in a function and in a compound literal as well"
(emits? (string-append "(struct pt ((x int)))"
"(fn f () void (var p (struct pt) #((struct pt) :)))")
"(struct pt){0}"))
(test-assert "inside other braces"
(emits? (string-append "(struct pt ((x int))) (struct h ((a (struct pt)) (n int)))"
"(var g (struct h) #(#() 1))")
"{{0}, 1}"))
(test-assert "and for a scalar"
(emits? (in-fn "(var n int #())") "int n = {0};"))
(test-assert "while a value is still its braces"
(emits? (string-append "(struct pt ((x int))) (struct h2 ((a (struct pt))))"
"(var g (struct h2) #(#((struct pt) : 1)))")
"h2 g = {{1}}")))
;; fmt-c kept the first star after a tag and dropped what followed it,
;; and took an enum's star for its list of values
(test-group "pointers to tagged types"
(test-assert "a const pointer to a struct stays const"
(emits? "(var q (const * struct what))" "struct what* const q;"))
(test-assert "and one in an array"
(emits? "(var a [const * struct what 4])" "struct what* const a[4];"))
(test-assert "a pointer to a pointer keeps both stars"
(emits? "(var pp (* * struct what))" "struct what* * pp;"))
(test-assert "so does a union's"
(emits? "(var u (const * union val))" "union val* const u;"))
(test-assert "a pointer to an enum is a pointer"
(emits? "(enum mood (glad sad)) (var e (* enum mood))" "enum mood* e;"))
(test-assert "and a const one"
(emits? "(enum mood (glad sad)) (var f (const * enum mood))" "enum mood* const f;")))
;; Toplevel forms used to be separated by a blank line unconditionally, ;; Toplevel forms used to be separated by a blank line unconditionally,
;; which spread a block of adjacent typedefs over twice the lines its ;; which spread a block of adjacent typedefs over twice the lines its

View File

@@ -1,4 +0,0 @@
#!/bin/sh
# Stands in for the C compiler: writes the arguments it was given, one
# to a line, to $CC_ARGUMENTS
printf '%s\n' "$@" > "$CC_ARGUMENTS"

View File

@@ -1,108 +0,0 @@
;;; What sexc makes of its command line.
;;;
;;; Everything after the first `--' is the C compiler's, word for word;
;;; `-o -' is stdout; --depfile writes a make rule. Each shows only in
;;; what a sexc process hands on, so each is checked on one. `cc' here
;;; stands in for the compiler and writes down the arguments it got.
;;;
;;; make check-command-line
(import scheme
(chicken base)
(chicken file)
(chicken io)
(chicken pathname)
(chicken process)
(chicken process-context)
(chicken string)
srfi-1
test)
(define sexc (or (get-environment-variable "SEXC") "../../sexc"))
(define scratch (create-temporary-directory))
(define (built name) (make-pathname scratch name))
(define cc-arguments-file (built "cc-arguments"))
(set-environment-variable! "CC_ARGUMENTS" cc-arguments-file)
(define cc-option (string-append "--c-compiler=" (make-pathname (current-directory) "cc")))
;;; The lines sexc prints when run with ARGS and INPUT on its stdin, or
;;; #f when it fails
(define (output-with-input input . args)
(let ((proc (process sexc args)))
(display input (process-input-port proc))
(close-output-port (process-input-port proc))
(let ((lines (read-lines (process-output-port proc))))
(process-wait proc)
(and (process-returned-normally? proc)
(zero? (process-exit-status proc))
lines))))
(define (output-of . args)
(apply output-with-input "" args))
(define (cc-arguments)
(call-with-input-file cc-arguments-file read-lines))
;;; ("-o" "a" "/tmp/x.c" "-lm") -> ("-lm")
(define (past-c-file arguments)
(cdr (find-tail (lambda (a) (equal? (pathname-extension a) "c")) arguments)))
;;; What the compiler got past sexc's own -o and .c file, when sexc
;;; compiles with ARGS
(define (cc-tail . args)
(and (apply output-of cc-option args)
(past-c-file (cc-arguments))))
(define hello (string-intersperse (call-with-input-file "hello.sex" read-lines) "\n"))
(test-group "--"
;; `OpenGL' has no dash, and was once dropped for it, leaving
;; -framework to swallow whatever came next
(test "what follows reaches the compiler as written"
'("-framework" "OpenGL" "-Wall")
(cc-tail "hello.sex" "-o" (built "a") "--" "-framework" "OpenGL" "-Wall"))
(test "what precedes stays with sexc"
(list "-o" (built "a"))
(begin (cc-tail "hello.sex" "-o" (built "a") "--" "-lm")
(take (cc-arguments) 2)))
(test "without one the compiler gets nothing more"
'()
(cc-tail "hello.sex" "-o" (built "a")))
(test "nor after a trailing one"
'()
(cc-tail "hello.sex" "-o" (built "a") "--"))
;; ld takes a `--' of its own
(test "only the first one separates"
'("-Wl,--as-needed" "--" "-lm")
(cc-tail "hello.sex" "-o" (built "a") "--" "-Wl,--as-needed" "--" "-lm"))
(test "a file after it is the compiler's, and the source is stdin"
'("extra.o")
(and (output-with-input hello cc-option "-o" (built "a") "--" "extra.o")
(past-c-file (cc-arguments)))))
;;; getopt-long reads a lone `-' as an option, and refused `-o -'
(test-group "-o -"
(test-assert "writes the C to stdout"
(member "int main (void) {" (or (output-of "hello.sex" "-C" "-o" "-") '())))
(test-assert "and so does --output -"
(member "int main (void) {" (or (output-of "hello.sex" "-C" "--output" "-") '()))))
;;; The rules for the modules a unit imports are checked in tests/modules
(test-group "--depfile"
(copy-file "hello.sex" (built "a b.sex"))
(test "a space is escaped, the way make reads it"
(list (string-append (built "a\\ b.c") ": " (built "a\\ b.sex")))
(and (output-of (built "a b.sex") "-C" "-o" (built "a b.c")
(string-append "--depfile=" (built "a b.d")))
(call-with-input-file (built "a b.d") read-lines)))
(test "stdin is no file to depend on"
(list (string-append (built "hello.c") ":"))
(and (output-with-input hello "-C" "-o" (built "hello.c")
(string-append "--depfile=" (built "hello.d")))
(call-with-input-file (built "hello.d") read-lines))))
(delete-directory scratch #t)
(test-exit)

View File

@@ -1,2 +0,0 @@
(pub fn main () int
(return 0))

View File

@@ -5,7 +5,8 @@
;;; is checked here is what the compiler refuses, and that it refuses ;;; is checked here is what the compiler refuses, and that it refuses
;;; it with the name of whatever is wrong. ;;; it with the name of whatever is wrong.
;;; ;;;
;;; `in-fn' comes from codegen.scm, which run.scm includes first. ;;; `sex->c', `read-source', `failure-message', `emits?', `reports?'
;;; and `in-fn' come from codegen.scm, which run.scm includes first.
(import sex-modules) (import sex-modules)
@@ -15,7 +16,8 @@ ahead of its pub forms."
(check-public-interface (read-source source))) (check-public-interface (read-source source)))
(define (interface-reports? source fragment) (define (interface-reports? source fragment)
(fails-with? (lambda () (interface-of source)) fragment)) (let ((m (failure-message (lambda () (interface-of source)))))
(and m (string-contains m fragment) #t)))
(define (ops-src . body) (define (ops-src . body)
(string-append (string-append
@@ -42,6 +44,16 @@ ahead of its pub forms."
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) " "(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
(apply string-append body) ")")) (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" (test-group "encapsulation"
;; A record is a struct plus a typedef of its own name, so the bare ;; A record is a struct plus a typedef of its own name, so the bare
@@ -217,11 +229,7 @@ ahead of its pub forms."
(not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))" (not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
"t tːa ("))) "t tːa (")))
(test-assert "so it is a constant at file scope" (test-assert "so it is a constant at file scope"
(emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" (emits? "(sum t ((a ((x int)))))(var g t (t/a 1))" "static t g = (t){"))
"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" (test-assert "and an lvalue a method can take the address of"
(emits? (string-append (emits? (string-append
"(sum t ((a ((x int)))))" "(sum t ((a ((x int)))))"
@@ -246,12 +254,6 @@ ahead of its pub forms."
(test-assert "and as many as the field holds" (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)))" (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")) "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" (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)))" (reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))"
"an array field takes an array")) "an array field takes an array"))
@@ -269,12 +271,12 @@ ahead of its pub forms."
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer")) (reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
(test-assert "though it can point at itself" (test-assert "though it can point at itself"
(emits? "(sum box ((inner ((x (* box))))))" "box * x;")) (emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
(test-assert "a function fills a function-pointer field" (test-assert "a function argument becomes the closure its field holds"
(emits? (string-append (emits? (string-append
"(fn g ((n int)) int (return n))" "(fn g ((n int)) int (return n))"
"(sum t ((a ((k (fn ((int)) int))))))" "(sum t ((a ((k (closure ((int)) int))))))"
"(fn f () t (return (t/a g)))") "(fn f () t (return (t/a g)))")
"(struct tːa){g}")) "ƛint_int_fromfn(g)"))
(test-assert "a tag-only sum has no union at all" (test-assert "a tag-only sum has no union at all"
(not (emits? "(sum light ((red ()) (green ())))" "union"))) (not (emits? "(sum light ((red ()) (green ())))" "union")))
(test-assert "a sum is declared once" (test-assert "a sum is declared once"
@@ -286,17 +288,111 @@ ahead of its pub forms."
(test-assert "and is declared once" (test-assert "and is declared once"
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice"))) (reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
;; match is an if over the tag whose arms bind the payload. What ;; 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. ;; it refuses is why it exists.
(test-group "match" (test-group "match"
(test-assert "it tests the tag" (test-assert "it switches on the tag"
(emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))"
" ((empty ()) (= out 0.0)))") " ((empty ()) (= out 0.0)))")
"if (s.tag == shapeǂcircle)")) "switch (s.tag)"))
(test-assert "but not for the last variant, which is all that is left"
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))"
" ((empty ()) (= out 0.0)))")
"s.tag == shapeǂempty")))
(test-assert "an arm binds its payload" (test-assert "an arm binds its payload"
(emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))" (emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))"
" ((empty ()) (= out 0.0)))") " ((empty ()) (= out 0.0)))")
@@ -308,33 +404,28 @@ ahead of its pub forms."
").h"))) ").h")))
(test-assert "a scrutinee that is not a path is read once" (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)))") (emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))")
"shape λm0 = mk()")) "shape ƛm0 = mk()"))
(test-assert "a path scrutinee is not copied" (test-assert "a path scrutinee is not copied"
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") (not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"λm0"))) "ƛm0")))
(test-assert "unless a binder is named like a part of it"
(emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))")
"shape λm0 = s"))
(test-assert "a macro scrutinee is typed by what it expands to" (test-assert "a macro scrutinee is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)" (emits? (string-append "(defmacro (the a) a)"
(sum-src "(match (the s) ((circle (r)) (= out r))" (sum-src "(match (the s) ((circle (r)) (= out r))"
" (else (= out 0.0)))")) " (else (= out 0.0)))"))
"shape λm0 = s")) "shape ƛm0 = s"))
(test-assert "a typedef of a sum is matched as the sum" (test-assert "a typedef of a sum is matched as the sum"
(emits? (string-append (emits? (string-append
"(sum shape ((circle ((r int))) (empty ())))" "(sum shape ((circle ((r int))) (empty ())))"
"(typedef alias shape)" "(typedef alias shape)"
"(fn f () int (var s alias (shape/circle 1))" "(fn f () int (var s alias (shape/circle 1))"
" (match s ((circle (r)) (return r)) ((empty ()) (return 0))))") " (match s ((circle (r)) (return r)) ((empty ()) (return 0))))")
"s.tag == shapeǂcircle")) "case shapeǂcircle"))
(test-assert "else is the last branch, wherever it is written" (test-assert "else becomes default"
(let ((c (silently (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
(lambda () "default:"))
(sex->c (sum-src "(match s (else (= out 2.0)) ((circle (r)) (= out r)))"))))))
(< (string-contains c "out = r") (string-contains c "out = 2.0"))))
(test-assert "a comment between arms is dropped" (test-assert "a comment between arms is dropped"
(emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 2.0)))") (emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 0.0)))")
"out = 2.0")) "default:"))
(test-assert "a variant left out is an error" (test-assert "a variant left out is an error"
(reports? (sum-src "(match s ((circle (r)) (= out r)))") (reports? (sum-src "(match s ((circle (r)) (= out r)))")
@@ -343,7 +434,7 @@ ahead of its pub forms."
(reports? (sum-src "(match s ((circle (r)) (= out r)))") "rect")) (reports? (sum-src "(match s ((circle (r)) (= out r)))") "rect"))
(test-assert "else excuses the rest" (test-assert "else excuses the rest"
(emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))") (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"s.tag == shapeǂcircle")) "switch (s.tag)"))
(test-assert "a variant the sum does not have is an error" (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))" (reports? (sum-src "(match s ((circle (r)) (= out r)) ((square (w)) (= out w))"
" ((rect (w h)) (= out w)) ((empty ()) (= out 0.0)))") " ((rect (w h)) (= out w)) ((empty ()) (= out 0.0)))")
@@ -367,56 +458,14 @@ ahead of its pub forms."
(test-assert "not even as an argument" (test-assert "not even as an argument"
(reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))") (reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))")
"match is a statement")) "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" (test-assert "but a case body is a statement"
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))" (emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
" (else (= out 0.0)))))") " (else (= out 0.0)))))")
"s.tag == shapeǂcircle")) "switch (s.tag)"))
(test-assert "and so is a lambda's, wherever the lambda stands" (test-assert "and so is a closure's, wherever the closure stands"
(emits? (sum-src "(var c (fn ((shape)) int) (lambda ((v shape)) int" (emits? (sum-src "(var c (closure () int) (closure () int ((t s))"
" (match v ((circle (r)) (return 1)) (else (return 0)))))") " (match t ((circle (r)) (return 1)) (else (return 0)))))")
"v.tag == shapeǂcircle")) "switch (t.tag)"))
;; a pointer to one was refused, where `.' reads through one
;; a variant with fields is a member of the sum's union, which C
;; would not take named `int'
(test-assert "a variant named like a C keyword is refused"
(reports? "(sum tok ((int ((v int))) (other ())))" "a variant cannot be named like a C keyword"))
(test-assert "one without fields too, to keep one rule"
(reports? "(sum tok ((default ()) (other ())))" "a variant cannot be named like a C keyword"))
(test-assert "and stdbool's names count"
(reports? "(sum b ((true ()) (false ())))" "a variant cannot be named like a C keyword"))
(test-assert "a pointer to a sum is matched as the sum"
(emits? (sum-src "(var p (* shape) (& s))"
"(match p ((circle (r)) (= out r)) (else (= out 0.0)))")
"(*p).tag == shapeǂcircle"))
(test-assert "binding through it"
(emits? (sum-src "(var p (* shape) (& s))"
"(match p ((circle (r)) (= out r)) (else (= out 0.0)))")
"float r = (*p).u.circle.r"))
(test-assert "and through a chain of them"
(emits? (sum-src "(var p (* shape) (& s)) (var pp (* * shape) (& p))"
"(match pp ((circle (r)) (= out r)) (else (= out 0.0)))")
"(*(*pp)).tag == shapeǂcircle"))
(test-assert "and a scrutinee that is not a sum" (test-assert "and a scrutinee that is not a sum"
(reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))"
"match wants a sum"))) "match wants a sum")))
@@ -443,18 +492,6 @@ ahead of its pub forms."
(test "nor a private fn's" (test "nor a private fn's"
'() '()
(interface-of "(record cell ((v int))) (fn f ((c cell)) void)")) (interface-of "(record cell ((v int))) (fn f ((c cell)) void)"))
;; importers are given the declaration, not the initializer, so `_'
;; reached them unsolved: `extern _ n'
(test-assert "a pub var's type is written out"
(interface-reports? "(pub var n _ 42)" "write it out"))
(test-assert "all of it"
(interface-reports? "(pub var p (* _) 0)" "write it out"))
(test "a private one is solved where it is"
'()
(interface-of "(var n _ 42)"))
(test-assert "a pub sum's variants are looked at past its docstring"
(interface-reports? "(record cell ((v int))) (pub sum s \"doc\" ((a ((c cell))) (b ())))"
"held by value"))
(test-assert "held by value it is an error" (test-assert "held by value it is an error"
(interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))" (interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))"
"held by value")) "held by value"))
@@ -466,15 +503,6 @@ ahead of its pub forms."
"held by value")) "held by value"))
(test-assert "returned" (test-assert "returned"
(interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value")) (interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value"))
(test-assert "or taken by a function a pub one takes"
(interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn ((c cell)) void))) void)"
"held by value"))
(test-assert "or returned by one"
(interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn () cell))) void)"
"held by value"))
(test "but a pointer there is still a pointer"
'((record cell))
(interface-of "(record cell ((v int))) (pub fn take ((cb (fn ((c (* cell))) void))) void)"))
(test-assert "or taken by a pub method" (test-assert "or taken by a pub method"
(interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))" (interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))"
"held by value")) "held by value"))

26
tests/exit-code/Makefile Normal file
View File

@@ -0,0 +1,26 @@
# The failure paths.
#
# Both need a process to show themselves, so neither fits the unit
# suite: sexc has to fail when cc fails -- exiting 0 after a failed
# compile makes every driver, sextest included, read it as success --
# and it has to clean up its temporary .c when its own emission throws.
#
# Everything is built inside a scratch TMPDIR, so nothing is left here
# to clean up.
SEXC ?= ../../sexc
check:
@d=`mktemp -d`; \
TMPDIR=$$d $(SEXC) nested-pointer.sex -o $$d/out >/dev/null 2>&1; \
if [ -n "`find $$d -name '*.c'`" ]; then \
echo "exit code FAILED: the temporary .c survived a failed emission"; \
rm -rf $$d; exit 1; \
fi; \
if $(SEXC) hello.sex -o $$d/out -- -no-such-cc-flag >/dev/null 2>&1; then \
echo "exit code FAILED: sexc reported success after cc failed"; \
rm -rf $$d; exit 1; \
fi; \
rm -rf $$d; echo "exit code ok"
.PHONY: check

View File

@@ -1,151 +0,0 @@
;;; The failure paths.
;;;
;;; Each needs a process to show itself, so none fits the unit suite:
;;; sexc has to fail when cc fails -- exiting 0 after a failed compile
;;; makes every driver, sextest included, read it as success -- it has to
;;; clean up its temporary .c, and any output it began, when its own
;;; emission throws, and it has to
;;; refuse `-o -' for an executable, which cc would write to a file named
;;; `-'.
;;;
;;; Everything is built inside a scratch directory, so nothing is left
;;; here to clean up.
;;;
;;; make check-exit-code
(import scheme
(chicken base)
(chicken file)
(chicken io)
(chicken pathname)
(chicken process)
(chicken process-context)
(chicken string)
test)
;;; A path stays good past the change of directory below; a bare name
;;; is looked up on PATH
(define sexc
(let ((path (or (get-environment-variable "SEXC") "../../sexc")))
(if (or (absolute-pathname? path) (not (substring-index "/" path)))
path
(make-pathname (current-directory) path))))
(define scratch (create-temporary-directory))
(define out (make-pathname scratch "out"))
(set-environment-variable! "TMPDIR" scratch)
;;; (status stdout stderr) of sexc run with ARGS, and INPUT, when one
;;; is given, on its stdin
(define (sexc-run input . args)
(let ((proc (process* sexc args)))
(when input (display input (process-input-port proc)))
(close-output-port (process-input-port proc))
(let* ((text (lambda (s) (if (eof-object? s) "" s)))
(out (text (read-string #f (process-output-port proc))))
(err (text (read-string #f (process-error-port proc)))))
(process-wait proc)
(list (process-exit-status proc) out err))))
;;; (status) of PROGRAM run on its own
(define (sexc-run-program program)
(let ((proc (process* program (list))))
(close-output-port (process-input-port proc))
(read-string #f (process-output-port proc))
(process-wait proc)
(list (process-exit-status proc))))
;;; Whether sexc exits 0 when run with ARGS, saying nothing of it
(define (sexc-succeeds? . args)
(zero? (system (string-append (string-intersperse (map qs (cons sexc args)))
" >/dev/null 2>&1"))))
;;; Every check below expects a failure, which a sexc that cannot run
;;; gives too
(test "sexc compiles a program" #t
(sexc-succeeds? "hello.sex" "-o" out))
(test "a failed emission leaves no temporary .c" '()
(begin
(sexc-succeeds? "nested-pointer.sex" "-o" out)
(glob (make-pathname scratch "*.c"))))
;; and none of a file it was writing out, which make would take for done
(test "a failed emission leaves no part of its output" #f
(begin
(sexc-succeeds? "nested-pointer.sex" "-C" "-o" (make-pathname scratch "out.c"))
(file-exists? (make-pathname scratch "out.c"))))
(test "a failed cc fails sexc" #f
(sexc-succeeds? "hello.sex" "-o" out "--" "-no-such-cc-flag"))
(define hello (make-pathname (current-directory) "hello.sex"))
(define hello-source (call-with-input-file hello (lambda (p) (read-string #f p))))
;;; getopt-long read a lone `-' as an option it did not know, and died
(test-assert "- is stdin"
(let ((run (sexc-run hello-source "-" "-C" "-o" "-")))
(and (zero? (car run)) (substring-index "main" (cadr run)) #t)))
(change-directory scratch)
;;; the second was never read, and nothing said so
(test-assert "a second input is refused"
(let ((run (sexc-run #f hello hello "-C" "-o" "-")))
(and (not (zero? (car run)))
(substring-index "one input file at a time" (caddr run))
#t)))
(test-assert "stdin besides a file too"
(let ((run (sexc-run hello-source "-" hello "-C" "-o" "-")))
(and (not (zero? (car run)))
(substring-index "one input file at a time" (caddr run))
#t)))
(test "-o - is refused for an executable" #f
(sexc-succeeds? hello "-o" "-"))
(test "and leaves no file named -" #f
(file-exists? "-"))
;;; -o naming the source overwrote it, whatever was asked for
(call-with-output-file "victim.sex" (lambda (p) (display hello-source p)))
(test-assert "an output naming the source is refused"
(let ((run (sexc-run #f "victim.sex" "-C" "-o" "./victim.sex")))
(and (not (zero? (car run)))
(substring-index "would overwrite its source" (caddr run))
#t)))
(test "and the source is as it was" hello-source
(call-with-input-file "victim.sex" (lambda (p) (read-string #f p))))
;;; A compiler is named with its own options, as make's CC is: SEX_CC
;;; "cc -DCODE=7" went looking for an executable of that whole name
(call-with-output-file "code.sex" (lambda (p) (display "(pub fn main () int (return CODE))" p)))
(test "a compiler given with options takes them"
7
(begin
(set-environment-variable! "SEX_CC" "cc -DCODE=7")
(let ((built (sexc-succeeds? "code.sex" "-o" "code")))
(unset-environment-variable! "SEX_CC")
(and built (car (sexc-run-program "./code"))))))
;;; An error is its message: CHICKEN's call history after it is for
;;; working on sexc itself, and asked for by SEXC_DEBUG
(test-assert "a missing input says so"
(let ((run (sexc-run #f "no-such.sex")))
(and (not (zero? (car run)))
(substring-index "no-such.sex: no such file" (caddr run))
(not (substring-index "Call history" (caddr run))))))
(test-assert "and any error is its message alone"
(let ((run (sexc-run "(fn f () int (return \"\\q\"))" "-C" "-o" "-")))
(and (= 70 (car run))
(substring-index "Error: stdin:1: unknown escape" (caddr run))
(not (substring-index "Call history" (caddr run))))))
(test-assert "unless the history is asked for"
(begin
(set-environment-variable! "SEXC_DEBUG" "1")
(let ((run (sexc-run "(fn f () int (return \"\\q\"))" "-C" "-o" "-")))
(unset-environment-variable! "SEXC_DEBUG")
(and (substring-index "Call history" (caddr run)) #t))))
(delete-directory scratch #t)
(test-exit)

View File

@@ -0,0 +1,3 @@
(module fmt-c-writer
*
"../fmt-c-writer.scm")

View File

@@ -1,132 +1,192 @@
;;; The C each declaration comes out as: names, types, variables, ;;; Types
;;; initializers, functions and structs. Non-pub ones are static, which (test-group "fmt-writer"
;;; the fragments leave out.
(test-group "fmt-c-writer" (test
'(const int)
(walk-type '(const int)))
(test-group "names" (test
(test-assert "kebab case is snake case" '(%array (const char) 512)
(emits? "(var kebab-case int)" "int kebab_case;")) (walk-type '(¤ const char 512)))
;; A Lisp predicate and mutator, in letters C takes
(test-assert "a predicate"
(emits? "(var ident-start? int)" "int ident_startʔ;"))
(test-assert "a mutator"
(emits? "(var reset! int)" "int resetꜝ;"))
;; The `regex' egg's string-substitute dropped one trailing character
;; per multi-byte one, and the C still compiled under the new name
(test-assert "a non-ASCII name survives"
(emits? "(var naïve-count int)" "int naïve_count;"))
(test-assert "wherever the dash is"
(emits? "(var aï-b int)" "int aï_b;"))
(test-assert "or with none"
(emits? "(var ïï int)" "int ïï;"))
(test-assert "an arrow inside a name is C's"
(emits? "(fn f () void (= this->member 1))" "this->member = 1;")))
;; The operators spelled with the characters names are converted from (test
(test-group "operators" '(%array (float) 512)
(test-assert "-=" (walk-type '(¤ (float) 512)))
(emits? "(fn f ((a int) (b int)) void (-= a b))" "a -= b;"))
(test-assert "!"
(emits? "(fn f ((a int)) void (if (! a) (return)))" "if (!a)"))
(test-assert "!="
(emits? "(fn f ((a int) (b int)) void (if (!= a b) (return)))" "if (a != b)")))
(test-group "toplevel comments" (test
(test-assert "are C comments" '(%array (const char) 512)
(emits? ";; hi" "/* hi */")) (walk-type '(¤ (const char) 512)))
(test-assert "without the markers or the padding"
(emits? ";;; Foo " "/* Foo */")))
(test-group "types" (test
(test-assert "an array" '(%array (const char))
(emits? "(var a [const char 512])" "const char a[512];")) (walk-type '(¤ const char)))
(test-assert "whose element type is grouped"
(emits? "(var c [(const char) 512])" "const char c[512];"))
(test-assert "an unsized one"
(emits? "(extern var d [const char])" "extern const char d[];"))
(test-assert "a pointer to const"
(emits? "(var p (* const char))" "const char * p;"))
(test-assert "a const pointer to const"
(emits? "(var q (const * const char))" "const char * const q;"))
(test-assert "a function pointer"
(emits? "(var fp (fn ((int) (float) [const * struct what]) void))"
"void (*fp)(int, float, struct what* const []);"))
(test-assert "taking an array"
(emits? "(var fq (fn ((int) [float]) void))"
"void (*fq)(int, float []);"))
(test-assert "an array of them"
(emits? "(extern var fa [(fn ((int) [float]) void)])"
"extern void (*fa[])(int, float []);")))
(test-group "variables" (test
(test-assert "a local array" '(%array (const char))
(emits? "(fn f () void (var a [float 8]))" "float a[8];")) (walk-type '(¤ (const char))))
(test-assert "a pointer, initialized"
(emits? "(fn f () void (var n int) (var b (* int) (& n)))" "int * b = &n;"))
(test-assert "a pointer to const"
(emits? "(fn f () void (var n int) (var c (* const int) (& n)))"
"const int * c = &n;"))
(test-assert "a struct"
(emits? "(fn f () void (var s (struct suc)))" "struct suc s;"))
(test-assert "a pointer to a const struct"
(emits? "(fn f ((s1 (* const struct suc))) void (var t (* const struct suc) s1))"
"const struct suc * t = s1;"))
(test-assert "grouped"
(emits? "(fn f ((s1 (* const struct suc))) void (var u (* (const struct suc)) s1))"
"const struct suc * u = s1;"))
(test-assert "a struct from a call"
(emits? "(fn f () void (var v (struct suc) (hoge piyo)))"
"struct suc v = hoge(piyo);"))
(test-assert "a pointer to one"
(emits? "(fn f () void (var w (* struct suc) (hoge piyo)))"
"struct suc* w = hoge(piyo);")))
(test-group "initializers" (test
(test-assert "a bare one is braces" '(%array float 8)
(emits? "(fn f () void (var a [int 2] #(1 2)))" "int a[2] = {1, 2};")) (walk-type '(¤ float 8)))
(test-assert "`:' ends the type and makes it a compound literal"
(emits? "(fn f () void (var p (struct point) #(struct point : 3 4)))"
"struct point p = (struct point){3, 4};"))
(test-assert "the type is bare words, as everywhere else"
(emits? "(fn f () void (var s (* const char) #(* const char : 65)))"
"const char * s = (const char *){65};"))
(test-assert "and may be an array type"
(emits? "(fn f () void (var t [int 3] #([int 3] : 10 20 30)))"
"int t[3] = (int [3]){10, 20, 30};"))
(test-assert "`.field value' is a designated initializer, kebab and all"
(emits? "(fn f () void (var n (struct named) #(struct named : .n 7 .first-name \"zoe\")))"
"(struct named){.n = 7, .first_name = \"zoe\"}"))
(test-assert "positional and designated may be mixed"
(emits? "(fn f () void (var m (struct point) #(struct point : 1 .y 5)))"
"(struct point){1, .y = 5}"))
(test-assert "designators work in an untyped initializer too"
(emits? "(fn f () void (var o (struct point) #(.y 5)))"
"struct point o = {.y = 5};")))
(test-group "functions" (test
(test-assert "a prototype may leave its parameters nameless" "Pointer to const char"
(emits? "(fn puk ((int) [float 8]) void)" "void puk (int, float [8]);")) '(const char *)
(test-assert "an array parameter" (walk-type '(* const char)))
(emits? "(fn g ((argc int) (argv [const char])) int (return 0))"
"int g (int argc, const char argv[]) {"))
(test-assert "a pointer parameter"
(emits? "(fn quxu ((bar (* struct piq))) int (return 0))"
"int quxu (struct piq * bar) {"))
(test-assert "an array of pointers"
(emits? "(fn quxu ((bar (* struct piq)) (ploop [* struct tt])) int (return 0))"
"int quxu (struct piq * bar, struct tt* ploop[]) {")))
(test-group "structs" (test
(test-assert "names are converted" "Const pointer to const char"
(emits? "(struct no-kebab ((a int) (f float)))" '(const char * const)
"struct no_kebab {\n int a;\n float f;\n};")) (walk-type '(const * const char)))
(test-assert "fields sharing a type share a line, and a field may be a struct"
(emits? "(struct settings ((x y w h u32) (colors [struct ((r g b a float)) 4])))" (test
"struct settings {\n u32 x, y, w, h;\n struct{\n float r, g, b, a;\n } colors[4];\n};")) '(%fun void (int float (%array (struct what * const))))
(test-assert "a named one" (walk-type '(fn ((int) (float) (¤ (const * struct what))) void)))
(emits? "(struct settings ((x y w h u32) (colors [struct color ((r g b a float)) 4])))"
" struct color{\n float r, g, b, a;\n } colors[4];")) (test
(test-assert "or a function pointer" '(%fun void (int (%array float) (%array (struct what * const))))
(emits? "(struct mega-kebab ((a int) (min (fn ((int) [int]) bool))))" (walk-type '(fn ((int) (¤ float) (¤ (const * struct what))) void)))
" bool (*min)(int, int []);"))))
(test
'(%array (%fun void (int (%array float) (%array (struct what * const)))))
(walk-type '(¤ (fn ((int) (¤ float) (¤ (const * struct what))) void))))
;; Type convert to C
(test
'(int)
(type-convert-to-c '(int)))
(test
'(* int)
(type-convert-to-c '(int *)))
(test
'(* const int)
(type-convert-to-c '(const int *)))
(test
'(const * const char)
(type-convert-to-c '(const char * const)))
;;; Variable defs
(test
'(%var (%array float 8) a)
(walk-var '(var a (¤ float 8))))
(test
'(%var (int *) a (& n))
(walk-var '(var a (* int) (& n))))
(test
'(%var (const int *) a (& n))
(walk-var '(var a (* const int) (& n))))
(test
'(%var (struct suc) s)
(walk-var '(var s (struct suc))))
(test
'(%var (const struct suc *) s s1)
(walk-var '(var s (* const struct suc) s1)))
(test
'(%var (const struct suc *) s s1)
(walk-var '(var s (* (const struct suc)) s1)))
(test
'(%var (struct suc) s (hoge piyo))
(walk-var '(var s (struct suc) (hoge piyo))))
(test
'(%var (struct suc *) s (hoge piyo))
(walk-var '(var s (* struct suc) (hoge piyo))))
;;; Initializers and compound literals
(test "a bare initializer is unchanged"
'#(1 2)
(walk-expr '#(1 2)))
(test "`:' ends the type and makes it a compound literal"
'(%compound (struct point) 3 4)
(walk-expr '#(struct point : 3 4)))
(test "the type is bare words, as everywhere else"
'(%compound (const char *) 65)
(walk-expr '#(* const char : 65)))
(test "and may be an array type"
'(%compound (%array int 3) 10 20 30)
(walk-expr '#(¤ int 3 : 10 20 30)))
(test "a grouped type is unwrapped the way a declaration's is"
'(%compound (%array int 3) 10)
(walk-expr '#((¤ int 3) : 10)))
(test "`.field value' is a designated initializer, kebab and all"
'(%compound (struct named) (%designate n 7) (%designate first_name "zoe"))
(walk-expr '#(struct named : .n 7 .first-name "zoe")))
(test "positional and designated may be mixed"
'(%compound (struct point) 1 (%designate y 5))
(walk-expr '#(struct point : 1 .y 5)))
(test "designators work in an untyped initializer too"
'#((%designate y 5))
(walk-expr '#(.y 5)))
;;; Fn defs
(test
'(%fun void puk ((int #f) ((%array float 8) #f)))
(walk-fn-def '(fn puk ((int) (¤ float 8)) void)))
(test
'(%fun int main ((int argc) ((%array (const char)) argv))
(return 0))
(walk-fn-def
'(fn main ((argc int) (argv (¤ const char))) int
(return 0))))
(test
'(%fun int quxu (((struct piq *) bar))
(return 0))
(walk-fn-def
'(fn quxu ((bar (* struct piq))) int
(return 0))))
(test
'(%fun int quxu (((struct piq *) bar) ((%array (struct tt *)) ploop))
(return 0))
(walk-fn-def
'(fn quxu ((bar (* struct piq)) (ploop (¤ * struct tt))) int
(return 0))))
;; Structs
(test
'(struct no_kebab ((int a) (float f)))
(walk-struct '(struct no-kebab ((a int) (f float)))))
(test
'(struct settings ((u32 x y w h)
((%array (struct ((float r g b a))) 4) colors)))
(walk-struct
'(struct settings
((x y w h u32)
(colors [¤ struct ((r g b a float)) 4])))))
(test
'(struct settings ((u32 x y w h)
((%array (struct color ((float r g b a))) 4) colors)))
(walk-struct
'(struct settings
((x y w h u32)
(colors [¤ struct color ((r g b a float)) 4])))))
(test
'(struct mega_kebab ((int a)
((struct ((int year) (int month) (int day))) dob)
((%fun bool (int (%array int))) min)))
(walk-struct '(struct mega-kebab
((a int)
(dob (struct ((year int)
(month int)
(day int))))
(min (fn ((int) (¤ int)) bool)))))))

45
tests/infer.module.scm Normal file
View File

@@ -0,0 +1,45 @@
(module infer
(;; The IR
tvar?
tvar-id
tvar-classes
tvar-rigid?
fresh-tvar
fresh-rigid-tvar
prim-type? prim-name prim-quals make-prim
ptr-type? ptr-target ptr-quals make-ptr
array-type? array-elt array-size make-array-type
fn-type? fn-ret fn-args fn-variadic? make-fn-type
agg-type? agg-kind agg-name agg-spelling agg-quals make-agg
alias-type? alias-name alias-expansion alias-quals make-alias
unknown-type? the-unknown-type
resolve
underlying
c-primitive?
type-quals
free-tvars
decay
;; The boundary
parse-type
unparse-type
;; Constraints
register-class!
add-instance!
entails?
default-tvar!
default-type-variables!
;; Unification
unify
;; Type schemes
scheme? scheme-vars scheme-constraints scheme-type
make-scheme
generalize
instantiate
substitute)
"../infer.scm")

View File

@@ -3,7 +3,7 @@
;;; Names registered in the type database are prefixed, since the ;;; Names registered in the type database are prefixed, since the
;;; database is one table shared by every suite in the linked binary. ;;; database is one table shared by every suite in the linked binary.
(import infer types) (import infer types (chicken sort))
;;; Parse and print a surface type again. Everything in this suite goes ;;; Parse and print a surface type again. Everything in this suite goes
;;; through this pair, which is deliberate: they are the only thing the ;;; through this pair, which is deliberate: they are the only thing the
@@ -85,10 +85,23 @@
;; Each _ is its own variable: solving one must not solve the rest. ;; Each _ is its own variable: solving one must not solve the rest.
(let ((t (parse-type '(fn ((_)) _)))) (let ((t (parse-type '(fn ((_)) _))))
(unify t (parse-type '(fn ((int)) _)) #f) (unify (car (fn-args t)) (parse-type 'int) #f)
(test "one hole at a time" '(fn ((int)) _) (unparse-type t)))) (test "one hole at a time" '(fn ((int)) _) (unparse-type t))))
(test-group "decay" (test-group "structure"
(test-assert "a pointer is a pointer" (ptr-type? (parse-type '(* char))))
(test "and knows what it points at" 'char
(unparse-type (ptr-target (parse-type '(* char)))))
(test "quals sit on the level they were written at" '(const)
(ptr-quals (parse-type '(const * char))))
(test "an unsized array has no size" #f (array-size (parse-type '(¤ int))))
(test "a sized one does" 16 (array-size (parse-type '(¤ int 16))))
(test "an aggregate is nominal" 'point (agg-name (parse-type '(struct point))))
(test-assert "a variadic signature says so"
(fn-variadic? (parse-type '(fn ((* const char) (...)) int))))
(test-assert "and a plain one does not"
(not (fn-variadic? (parse-type '(fn ((int)) int)))))
;; decay: the conversion C performs at a call site, an operand of ;; decay: the conversion C performs at a call site, an operand of
;; `+', or the left half of a subscript. ;; `+', or the left half of a subscript.
(test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16))))) (test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16)))))
@@ -102,7 +115,7 @@
(test-error "and not with another one" (test-error "and not with another one"
(unify (parse-type 'int) (parse-type 'char) #f)) (unify (parse-type 'int) (parse-type 'char) #f))
(let ((a (parse-type '_))) (let ((a (fresh-tvar)))
(unify a (parse-type '(* const char)) #f) (unify a (parse-type '(* const char)) #f)
(test "a variable takes the shape it is unified with" (test "a variable takes the shape it is unified with"
'(* const char) (unparse-type a))) '(* const char) (unparse-type a)))
@@ -112,8 +125,8 @@
(unify p (parse-type '(* int)) #f) (unify p (parse-type '(* int)) #f)
(test "a partial type is completed by one step" '(* int) (unparse-type p))) (test "a partial type is completed by one step" '(* int) (unparse-type p)))
(let ((a (parse-type '_)) (let ((a (fresh-tvar))
(b (parse-type '_))) (b (fresh-tvar)))
(unify a b #f) (unify a b #f)
(unify b (parse-type 'double) #f) (unify b (parse-type 'double) #f)
(test "two variables joined then solved" 'double (unparse-type a))) (test "two variables joined then solved" 'double (unparse-type a)))
@@ -139,7 +152,168 @@
(add-typedef 'i-count '(typedef i-count int)) (add-typedef 'i-count '(typedef i-count int))
(test-assert "a typedef unifies with its target" (test-assert "a typedef unifies with its target"
(unify (parse-type 'i-count) (parse-type 'int) #f)) (unify (parse-type 'i-count) (parse-type 'int) #f))
(let ((a (parse-type '_))) (let ((a (fresh-tvar)))
(unify a (parse-type 'i-count) #f) (unify a (parse-type 'i-count) #f)
(test "and keeps its name when it is the one printed" (test "and keeps its name when it is the one printed"
'i-count (unparse-type a))))) 'i-count (unparse-type a)))
(test-group "the unknown type"
(test-assert "? is consistent with anything"
(unify the-unknown-type (parse-type '(struct point)) #f))
(test-assert "in either order"
(unify (parse-type 'int) the-unknown-type #f))
;; ...and binds nothing. Degrading to ? is what keeps an
;; unparsed C declaration from poisoning everything it touches.
(let ((a (fresh-tvar)))
(unify a the-unknown-type #f)
(test "a variable met with ? stays open" '_ (unparse-type a))))
(test-group "occurs check"
;; Unreachable without recursive types, and the alternative to
;; having it is not an error but a hang.
(let ((a (fresh-tvar)))
(test-error "a variable may not contain itself"
(unify a (make-ptr a (list)) #f))))
(test-group "rigid variables"
(let ((r (fresh-rigid-tvar))
(a (fresh-tvar)))
(test-error "a type parameter does not unify with a type"
(unify r (parse-type 'int) #f))
(test-assert "an ordinary variable binds to it instead"
(unify a r #f))
;; An unsolved variable resolves to itself.
(test-assert "it is still open" (tvar? (resolve r))))
;; ...and the same the other way round: it is which side is free
;; that decides, not which side was written first.
(let ((r (fresh-rigid-tvar))
(a (fresh-tvar)))
(test-assert "rigid first binds the free one" (unify r a #f))
(test-assert "to the parameter itself" (eq? r (resolve a))))
(let ((r1 (fresh-rigid-tvar))
(r2 (fresh-rigid-tvar)))
(test-error "two parameters do not unify with each other"
(unify r1 r2 #f)))))
(test-group "constraints"
(test #t (entails? 'numeric (parse-type 'int)))
(test #t (entails? 'numeric (parse-type '(unsigned long))))
(test #t (entails? 'integral (parse-type 'char)))
(test #f (entails? 'integral (parse-type 'double)))
(test #t (entails? 'floating (parse-type 'double)))
(test #f (entails? 'floating (parse-type 'int)))
(test #f (entails? 'numeric (parse-type '(* char))))
(test #t (entails? 'scalar (parse-type '(* char))))
(test #f (entails? 'numeric (parse-type 'void)))
(add-enum 'i-mood '(enum i-mood (glad sad)))
(test "an enum is an integer" #t (entails? 'integral (parse-type '(enum i-mood))))
;; The third answer, and the important one. A name from a header
;; might well be numeric; #f would reject working programs and #t
;; would invent knowledge.
(test "an unparsed C name is not known either way"
'unknown (entails? 'numeric (parse-type 'size-t)))
(test "nor is an open variable" 'unknown (entails? 'numeric (fresh-tvar)))
(test "? entails nothing, but says so quietly"
'unknown (entails? 'numeric the-unknown-type))
;; A typedef is entailed by what it resolves to, so an alias cannot
;; sneak past a constraint its target would fail.
(add-typedef 'i-len '(typedef i-len int))
(test "a typedef is judged by its target" #t (entails? 'numeric (parse-type 'i-len)))
;; A constrained variable checks its classes at the moment it is
;; solved, not at the end.
(let ((a (fresh-tvar '(numeric))))
(test-error "solving to a type that fails the class is an error"
(unify a (parse-type '(* char)) #f)))
(let ((a (fresh-tvar '(numeric))))
(test-assert "and to one that satisfies it is not"
(unify a (parse-type 'double) #f)))
;; ...but an unparsed name is not a failure, it is an absence of
;; knowledge, and must stay silent.
(let ((a (fresh-tvar '(numeric))))
(test-assert "an unparsed C name does not trip a constraint"
(unify a (parse-type 'GLuint) #f)))
;; Joining two variables joins what is known about both.
(let ((a (fresh-tvar '(numeric)))
(b (fresh-tvar '(integral))))
(unify a b #f)
(test "constraints merge when variables do"
'("integral" "numeric")
(sort (map symbol->string (tvar-classes b)) string<?)))
(test-group "defaulting"
(let ((a (fresh-tvar '(numeric))))
(default-type-variables! a #f)
(test "an open numeric is an int" 'int (unparse-type a)))
(let ((a (fresh-tvar '(floating))))
(default-type-variables! a #f)
(test "an open floating is a double" 'double (unparse-type a)))
(let ((a (fresh-tvar)))
(test "a variable with nothing known about it cannot be defaulted"
#f (default-type-variables! a #f))
(test "and stays a hole, for the caller to complain about"
'_ (unparse-type a)))
;; Defaulting reaches into the structure, since the hole may be
;; anywhere: `(var p (* _) ...)'.
(let ((t (parse-type '(* _))))
(unify (ptr-target t) (fresh-tvar '(numeric)) #f)
(default-type-variables! t #f)
(test "and it reaches inside a type" '(* int) (unparse-type t))))
(test-group "user classes"
;; A trait bound is the same shape as `numeric', discharged by
;; the same procedure -- that is the point of one representation.
;; It differs in two rules, and both are stated while there is
;; still only one kind of constraint to state them about.
(register-class! 'i-ord #f #f #t)
(add-struct 'i-circle '(struct i-circle ((r int))))
(test "no instance, no entailment" #f (entails? 'i-ord (parse-type '(struct i-circle))))
(add-instance! 'i-ord (parse-type '(struct i-circle)))
(test "and with one, entailment" #t (entails? 'i-ord (parse-type '(struct i-circle))))
;; Instances key on the resolved type, so an alias cannot be
;; registered twice under two names.
(add-typedef 'i-circle-alias '(typedef i-circle-alias (struct i-circle)))
(test "an alias of an instance is the same instance"
#t (entails? 'i-ord (parse-type 'i-circle-alias)))
;; Decision 2: static dispatch cannot select an instance for a
;; type it does not know, so a strict class says no to ? rather
;; than shrugging the way `numeric' does.
(test "a strict class refuses ?" #f (entails? 'i-ord the-unknown-type))
(test "where a lenient one abstains" 'unknown (entails? 'numeric the-unknown-type))
;; ...and it has no default to fall back on.
(let ((a (fresh-tvar '(i-ord))))
(test-error "an unresolved user constraint is an error, not a guess"
(default-type-variables! a #f)))))
(test-group "schemes"
;; Nothing generalizes yet. The shape is here because a scheme
;; without a constraint list is the wrong shape for every bounded
;; generic, and because instantiation is how a generic body gets
;; fresh cells instead of a second type for the same one.
(let* ((a (fresh-tvar '(numeric)))
(id (make-fn-type a (list a) #f))
(s (generalize id (list))))
(test "the free variable is quantified" 1 (length (scheme-vars s)))
(test "carrying its class as the scheme's context"
'((numeric)) (list (map car (scheme-constraints s))))
(let ((one (instantiate s))
(two (instantiate s)))
(test "an instantiation is still open" '(fn ((_)) _) (unparse-type one))
(unify (fn-ret one) (parse-type 'int) #f)
(test "solving one instantiation" '(fn ((int)) int) (unparse-type one))
(test "leaves the other alone" '(fn ((_)) _) (unparse-type two))
(test "and the scheme itself untouched" '(fn ((_)) _) (unparse-type id))))
(let* ((a (fresh-tvar))
(b (fresh-tvar))
(s (generalize (make-fn-type a (list b) #f) (list b))))
(test "a variable free in the environment is not quantified"
1 (length (scheme-vars s)))
(let ((inst (instantiate s)))
(unify (car (fn-args inst)) (parse-type 'char) #f)
(test "so instantiating solves it for everyone" 'char (unparse-type b))))))

View File

@@ -17,13 +17,14 @@
;;; get the true source line) and in the C output (to get the line the ;;; get the true source line) and in the C output (to get the line the
;;; directives claim). The two must agree. ;;; directives claim). The two must agree.
(import (chicken pathname) (import (chicken port)
(chicken port)
(chicken string) (chicken string)
srfi-1 srfi-1
srfi-13 srfi-13
fmt-c-writer fmt-c-writer
semen) reader
semen
utils)
;;; ------------------------------------------------------------------ ;;; ------------------------------------------------------------------
;;; Fixture. Line numbers are in the trailing comments; keep them ;;; Fixture. Line numbers are in the trailing comments; keep them
@@ -96,10 +97,16 @@
;;; ------------------------------------------------------------------ ;;; ------------------------------------------------------------------
;;; Pipeline and #line accounting ;;; Pipeline and #line accounting
(define (compile-to-c source #!optional (file "fixture.sex")) (define (compile-to-c source)
"Run reader -> semen -> writer on SOURCE, read from FILE, "Run reader -> semen -> writer on SOURCE, returning the generated C.
returning the generated C." parse-all is called directly rather than through read-raw-forms so the
(let ((forms (read-source source file))) fixture can be given a file name: a location carries one, and the
file is what makes an imported module report itself rather than the unit
that imported it."
(let ((forms (with-input-from-string source
(lambda ()
(parameterize ((current-source-file "fixture.sex"))
(parse-all (current-input-port)))))))
(with-output-to-string (with-output-to-string
(lambda () (emit-c (semen-process forms)))))) (lambda () (emit-c (semen-process forms))))))
@@ -231,26 +238,15 @@ after that is one more. Lines before the first directive get #f."
;; an `if' arm is a statement only where the `if' is one: a ;; an `if' arm is a statement only where the `if' is one: a
;; directive between `?' and `:' does not compile ;; directive between `?' and `:' does not compile
(maps "conditional argument" "123") (maps "conditional argument" "123")
;; a bare 123 may be a digit run of the fixture's path, in every #line
(test-assert "holds no directive" (test-assert "holds no directive"
(let ((start (string-contains c-out "mvar < 123"))) (let ((start (string-contains c-out "123")))
(not (string-contains (substring c-out start (string-contains c-out ": 125" start)) (not (string-contains (substring c-out start (string-contains c-out "125" start))
"#line"))))) "#line")))))
;; A location is (file . line); every directive must name the file the ;; A location is (file . line); every directive must name the file the
;; form was read from. ;; form was read from.
(test-group "file name" (test-group "file name"
(test "every directive names the fixture" (test "every directive names the fixture"
(list "fixture.sex") (list "\"fixture.sex\"")
(delete-duplicates (delete-duplicates
(map (lambda (quoted) (filter values (map directive-file (split-lines c-out)))))))
(pathname-strip-directory (string-trim-both quoted #\")))
(filter values (map directive-file (split-lines c-out))))))
;; it was pasted between quotes as it came: a quote ended it, a
;; backslash began an escape, and ??= was a trigraph
(test-assert "and is written the way C writes a string"
(string-suffix? "/we\\\"ird\\\\a?\\?=.sex\""
(directive-file
(find directive-line
(split-lines (compile-to-c "(fn f () int (return 1))"
"we\"ird\\a??=.sex"))))))))

View File

@@ -1,38 +1,22 @@
;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the ;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the
;;; start, from the directory sexc was started in. ;;; start, from the directory sexc was started in.
(import (chicken file) (import (chicken pathname)
(chicken pathname)
(chicken process-context) (chicken process-context)
semen
sex-modules) sex-modules)
(define (write-module dir name)
(create-directory dir #t)
(with-output-to-file (make-pathname dir name "sex")
(lambda () (display "(pub fn found () int)"))))
(test-group "module path" (test-group "module path"
;; make-absolute-pathname took `src' for a directory under the root, ;; make-absolute-pathname took `src' for a directory under the root,
;; and an import searched /src/ ;; and an import searched /src/
(let ((start (current-directory)) (set-environment-variable! "SEX_MODULE_PATH" "src:/abs/lib")
(scratch (create-temporary-directory))) (load-persistent-module-paths)
(write-module (make-pathname scratch "src") "mp-relative") (test "a relative entry is from the working directory"
(write-module (make-pathname scratch "lib") "mp-absolute") (make-absolute-pathname (current-directory) "src")
(change-directory scratch) (second (get-module-paths)))
(set-environment-variable! "SEX_MODULE_PATH" (test "an absolute one is as written"
(string-append "src:" (make-pathname scratch "lib"))) "/abs/lib"
(load-persistent-module-paths) (third (get-module-paths)))
(change-directory start)
(test "a relative entry is from the working directory" (set-environment-variable! "SEX_MODULE_PATH" "")
'((pub fn found () int)) (load-persistent-module-paths)
(semen-process '((import mp-relative)))) (unset-environment-variable! "SEX_MODULE_PATH"))
(test "an absolute one is as written"
'((pub fn found () int))
(semen-process '((import mp-absolute))))
(set-environment-variable! "SEX_MODULE_PATH" "")
(load-persistent-module-paths)
(unset-environment-variable! "SEX_MODULE_PATH")
(delete-directory scratch #t)))

55
tests/modules/Makefile Normal file
View File

@@ -0,0 +1,55 @@
# Multi-module linking.
#
# Modules are only testable end to end, and nothing else in the suite
# links more than one translation unit. Three things have to hold at
# once: an imported `pub fn' comes out as a prototype with external
# linkage, an imported `pub var' as an extern declaration, and the
# module's object survives being passed after `--'. Get any of them
# wrong and this fails to link -- or, in the `pub var' case, links and
# quietly counts into a private copy.
#
# It also checks what only a second translation unit can check: that an
# imported type reaches the type database, by expanding a macro that
# reads the imported struct's fields; and that a closure type crossing
# the boundary works both ways -- one built in the module and called
# here, one built here and called there, through a code pointer that is
# static in the other object. And that a record can cross as a handle
# alone, its fields left behind and its methods still found.
#
# The public forms carry comments in their headers, which the reduction
# to a prototype and to an extern both have to look past. And a type the
# app cannot see -- private to greet, or from a module greet imports
# without `pub' -- crosses behind a pointer, declared and no more.
#
# The interface prints as importers get it: the declarations first, then
# the pub forms in the order they were written.
#
# The app's dependency rule names both modules: greet, which it imports,
# and ledger, which only greet does but which decides what the app is
# told of it.
SEXC ?= ../../sexc
EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123
check:
@if [ "`$(SEXC) --public-interface greet.sex | head -3`" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \
echo "modules FAILED, the interface begins:"; $(SEXC) --public-interface greet.sex | head -3; exit 1; \
fi
@$(SEXC) ledger.sex -c -o ledger.o
@$(SEXC) greet.sex -c -o greet.o
@$(SEXC) greet-app.sex -o greet-app --depfile=greet-app.d -- greet.o ledger.o
@if ! head -1 greet-app.d | grep -q '^greet-app: greet-app.sex .*/greet.sex .*/ledger.sex$$'; then \
echo "modules FAILED, the dependency rule is:"; cat greet-app.d; $(MAKE) clean; exit 1; \
fi
@if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \
echo "modules ok"; \
else \
echo "modules FAILED, got:"; ./greet-app; $(MAKE) clean; exit 1; \
fi
@$(MAKE) --no-print-directory clean
clean:
@rm -f greet.o ledger.o greet-app greet-app.d
.PHONY: check clean

View File

@@ -1,161 +0,0 @@
;;; Multi-module linking.
;;;
;;; Modules are only testable end to end, and nothing else in the suite
;;; links more than one translation unit. Three things have to hold at
;;; once: an imported `pub fn' comes out as a prototype with external
;;; linkage, an imported `pub var' as an extern declaration, and the
;;; module's object survives being passed after `--'. Get any of them
;;; wrong and this fails to link -- or, in the `pub var' case, links and
;;; quietly counts into a private copy.
;;;
;;; It also checks what only a second translation unit can check: that an
;;; imported type reaches the type database, by expanding a macro that
;;; reads the imported struct's fields; and that a record can cross as a
;;; handle alone, its fields left behind and its methods still found.
;;;
;;; The public forms carry comments in their headers, which the reduction
;;; to a prototype and to an extern both have to look past. And a type the
;;; app cannot see -- private to greet, or from a module greet imports
;;; without `pub' -- crosses behind a pointer, declared and no more.
;;;
;;; The interface prints as importers get it: the declarations first, then
;;; the pub forms in the order they were written.
;;;
;;; The app's dependency rule names both modules: greet, which it imports,
;;; and ledger, which only greet does but which decides what the app is
;;; told of it.
;;;
;;; A module in a directory of its own finds its imports beside itself,
;;; not beside the unit importing it: shelf-app imports shelf/book, and
;;; book its siblings page, with `pub', and spine, without. A pub macro
;;; of page's expands into a private one, which crosses with it.
;;;
;;; Two modules may import each other with `pub': cycle/a and cycle/b,
;;; whose interfaces each import the other back.
;;;
;;; gen/made writes its pub forms by macro calls, which are expanded when
;;; its interface is read; the macros it used for that stay its own.
;;; gen/broken's call raises, which reading its interface reports.
;;;
;;; make check-modules
(import scheme
(chicken base)
(chicken file)
(chicken io)
(chicken irregex)
(chicken pathname)
(chicken process)
(chicken process-context)
srfi-1
test)
(define sexc (or (get-environment-variable "SEXC") "../../sexc"))
;;; Where the objects and the app go: not beside the sources, where what
;;; an earlier run left would pass for what this one did not build
(define scratch (create-temporary-directory))
(define (built name) (make-pathname scratch name))
;;; What PROGRAM run with ARGS writes to stderr when it fails, or #f
(define (error-of program . args)
(let* ((proc (process* program args))
(err (begin (read-string #f (process-output-port proc))
(read-string #f (process-error-port proc)))))
(process-wait proc)
(and (not (zero? (process-exit-status proc))) (string? err) err)))
;;; The lines PROGRAM prints when run with ARGS, or #f when it fails
(define (output-of program . args)
(let* ((proc (process program args))
(lines (read-lines (process-output-port proc))))
(process-wait proc)
(and (process-returned-normally? proc)
(zero? (process-exit-status proc))
lines)))
(test "the interface begins with the declarations"
'("(record cell)" "(record ledger)" "(include stdio.h)")
(take (or (output-of sexc "--public-interface" "greet.sex") '()) 3))
(test-assert "the app links with both modules"
(and (output-of sexc "ledger.sex" "-c" "-o" (built "ledger.o"))
(output-of sexc "greet.sex" "-c" "-o" (built "greet.o"))
(output-of sexc "greet-app.sex" "-o" (built "greet-app")
(string-append "--depfile=" (built "greet-app.d"))
"--" (built "greet.o") (built "ledger.o"))))
(test-assert "the dependency rule names both modules"
(irregex-match ".*/greet-app: greet-app\\.sex .*/greet\\.sex .*/ledger\\.sex"
(call-with-input-file (built "greet-app.d") read-line)))
;;; Each module has a rule of its own, so make takes one deleted since as
;;; out of date rather than as a file it has no rule to make
(test "and gives each a rule of its own"
'("greet.sex:" "ledger.sex:")
(filter-map (lambda (line)
(and (irregex-match ".*\\.sex:" line) (pathname-strip-directory line)))
(call-with-input-file (built "greet-app.d") read-lines)))
(test "a module's interface does not depend on where sexc runs"
'("(record spine)" "(import page)")
(take (or (output-of sexc "--public-interface" "shelf/book.sex") '()) 2))
(test-assert "a module in a directory finds its imports beside itself"
(and (output-of sexc "shelf/page.sex" "-c" "-o" (built "page.o"))
(output-of sexc "shelf/book.sex" "-c" "-o" (built "book.o"))
(output-of sexc "shelf-app.sex" "-o" (built "shelf-app")
"--" (built "book.o") (built "page.o"))))
(test "and the app runs through it"
'("pages 2 3" "number 2")
(output-of (built "shelf-app")))
(test-assert "modules importing each other with pub compile"
(and (output-of sexc "cycle/a.sex" "-c" "-o" (built "cycle-a.o"))
(output-of sexc "cycle/b.sex" "-c" "-o" (built "cycle-b.o"))
(output-of sexc "cycle-app.sex" "-o" (built "cycle-app")
"--" (built "cycle-a.o") (built "cycle-b.o"))))
(test "and the app runs through them"
'("cycle 1 2")
(output-of (built "cycle-app")))
;;; ...it lists pub forms a macro wrote, and not the macros that wrote them
(test "a module's interface holds what its macros wrote"
'("(pub fn forty-two () int)" "(pub fn seven () int)"
"(pub fn one () int)" "(pub fn two () int)")
(output-of sexc "--public-interface" "gen/made.sex"))
(test-assert "and an importer links with them"
(and (output-of sexc "gen/made.sex" "-c" "-o" (built "made.o"))
(output-of sexc "made-app.sex" "-o" (built "made-app")
"--" (built "made.o"))))
(test "and calls them"
'("made 42 7 1 2")
(output-of (built "made-app")))
;;; ...but a call failing for other than a name its module declares fails
;;; there as well
(test-assert "a toplevel macro call that raises fails the interface too"
(let ((err (error-of sexc "--public-interface" "gen/broken.sex")))
(and err (irregex-search "broken\\.sex:8: expanding boom: nope" err))))
(test "the app runs through both"
'("hello, world"
"hello, sex"
"2 greetings"
"text times "
"text times "
"mood 1"
"vec2 7 7"
"tally 2"
"board 42"
"ledger 2"
"colour 123")
(output-of (built "greet-app")))
(delete-directory scratch #t)
(test-exit)

View File

@@ -1,7 +0,0 @@
(include stdio.h)
(import cycle/a)
(pub fn main () int
(var b rb (make-rb 1 2))
(printf "cycle %d %d\n" (. b a x) (. b y))
(return 0))

View File

@@ -1,8 +0,0 @@
;;; Each imports the other with pub, so either one compiled pastes the
;;; other's interface, which imports it back. b holds an ra by value, so
;;; ra is defined before b is imported, as C needs it in one unit
(pub record ra ((x int)))
(pub import b)
(pub fn make-ra ((x int)) ra (return #(ra : x)))

View File

@@ -1,5 +0,0 @@
(pub import a)
(pub record rb ((a ra) (y int)))
(pub fn make-rb ((x int) (y int)) rb (return #(rb : (make-ra x) y)))

View File

@@ -1,8 +0,0 @@
;;; A toplevel macro call failing for what it is, not for asking after a
;;; name declared here: an importer is told so, as this module is
(defmacro (boom)
(error "nope"))
(pub fn fine () int (return 1))
(boom)

View File

@@ -1,23 +0,0 @@
;;; Its pub forms are written by macro calls -- its own, one it imports
;;; without pub, and a splice of two -- and reach importers as written
;;; ones do. One reading a record kept private here cannot expand for an
;;; importer, who is given nothing of it, as before, and still builds
(import makers)
(defmacro (getter name value)
`(pub fn ,name () int (return ,value)))
(defmacro (pair-of a b)
`($ (pub fn ,a () int (return 1)) (pub fn ,b () int (return 2))))
(defmacro (field-count name)
(let ((fields (get-fields name)))
(unless fields (error "no such record" name))
`(pub fn ,(cat name "-fields") () int (return ,(length fields)))))
(record box ((w int) (h int)))
(getter forty-two 42)
(field-count box)
(constant seven 7)
(pair-of one two)

View File

@@ -1,3 +0,0 @@
;;; A macro module: what it writes is up to whoever calls it
(pub defmacro (constant name value)
`(pub fn ,name () int (return ,value)))

View File

@@ -27,10 +27,19 @@
(var m (enum mood) grumpy) (var m (enum mood) grumpy)
(printf "mood %d\n" m) (printf "mood %d\n" m)
(var add-10 (closure ((int)) int) (make-adder 10))
(printf "closure %d %d" (add-10 5) (apply-twice add-10 1))
(var base int 100)
(var here (closure ((int)) int)
(closure ((x int)) int (base) (return (+ base x))))
(printf " %d\n" (apply-twice here 1))
;; the bare record name, then the method both ways round ;; the bare record name, then the method both ways round
(var v vec2 #(vec2 : 3 4)) (var v vec2 #(vec2 : 3 4))
(printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v))) (printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v)))
(.show-line v)
;; only the handle crossed: (. t n) here is an incomplete type ;; only the handle crossed: (. t n) here is an incomplete type
(var t (* tally) (tally/make)) (var t (* tally) (tally/make))
(.bump t) (.bump t)

View File

@@ -62,6 +62,19 @@
(pub fn ledger-total ((l (* const ledger))) int (pub fn ledger-total ((l (* const ledger))) int
(return (. l total))) (return (. l total)))
;;; A closure type crossing the boundary. Both units generate the
;;; struct for this signature independently, so they have to agree on
;;; its tag and its layout, or the value is passed wrong and nothing
;;; says so.
(pub fn make-adder ((n int)) (closure ((int)) int)
(return (closure ((b int)) int (n)
(return (+ n b)))))
;;; The other direction: a closure built by the importer, whose code
;;; pointer is static in *its* object, called from here
(pub fn apply-twice ((f (closure ((int)) int)) (x int)) int
(return (f (f x))))
;;; A record and an ops block crossing the boundary. The record has to ;;; 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 ;;; 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 ;;; work there; the ops block has to arrive as a block rather than as
@@ -97,6 +110,20 @@
;;; called, so there is no function for two units to both define. ;;; called, so there is no function for two units to both define.
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ()))) (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. ;;; Not `pub': invisible to importers, and static in the generated C.
(fn unused-helper () void (fn unused-helper () void
(printf "private\n")) (printf "private\n"))

View File

@@ -1,6 +0,0 @@
(include stdio.h)
(import gen/made)
(pub fn main () int
(printf "made %d %d %d %d\n" (forty-two) (seven) (one) (two))
(return 0))

View File

@@ -1,10 +0,0 @@
(include stdio.h)
(import shelf/book)
(pub fn main () int
(var b book #(book : NULL #(page : 1)))
(printf "pages %d %d\n"
(. (second-page (& b)) number)
(. (page-after (second-page (& b))) number))
(printf "number %d\n" (page-number (second-page (& b))))
(return 0))

View File

@@ -1,8 +0,0 @@
;;; Its imports are found beside it, wherever the unit importing it is
(pub import page)
(import spine)
(pub record book ((spine (* spine)) (first page)))
(pub fn second-page ((b (* const book))) page
(return (page-after (. b first))))

View File

@@ -1,9 +0,0 @@
(pub record page ((number int)))
(pub fn page-after ((p page)) page
(return #(page : (+ (. p number) 1))))
;;; number-of is private, but page-number expands into it, so importers
;;; are given both, the way a C header carries a helper macro too
(defmacro (number-of p) `(. ,p number))
(pub defmacro (page-number p) `(number-of ,p))

View File

@@ -1,3 +0,0 @@
;;; book imports this without `pub', so book's importers get the record
;;; behind a pointer, declared and no more
(pub record spine ((width int)))

View File

@@ -1,75 +0,0 @@
;;; Sex source in, C or the error it raises out, the way sexc runs
;;; the pipeline: reader -> semen -> writer. The suites after this one
;;; check the compiler through these.
(import (chicken condition)
(chicken file)
(chicken pathname)
(chicken port)
srfi-13
fmt-c-writer
reader
semen)
(define (read-source source #!optional (name "codegen.sex"))
"The forms of SOURCE, read from a file NAME, which is what the
locations then name: (read-source \"(f)\") reads (f) from codegen.sex."
(let* ((dir (create-temporary-directory))
(file (make-pathname dir name)))
(with-output-to-file file (lambda () (display source)))
(let ((forms (read-from-file file)))
(delete-directory dir #t)
forms)))
(define (sex->c source)
"Compile SOURCE, a string of Sex, and return the generated C."
(let ((forms (read-source source)))
(with-output-to-string
(lambda ()
(parameterize ((sex-line-directives 'none))
(emit-c (semen-process forms)))))))
;;; Warnings are what `warns?' is for; a test that happens to trip one
;;; should not print it
(define (silently thunk)
"THUNK's value, with whatever it wrote to stderr dropped."
(let ((value #f))
(with-error-output-to-string (lambda () (set! value (thunk))))
value))
(define (emits? source fragment)
(and (string-contains (silently (lambda () (sex->c source))) fragment) #t))
(define (failure-message thunk)
"The error THUNK raises as the user sees it -- message plus arguments,
the way CHICKEN prints it -- or #f if it raises none."
(handle-exceptions e
(with-output-to-string
(lambda ()
(display ((condition-property-accessor 'exn 'message) e))
(for-each (lambda (a) (display " ") (write a))
((condition-property-accessor 'exn 'arguments) e))))
(begin (thunk) #f)))
(define (fails-with? thunk fragment)
(let ((m (failure-message thunk)))
(and m (string-contains m fragment) #t)))
(define (reports? source fragment)
(fails-with? (lambda () (sex->c source)) fragment))
(define (followed-by? source first then)
"Is FIRST in the C compiled from SOURCE, and the next thing past it,
whitespace aside, THEN?"
(let* ((c (silently (lambda () (sex->c source))))
(at (string-contains c first)))
(and at
(let ((next (string-skip c char-whitespace? (+ at (string-length first)))))
(and next (string-prefix? then (substring c next)))))))
(define (warnings source)
"What compiling SOURCE writes to stderr."
(with-error-output-to-string (lambda () (sex->c source))))
(define (warns? source fragment)
(and (string-contains (warnings source) fragment) #t))

3
tests/reader.module.scm Normal file
View File

@@ -0,0 +1,3 @@
(module reader
*
"../reader.scm")

View File

@@ -1,6 +1,4 @@
(import (chicken condition) (import (chicken port)
(chicken irregex)
(chicken port)
reader) reader)
(define-syntax feature-test (define-syntax feature-test
@@ -11,18 +9,6 @@
(with-input-from-string string (with-input-from-string string
(lambda () (read-raw-forms 'stdin)))))))) (lambda () (read-raw-forms 'stdin))))))))
(define (read-error-at string)
"The message of the error reading STRING raises, where included, or
#f if it reads."
(handle-exceptions e ((condition-property-accessor 'exn 'message) e)
(with-input-from-string string (lambda () (read-raw-forms 'stdin)))
#f))
(define (read-error string)
"The message of the error reading STRING raises, or #f if it reads."
(let ((message (read-error-at string)))
(and message (irregex-replace "^[^:]*:[0-9]+: " message ""))))
(define-syntax reader-test (define-syntax reader-test
(syntax-rules () (syntax-rules ()
((reader-test result string) ((reader-test result string)
@@ -60,10 +46,6 @@
(reader-test '((- _x)) "-_x") (reader-test '((- _x)) "-_x")
(reader-test '(-1 -1.5) "-1 -1.5") (reader-test '(-1 -1.5) "-1 -1.5")
(reader-test '(- -> ->> -- -=) "- -> ->> -- -=") (reader-test '(- -> ->> -- -=) "- -> ->> -- -=")
;; ...but a quoted name is a name: (cat name '-fields) built `name(- fields)'
(reader-test '((quote -fields)) "'-fields")
;; while a quoted list is code a macro hands back as often as not
(reader-test '((quote ((- a) b))) "'(-a b)")
;; a number in another radix, spelled the way C does or the way ;; a number in another radix, spelled the way C does or the way
;; Scheme does; either is an ordinary integer from here on ;; Scheme does; either is an ordinary integer from here on
@@ -72,86 +54,6 @@
;; ...and only a number: a prefix with nothing after it is a name ;; ...and only a number: a prefix with nothing after it is a name
(reader-test '(0x 0xg) "0x 0xg") (reader-test '(0x 0xg) "0x 0xg")
;; `_' between two digits groups them, the way C23's ' does, which in
;; Sex is quote. Anywhere else it is part of a name
(reader-test '(1000000 65535 165 1000.5 -1000 100000.0 32768)
"1_000_000 0xFF_FF 0b1010_0101 1_000.5 -1_000 1e0_5 #x80_00")
(reader-test '(_1 1_ 1__0 0x_FF 0xF_p) "_1 1_ 1__0 0x_FF 0xF_p")
;; 017 is 17 to Scheme and 15 to C, so it means one thing to whoever
;; reads the Sex and another to whoever reads the C
(test "a leading 0 is refused"
"a leading 0 is octal to C; write the number without it, or #o for octal"
(read-error "017"))
(test "with a suffix as well" #t (string? (read-error "017u")))
(test "or grouped" #t (string? (read-error "0_17")))
(reader-test '(0 0.5 15) "0 00.5 #o17")
;; Scheme reads numbers C has no literal for, and they reached C as
;; written: 1/2 is integer division there, and +inf.0 no number at all
(test "a ratio is not a C number"
"C has no literal for this number" (read-error "1/2"))
(test "nor a double out of range"
"C has no literal for this number" (read-error "1e400"))
(test "nor a float" "C has no literal for this number" (read-error "1e39f"))
(test "but a long double may be wider than a double"
#f (read-error "1e400L"))
(test "a hex float is held to the same ranges"
"C has no literal for this number" (read-error "0x1p1024"))
(test "a float's too" "C has no literal for this number" (read-error "0x1p128f"))
(test "and a long double's" #f (read-error "0x1p1024L"))
(test "nor an infinity" "C has no literal for this number" (read-error "-inf.0"))
(test "nor a NaN" "C has no literal for this number" (read-error "+nan.0"))
(test "nor a complex number" "C has no literal for this number" (read-error "1+2i"))
(test "an integer has 64 bits at most"
"too large for any C integer type" (read-error "18446744073709551616"))
(test "and a signed suffix leaves it 63"
"too large for its suffix" (read-error "9223372036854775808ll"))
(test "an unsigned one does not"
#f (read-error "18446744073709551615ull"))
;; a name that only begins like a number is still a name
(reader-test '(3dmath.h) "3dmath.h")
;; A string is text, and an escape is one of its characters, spelled
;; the way C spells it. An escape the reader did not know lost its
;; backslash, so "\x41" read as "x41" and "\012" as NUL and "12"
(reader-test '("A" "A" "A" "A") "\"\\x41\" \"\\101\" \"\\u0041\" \"\\U00000041\"")
(reader-test '("\n" "'?" "\x7f;") "\"\\012\" \"\\'\\?\" \"\\x7f\"")
(reader-test '("é" "😀") "\"\\u00e9\" \"\\U0001F600\"")
;; a backslash ending a line joins it to the next, as in C
(reader-test '("ab") "\"a\\\nb\"")
;; C reads \xff and \377 as a byte, which text has none of: what is
;; past ASCII is written as the character, or its \u
(test "a byte past ASCII is not text"
"a byte past ASCII is not text; write the character or \\u, or a [u8 N] array for bytes"
(read-error "\"\\xff\""))
(test "in octal neither" #t (string? (read-error "\"\\377\"")))
(test "nor is a run of hex digits, which \\x takes all of"
#t (string? (read-error "\"\\x41BC\"")))
(test "an escape C has not is an error" "unknown escape" (read-error "\"\\q\""))
(test "\\x needs a digit" "\\x needs a hex digit" (read-error "\"\\xg\""))
(test "\\u takes four"
"\\u takes four hex digits and \\U eight" (read-error "\"\\u41\""))
(test "a surrogate is no character"
"no character has this code point" (read-error "\"\\uD800\""))
;; A char is C's, one byte, and #\λ came out a multi-character
;; constant whose value is the compiler's to choose
(test "a char is one byte"
"a char is one byte, and this is not: write its code point, or a string"
(read-error "#\\λ"))
(test "Latin-1 is no exception" #t (string? (read-error "#\\é")))
(reader-test '(#\a #\~ #\space) "#\\a #\\~ #\\space")
;; A reader error said what and not where, which the error of every
;; later stage does
(test "a reader error says where"
"stdin:2: unknown escape"
(read-error-at "(a)\n\"\\q\""))
(test "an unclosed list, where it opened"
"stdin:3: Unexpected end of input inside a list opened on line 2"
(read-error-at "(a)\n(b\n (c)"))
;; `;' comments are preserved as (comment "...") forms ;; `;' comments are preserved as (comment "...") forms
(reader-test '((comment " hi")) "; hi") (reader-test '((comment " hi")) "; hi")
(reader-test '((comment ";; Prototypes")) ";;; Prototypes") (reader-test '((comment ";; Prototypes")) ";;; Prototypes")

View File

@@ -1,17 +1,18 @@
(import (import
test) test)
(include-relative "pipeline.scm") (include "basic.scm")
(include-relative "semen.scm") (include "semen.scm")
(include-relative "reader.scm") (include "reader.scm")
(include-relative "fmt-c-writer.scm") (include "fmt-c-writer.scm")
(include-relative "utils.scm") (include "utils.scm")
(include-relative "line-directives.scm") (include "line-directives.scm")
(include-relative "codegen.scm") (include "codegen.scm")
(include-relative "encapsulation.scm") (include "encapsulation.scm")
(include-relative "module-path.scm") (include "args.scm")
(include-relative "types.scm") (include "module-path.scm")
(include-relative "infer.scm") (include "types.scm")
(include "infer.scm")
;;; Should be the last in the test suite ;;; Should be the last in the test suite
(test-exit) (test-exit)

2
tests/semen.module.scm Normal file
View File

@@ -0,0 +1,2 @@
(module semen *
"../semen.scm")

View File

@@ -1,8 +1,35 @@
(import semen (import srfi-69
semen
types) types)
(define print-str-fn
'(fn print-str ((s string)) void
(printf "%s" s)))
(define sum-fn
'(pub fn sum ((a int) (b int)) float
(return (cast (+ a b) float))))
(test-group "semen" (test-group "semen"
;;; Macro expansion (test-assert (sex-fn? print-str-fn))
(test #f (sex-fn-public? print-str-fn))
(test 'void (sex-fn-return-type print-str-fn))
(test 'print-str (sex-fn-name print-str-fn))
(test '((s string)) (sex-fn-arglist print-str-fn))
(test '(fn print-str ((s string)) void) (sex-fn-prototype print-str-fn))
(test '((printf "%s" s)) (sex-fn-body print-str-fn))
(test-assert (sex-fn? sum-fn))
(test #t (sex-fn-public? sum-fn))
(test 'float (sex-fn-return-type sum-fn))
(test 'sum (sex-fn-name sum-fn))
(test '((a int) (b int)) (sex-fn-arglist sum-fn))
(test '(pub fn sum ((a int) (b int)) float) (sex-fn-prototype sum-fn))
(test '((return (cast (+ a b) float))) (sex-fn-body sum-fn))
(test-assert (sex-fn? '(extern fn foo () void)))
(test 'foo (sex-fn-name '(extern fn foo () void)))
(test #f (sex-fn? '(struct point ((x int)))))
(let ((sex-code (let ((sex-code
'((defmacro (sum-var name a b c) '((defmacro (sum-var name a b c)
@@ -12,6 +39,17 @@
(test '((var v 6)) (semen-process sex-code))) (test '((var v 6)) (semen-process sex-code)))
;;; Macro expansion
(define (form-identity form env)
form)
(test 'a (walk-form 'a form-identity (make-hash-table)))
(test '(a b c) (walk-form '(a b c) form-identity (make-hash-table)))
(test 'a (macro-expand 'a))
(test '(a b c) (macro-expand '(a b c)))
(let ((sex-code-macro (let ((sex-code-macro
'((defmacro (x10 a) '((defmacro (x10 a)
`(* 10 ,a)) `(* 10 ,a))

View File

@@ -0,0 +1,3 @@
(module sex-macros
*
"../sex-macros.scm")

View File

@@ -0,0 +1,3 @@
(module sex-modules
*
"../sex-modules.scm")

View File

@@ -1,7 +1,6 @@
(compilation "-- -std=c11 -pedantic-errors") (compilation "-- -std=c11 -pedantic-errors")
(input) (input)
(output "c11: 42 43 6 4 6 12 5 0 -9223372036854775808" (output "c11: 42 43 6")
"trigraphs: what??! ??= ???( ??/")
(return 0) (return 0)
;;; C11 is the floor, and this is the program that holds it there: the ;;; C11 is the floor, and this is the program that holds it there: the
@@ -9,14 +8,9 @@
;;; one that reaches past it -- a GNU statement expression, a C23 ;;; one that reaches past it -- a GNU statement expression, a C23
;;; keyword -- fails here rather than on a user's compiler. ;;; keyword -- fails here rather than on a user's compiler.
;;; ;;;
;;; A lifted lambda is the one that leans on C11 itself, through ;;; A capturing closure is the one that leans on C11 itself, through
;;; `_Static_assert'; the record, the method and the match are here for ;;; max_align_t in the environment and `_Static_assert' on its size;
;;; what they emit, and the globals for initializers that have to be ;;; the record, the method and the match are here for what they emit.
;;; constants.
;;;
;;; It is also the one mode where C still reads trigraphs, which Sex has
;;; none of: a string says what was written, `??/' before its closing
;;; quote included.
(include stdio.h) (include stdio.h)
@@ -28,13 +22,6 @@
(sum shape ((square ((side int))) (dot ()))) (sum shape ((square ((side int))) (dot ())))
(var corner _ #(point : 2 3))
(var primes (* int) #([int 3] : 2 3 5))
(var origin point #())
(var unit _ (shape/square 1))
(var pair [_ 2] #(#(point : 1 2) #(point : 3 4)))
(var least _ -9223372036854775808)
(fn sides ((s shape)) int (fn sides ((s shape)) int
(var n int 0) (var n int 0)
(match s (match s
@@ -44,10 +31,9 @@
(pub fn main () int (pub fn main () int
(var p point #(point : 6 7)) (var p point #(point : 6 7))
(var add-k (fn ((int)) int) (var k int 1)
(lambda ((v int)) int (return (+ v 1)))) (var add-k (closure ((int)) int)
(printf "c11: %d %d %d %d %d %d %d %d %lld\n" (closure ((v int)) int (k) (return (+ v k))))
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2) (printf "c11: %d %d %d\n"
(sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least) (.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2))
(printf "trigraphs: %s\n" "what??! ??= ???( ??/")
(return 0)) (return 0))

View File

@@ -0,0 +1,52 @@
(input)
(output "one argument of two words: 7"
"two arguments of one: 7"
"unsigned, one argument: 9"
"unsigned, two arguments: 3"
"captured global: 12"
"captured function: 8")
(return 0)
;;; A closure's struct is named after its signature, so that two
;;; translation units agree on it without sharing a header. The name is
;;; built by flattening the argument list, and flattening loses where one
;;; argument ends and the next begins: `((long long))' and
;;; `((long) (long))' are different signatures that used to mangle alike,
;;; and the second quietly reused the first one's struct.
;;;
;;; A capture that borrows a name reads it from wherever the name is
;;; declared, a global or a function included.
(include stdio.h)
(var scale int 3)
(fn double-it ((n int)) int
(return (* n 2)))
(pub fn main () int
(var one-wide (closure ((long long)) int)
(closure ((a (long long))) int () (return (cast a int))))
(printf "one argument of two words: %d\n" (one-wide 7))
(var two-longs (closure ((long) (long)) int)
(closure ((a long) (b long)) int () (return (cast (+ a b) int))))
(printf "two arguments of one: %d\n" (two-longs 3 4))
(var one-unsigned (closure ((unsigned int)) int)
(closure ((a (unsigned int))) int () (return (cast a int))))
(printf "unsigned, one argument: %d\n" (one-unsigned 9))
(var two-unsigned (closure ((unsigned) (int)) int)
(closure ((a unsigned) (b int)) int () (return (+ (cast a int) b))))
(printf "unsigned, two arguments: %d\n" (two-unsigned 1 2))
;; a capture names what it borrows, and the name need not be a local
(var scaled (closure ((int)) int)
(closure ((x int)) int (scale) (return (* x scale))))
(printf "captured global: %d\n" (scaled 4))
(var doubled (closure ((int)) int)
(closure ((x int)) int (double-it) (return (double-it x))))
(printf "captured function: %d\n" (doubled 4))
(return 0))

View File

@@ -0,0 +1,121 @@
(input)
(output "Adders: 15 25"
"Two captures: 47"
"No captures: 7"
"Through a parameter: 110"
"From an array: 1 2 3"
"Index evaluated once: 21 i 1"
"Through a struct member: 8"
"Shadowed in a block: 9 then 15"
"Nested: 33"
"Named capture: 7"
"Captured pointer: 11 then 12"
"From a bare fn: 20 42 7")
(return 0)
;;; A closure is a code pointer beside its captures, so what this
;;; checks is that the captures survive the lifting -- that two
;;; closures of one shape keep their own environments, that a closure
;;; outlives the call that built it, and that calling one through a
;;; parameter, an array element or a struct member resolves the same
;;; way as through a local.
;;;
;;; A receiver is also an ordinary expression: `[table (++ i)]' has to
;;; evaluate its index exactly once, the way it would for an array of
;;; function pointers.
(include stdio.h)
(fn double-it ((n int)) int
(return (* n 2)))
;;; a bare function is a closure that captures nothing, so it converts
;;; wherever one is expected -- here a declared return type
(fn as-closure () (closure ((int)) int)
(return double-it))
(fn make-adder ((n int)) (closure ((int)) int)
(return (closure ((b int)) int (n)
(return (+ n b)))))
(fn make-affine ((k int) (b int)) (closure ((int)) int)
(return (closure ((x int)) int (k b)
(return (+ (* k x) b)))))
(fn make-const-7 () (closure () int)
(return (closure () int ()
(return 7))))
;;; A closure arriving as a parameter: its type is written, so the call
;;; resolves without knowing where it came from
(fn apply-twice ((f (closure ((int)) int)) (x int)) int
(return (f (f x))))
(struct handlers ((on-tick (closure ((int)) int))))
(pub fn main () int
(var add-10 (closure ((int)) int) (make-adder 10))
(var add-20 (closure ((int)) int) (make-adder 20))
(printf "Adders: %d %d\n" (add-10 5) (add-20 5))
(var affine (closure ((int)) int) (make-affine 5 2))
(printf "Two captures: %d\n" (affine 9))
(var seven (closure () int) (make-const-7))
(printf "No captures: %d\n" (seven))
(printf "Through a parameter: %d\n" (apply-twice (make-adder 50) 10))
(var table [(closure ((int)) int) 3])
(var i int 0)
(for (= i 0) (< i 3) (++ i)
(= [table i] (make-adder i)))
(printf "From an array: %d %d %d\n"
([table 0] 1) ([table 1] 1) ([table 2] 1))
;; the index must be evaluated once, so `i' ends at 1 and not 2 --
;; read in a separate statement, since reading and bumping it in one
;; printf would be unsequenced whatever the closure did
(= i 0)
(var once int ([table (++ i)] 20))
(printf "Index evaluated once: %d i %d\n" once i)
(var h (struct handlers) #((struct handlers) : .on-tick (make-adder 5)))
(printf "Through a struct member: %d\n" ((. h on-tick) 3))
;; a block opens a scope: the inner `add-10' ends with it, and the
;; call after it is the closure again
(do (var add-10 int 9)
(printf "Shadowed in a block: %d then " add-10))
(printf "%d\n" (add-10 5))
;; a closure built inside a closure, capturing that one's capture
(var outer (closure ((int)) int)
(closure ((x int)) int ()
(var inner (closure ((int)) int) (make-adder x))
(return (inner 3))))
(printf "Nested: %d\n" (outer 30))
;; a capture can name what it holds rather than borrow a variable's
;; name, and the expression is evaluated where the closure is written
(var pt (struct handlers))
(var sum-once (closure () int)
(closure () int ((sum (+ 3 4))) (return sum)))
(printf "Named capture: %d\n" (sum-once))
;; capturing a pointer is how by-reference is spelled; the caller owns
;; what it points at
(var counter int 11)
(var peek (closure () int)
(closure () int ((at (& counter))) (return (* at))))
(printf "Captured pointer: %d then " (peek))
(++ counter)
(printf "%d\n" (peek))
;; ...and in an initializer, as an argument, and as a return
(var from-fn (closure ((int)) int) double-it)
(printf "From a bare fn: %d %d %d\n"
(apply-twice from-fn 5)
((as-closure) 21)
(apply-twice (lambda ((n int)) int (return (+ n 1))) 5))
(return 0))

View File

@@ -6,8 +6,7 @@
"array 10 20 30" "array 10 20 30"
"argument 6" "argument 6"
"mixed 1 5" "mixed 1 5"
"read through a pointer 1 5" "read through a pointer 1 5")
"by index 0 2 0 1")
(return 0) (return 0)
;;; `:' inside #(...) ends a type and makes the rest a C99 compound ;;; `:' inside #(...) ends a type and makes the rest a C99 compound
@@ -54,8 +53,4 @@
(var c (struct point) #(struct point : (. pm x) (. pm y))) (var c (struct point) #(struct point : (. pm x) (. pm y)))
(printf "read through a pointer %d %d\n" (. c x) (. c y)) (printf "read through a pointer %d %d\n" (. c x) (. c y))
;; an element may be named by its index, as a field is by its name
(var sparse [int 4] #([3] 1 [1] 2))
(printf "by index %d %d %d %d\n" [sparse 0] [sparse 1] [sparse 2] [sparse 3])
(return 0)) (return 0))

View File

@@ -0,0 +1,61 @@
(input)
(output "direct: 120"
"fac: 120 3628800"
"fib: 55 6765"
"applied on the spot: 120")
(return 0)
;;; A fixed point built out of closures, which is the hardest thing to
;;; ask of them: recursion with no recursive function anywhere, only
;;; self-application.
;;;
;;; Self-application needs `x x' and so a recursive type, which is
;;; spelled here by routing it through a named struct whose field is a
;;; closure whose own signature mentions that struct. The generated
;;; closure struct is written before `struct rec' is, so this only
;;; compiles because a forward declaration is emitted ahead of both.
;;;
;;; Note what `fix' captures: a *pointer* to the knot, not the knot. A
;;; closure is a code pointer beside N bytes of environment, so
;;; capturing one by value would need N >= 8 + N. No budget makes that
;;; true, and the static assertion says so rather than letting it
;;; corrupt anything.
(include stdio.h)
(struct rec ((f (closure (((* (struct rec))) (int)) int))))
;;; Takes a step that expects itself, returns an ordinary closure with
;;; the self-application hidden inside
(fn fix ((step (* (struct rec)))) (closure ((int)) int)
(return (closure ((n int)) int (step)
(return ((. step f) step n)))))
(pub fn main () int
(var fac-knot (struct rec))
(= (. fac-knot f)
(closure ((self (* (struct rec))) (n int)) int ()
(if (<= n 1) (return 1))
(return (* n ((. self f) self (- n 1))))))
;; the knot applied to itself directly, without fix
(printf "direct: %d\n" ((. fac-knot f) (& fac-knot) 5))
(var fib-knot (struct rec))
(= (. fib-knot f)
(closure ((self (* (struct rec))) (n int)) int ()
(if (< n 2) (return n))
(return (+ ((. self f) self (- n 1))
((. self f) self (- n 2))))))
;; one combinator, two different recursions
(var fac (closure ((int)) int) (fix (& fac-knot)))
(var fib (closure ((int)) int) (fix (& fib-knot)))
(printf "fac: %d %d\n" (fac 5) (fac 10))
(printf "fib: %d %d\n" (fib 10) (fib 20))
;; the combinator's result invoked where it is returned, with no
;; intervening `var' -- the receiver's type is the return type of the
;; signature it came from, which is what the name table records
(printf "applied on the spot: %d\n" ((fix (& fac-knot)) 5))
(return 0))

View File

@@ -8,8 +8,8 @@
"0 1 4 9 " "0 1 4 9 "
"4" "4"
"42" "42"
"<fn of 0: 10>" "<closure of 0: 10>"
"32" "42"
"2 1" "2 1"
"Hello from Sex!") "Hello from Sex!")
(return 0) (return 0)
@@ -47,11 +47,11 @@
(= (. m y) (/ (+ (. a y) (. b y)) 2)) (= (. m y) (/ (+ (. a y) (. b y)) 2))
(return m)) (return m))
;;; A lambda's type is written once, in the signature; `_' reads it ;;; The closure's type is written once, in the signature; `_' reads it
;;; from there wherever the function is called. ;;; from there at every use.
(fn make-adder () (fn ((int)) int) (fn make-adder ((n int)) (closure ((int)) int)
(return (lambda ((b int)) int (return (closure ((b int)) int (n)
(return (+ b 10))))) (return (+ n b)))))
;;; A macro that asks what it was handed. ;;; A macro that asks what it was handed.
;;; ;;;
@@ -68,9 +68,9 @@
;; NOTE: ,x twice -- a macro that duplicates its argument still has ;; NOTE: ,x twice -- a macro that duplicates its argument still has
;; to think about evaluating it twice. Inference does not fix that. ;; to think about evaluating it twice. Inference does not fix that.
((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y))) ((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y)))
;; a function type is a type like any other, so it dispatches like ;; a closure is a type like any other, so it dispatches like one --
;; one -- and `_' saves a clause per signature ;; and `_' saves a clause per signature
((fn _ int) `(printf "<fn of 0: %d>\n" (,x 0))) ((closure _ int) `(printf "<closure of 0: %d>\n" (,x 0)))
(else (error "print: don't know how to print" (type-of x))))) (else (error "print: don't know how to print" (type-of x)))))
;;; The temporary's type is the thing the macro could not write down ;;; The temporary's type is the thing the macro could not write down
@@ -136,14 +136,14 @@
(var squares [_ 4] #(0 1 4 9)) (var squares [_ 4] #(0 1 4 9))
(print [squares 2]) (print [squares 2])
;; A function pointer's type comes from the signature that produced ;; A closure's type comes from the signature that produced it, and
;; it, and calling one needs that type and nothing else. ;; calling one needs that type and nothing else.
(var add-10 _ (make-adder)) (var add-10 _ (make-adder 10))
(print (add-10 32)) (print (add-10 32))
(print add-10) (print add-10)
;; ...including where it is returned, with no name in between. ;; ...including where it is returned, with no name in between.
(print ((make-adder) 22)) (print ((make-adder 20) 22))
;; A macro writing a declaration it could not have written before. ;; A macro writing a declaration it could not have written before.
(var a _ 1) (var a _ 1)
@@ -157,12 +157,12 @@
;;; Open questions this draft raises, to settle before Layer 2 ships: ;;; Open questions this draft raises, to settle before Layer 2 ships:
;;; ;;;
;;; 1. SETTLED. `type-match' took `_' on the pattern side, so ;;; 1. SETTLED. `type-match' took `_' on the pattern side, so
;;; `(fn _ int)' above is one clause rather than one per signature, ;;; `(closure _ int)' above is one clause rather than one per
;;; and `(* _)' and `[_ _]' say "any pointer" and "any array". A `_' ;;; signature, and `(* _)' and `[_ _]' say "any pointer" and "any
;;; written last takes the rest, since a type's words are spread and ;;; array". A `_' written last takes the rest, since a type's words
;;; not nested: `(* const char)' is three elements. Nothing ;;; are spread and not nested: `(* const char)' is three elements.
;;; destructures -- a macro body is Scheme and a type is a list, so ;;; Nothing destructures -- a macro body is Scheme and a type is a
;;; `(caddr (type-of x))' reads an array's length. ;;; list, so `(caddr (type-of x))' reads an array's length.
;;; ;;;
;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each ;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each
;;; element with the hole, so the element type comes from the ;;; element with the hole, so the element type comes from the

View File

@@ -9,7 +9,7 @@
(include stddef.h) (include stddef.h)
(include stdio.h) (include stdio.h)
(import lib/list-macros) (import list-macros)
(struct foo (struct foo
((a-field float) ((a-field float)

View File

@@ -1,45 +0,0 @@
(compilation "-- -std=c11 -pedantic-errors -Werror")
(input)
(output "unsigned: 4294967295 18446744073709551615 4294967295"
"widths: 1 1 1"
"a float stays a float: 1"
"radix with suffix: 255 5"
"by magnitude: 4000000000 18446744073709551615"
"hex floats: 12 0.25 1")
(return 0)
;;; A number is written the way C writes it, suffix included, and `_'
;;; takes the type C gives it: the suffix's, or for none the first type
;;; wide enough to hold it.
(include stdio.h)
(pub fn main () int
(var u _ 1u)
(var ull _ 1ULL)
(printf "unsigned: %u %llu %u\n" (- u 2) (- ull 2) -1u)
(var l _ 10L)
(var f _ 1.5f)
(var ld _ 0.1L)
(printf "widths: %d %d %d\n"
(== (sizeof l) (sizeof long))
(== (sizeof f) (sizeof float))
(== (sizeof ld) (sizeof (long double))))
;; the float nearest 0.1 is not the double nearest it
(var tenth-f _ 0.1f)
(var tenth _ 0.1)
(printf "a float stays a float: %d\n" (!= tenth-f tenth))
(printf "radix with suffix: %u %u\n" 0xFFu 0b101u)
(var big _ 4000000000)
(var mask _ 0xFFFFFFFFFFFFFFFF)
(printf "by magnitude: %lld %llu\n" big mask)
;; a double's own digits, which no decimal has to round to
(var twelve _ 0x1.8p3)
(var quarter _ 0x1p-2f)
(printf "hex floats: %g %g %d\n" twelve quarter (== (sizeof quarter) (sizeof float)))
(return 0))

View File

@@ -6,10 +6,10 @@
"decayed: 2 2 there" "decayed: 2 2 there"
"unsigned wins either way: 4294967295 4294967295" "unsigned wins either way: 4294967295 4294967295"
"toplevel: 1 2.5 hi 12" "toplevel: 1 2.5 hi 12"
"closure in place: 5"
"a type is not a call: 7" "a type is not a call: 7"
"radix literals: 224 5 128" "radix literals: 224 5 128"
"a double reaches C whole: 1" "a double reaches C whole: 1")
"negated literals: 1 2.5")
(return 0) (return 0)
;;; The walk types an expression by its head, and the heads it had a ;;; The walk types an expression by its head, and the heads it had a
@@ -34,6 +34,9 @@
(var s _ "hi") (var s _ "hi")
(var a _ (+ 3 (* 3 3))) (var a _ (+ 3 (* 3 3)))
(fn make-adder ((k int)) (closure ((int)) int)
(return (closure ((b int)) int (k) (return (+ k b)))))
(pub fn main () int (pub fn main () int
(var x int 6) (var x int 6)
(var y int 3) (var y int 3)
@@ -76,9 +79,14 @@
(printf "toplevel: %d %g %s %d\n" n d s a) (printf "toplevel: %d %g %s %d\n" n d s a)
;; a closure literal is its own type, so it can be called where it is
;; written, the way a lambda already could
(printf "closure in place: %d\n"
((closure ((v int)) int () (return v)) 5))
;; a `fn' type's parameter list looks exactly like a call; with a ;; a `fn' type's parameter list looks exactly like a call; with a
;; function named `f' in scope it used to be read as one ;; closure named `f' in scope it used to be read as one
(var f (fn ((int)) int) (lambda ((v int)) int (return (+ v 1)))) (var f (closure ((int)) int) (make-adder 1))
(var fp (fn ((f int) (g int)) int) area) (var fp (fn ((f int) (g int)) int) area)
(printf "a type is not a call: %d\n" (f 6)) (printf "a type is not a call: %d\n" (f 6))
@@ -89,8 +97,4 @@
;; ...and a double in all the digits it was written with ;; ...and a double in all the digits it was written with
(var sixth double (/ 1.0 6.0)) (var sixth double (/ 1.0 6.0))
(printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth)) (printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth))
;; a negative literal is one token in Sex and two in C, and C reads a
;; minus written before them as `--'
(printf "negated literals: %d %g\n" (- -1) (- -2.5))
(return 0)) (return 0))

View File

@@ -1,6 +1,5 @@
(input) (input)
(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8" (output "p 3 4 / n 7 zoe / area 12 / sizes 8 8")
"chain 1 2")
(return 0) (return 0)
;;; A record is a struct that also names itself, so the bare name ;;; A record is a struct that also names itself, so the bare name
@@ -13,16 +12,11 @@
(record point ((x int) (y int))) (record point ((x int) (y int)))
(record named (record named "Fields of more than one kind, and a docstring."
"Fields of more than one kind, and a docstring."
((id int) (first-name (* const char)))) ((id int) (first-name (* const char))))
(struct raw ((a int) (b int))) (struct raw ((a int) (b int)))
;;; A record naming itself in its own fields: the name is a type before
;;; the fields are
(record node ((value int) (next (* node))))
(fn shift ((p (* point)) (dx int) (dy int)) void (fn shift ((p (* point)) (dx int) (dy int)) void
(+= (. p x) dx) (+= (. p x) dx)
(+= (. p y) dy)) (+= (. p y) dy))
@@ -48,8 +42,4 @@
(. p x) (. p y) (. n id) (. n first-name) (. p x) (. p y) (. n id) (. n first-name)
(area [ps 0]) (area [ps 0])
(sizeof point) (sizeof (struct raw))) (sizeof point) (sizeof (struct raw)))
(var tail node #(node : 2 NULL))
(var head node #(node : 1 (& tail)))
(printf "chain %d %d\n" (. head value) (. head next value))
(return (+ (. [ps 1] x) (- (. r a) 1)))) (return (+ (. [ps 1] x) (- (. r a) 1))))

View File

@@ -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))

View File

@@ -2,9 +2,7 @@
(output "3.14 12.00 0.00" (output "3.14 12.00 0.00"
"held once: a 1" "held once: a 1"
"nested: -(2 + 3) = -5" "nested: -(2 + 3) = -5"
"size: 4"
"tagged only: 1" "tagged only: 1"
"broke out after 2"
"rows: 18 5") "rows: 18 5")
(return 0) (return 0)
@@ -47,14 +45,6 @@
((neg (e)) (printf "-") (show e)) ((neg (e)) (printf "-") (show e))
((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")")))) ((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")"))))
;;; A binder may take the name the scrutinee is spelled with, and a
;;; later binder still reads the scrutinee, not the earlier binder
(fn size ((e (* const expr))) int
(match (* e)
((lit (v)) (return 1))
((neg (e)) (return (+ 1 (size e))))
((add (e r)) (return (+ 1 (size e) (size r))))))
;;; No fields anywhere: the record is the tag alone, with no union ;;; No fields anywhere: the record is the tag alone, with no union
(sum light ((red ()) (green ()))) (sum light ((red ()) (green ())))
@@ -87,24 +77,12 @@
(printf "nested: ") (printf "nested: ")
(show (& e)) (show (& e))
(printf " = %g\n" (eval (& e))) (printf " = %g\n" (eval (& e)))
(printf "size: %d\n" (size (& e)))
(var l light (light/green)) (var l light (light/green))
(match l (match l
((red ()) (printf "tagged only: 0\n")) ((red ()) (printf "tagged only: 0\n"))
((green ()) (printf "tagged only: 1\n"))) ((green ()) (printf "tagged only: 1\n")))
;; there is no switch in the source, so `break' in an arm leaves the
;; loop around the match; one in a loop of the arm's own leaves that
(var lights [light 3] #((light/green) (light/red) (light/green)))
(var seen int 0)
(for (var i int 0) (< i 3) (++ i)
(++ seen)
(match [lights i]
((red ()) (while true (break)) (break))
((green ()) (continue))))
(printf "broke out after %d\n" seen)
(var a [int N] #(5 6 7 8)) (var a [int N] #(5 6 7 8))
(var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4)))) (var rows [row 2] #((row/cells a) (row/cells #(1 2 3 4))))
(= [a 0] 50) ; the row holds a copy (= [a 0] 50) ; the row holds a copy

View File

@@ -6,8 +6,14 @@
"one step is just the value: 7") "one step is just the value: 7")
(return 0) (return 0)
;;; A step may be a call, a bare name, a member path or a method, and ;;; `->' used to be C's arrow. The arrow is what `.' writes now when
;;; the value goes in as its first argument. ;;; the thing it reads from is a pointer, which left the name free for
;;; threading -- the first module of the standard library.
;;;
;;; What this pins is that a step may be a call, a bare name or a
;;; method, that the value is threaded into the *first* argument, and
;;; that the compiler's own generated arrows survived the rename --
;;; `ops' below lifts a method, which is where the captures live.
(include stdio.h) (include stdio.h)
(import threading-macros) (import threading-macros)

View File

@@ -8,9 +8,7 @@
"named bound: 2 4 b" "named bound: 2 4 b"
"unnamed parameters: 7 -1 2" "unnamed parameters: 7 -1 2"
"typedefs: hi 4 2" "typedefs: hi 4 2"
"sizeof a pointer type: 1 1" "sizeof a pointer type: 1 1")
"dimensions: 6 12 5"
"returned function: 42")
(return 0) (return 0)
;;; Three questions about a written type that used to be answered in ;;; Three questions about a written type that used to be answered in
@@ -30,9 +28,6 @@
(typedef vec4 [float 4]) (typedef vec4 [float 4])
(typedef unary (fn ((small)) small)) (typedef unary (fn ((small)) small))
(fn successor ((n int)) int (return (+ n 1)))
(fn stepper () (fn ((int)) int) (return successor))
(define CAP 2) (define CAP 2)
;;; a parameter that names nothing is a type, however many words it ;;; a parameter that names nothing is a type, however many words it
@@ -100,12 +95,4 @@
(printf "sizeof a pointer type: %d %d\n" (printf "sizeof a pointer type: %d %d\n"
(== (sizeof (* const char)) (sizeof greeting)) (== (sizeof (* const char)) (sizeof greeting))
(== (sizeof (* greeting)) 1)) (== (sizeof (* greeting)) 1))
;; [int 2 3] is two rows of three, indexed [g row column]
(var g [int 2 3] #(#(0 1 2) #(3 4 5)))
(printf "dimensions: %zu %zu %d\n"
(/ (sizeof g) (sizeof int)) (sizeof [g 0]) [g 1 2])
;; a function type is a declarator wrapped round the name
(printf "returned function: %d\n" ((stepper) 41))
(return 0)) (return 0))

View File

@@ -11,7 +11,6 @@
"partial: 1 2.5" "partial: 1 2.5"
"joined: 43.5 84 49 1" "joined: 43.5 84 49 1"
"promoted: 200 60000 3705032704" "promoted: 200 60000 3705032704"
"prelude: 400 6"
"from elements: 4 9 0") "from elements: 4 9 0")
(return 0) (return 0)
@@ -106,14 +105,6 @@
(var unpromoted _ (+ kept kept)) (var unpromoted _ (+ kept kept))
(printf "promoted: %d %d %u\n" narrow narrower unpromoted) (printf "promoted: %d %d %u\n" narrow narrower unpromoted)
;; the prelude's widths are C's own types under other names, and
;; promote the way those do
(var b8 u8 200)
(var w32 i32 5)
(var bytes _ (+ b8 b8))
(var next _ (+ w32 1))
(printf "prelude: %d %d\n" bytes next)
;; a brace initializer has no type of its own, but its elements solve ;; a brace initializer has no type of its own, but its elements solve
;; the hole in the array type around it -- and the length stays as ;; the hole in the array type around it -- and the length stays as
;; written, whether or not every slot is initialized ;; written, whether or not every slot is initialized

View File

@@ -3,8 +3,9 @@
"-5") "-5")
(return 0) (return 0)
;;; A recursive sum and an inherent method on it: every layer of ;;; The worked example from Encapsulation.org, kept here so it stays
;;; encapsulation in one program, built at once. ;;; true: a recursive sum, an inherent method on it, and a spec
;;; realized for it, which is every layer that is built at once.
(include stdio.h) (include stdio.h)
@@ -19,15 +20,20 @@
(match (* self) (match (* self)
((lit (v)) (return v)) ((lit (v)) (return v))
((neg (e)) (return (- (.eval e)))) ((neg (e)) (return (- (.eval e))))
((add (l r)) (return (+ (.eval l) (.eval r)))))) ((add (l r)) (return (+ (.eval l) (.eval r)))))))
(pub fn show ((self (* const expr))) void
(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) (match (* self)
((lit (v)) (printf "%g" v)) ((lit (v)) (printf "%g" v))
((neg (e)) (printf "-") (.show e)) ((neg (e)) (printf "-") (.show e))
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")")))) ((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")")))))
(pub fn show-line ((self (* const expr))) void
(.show self)
(printf "\n")))
(pub fn main () int (pub fn main () int
(var two expr (expr/lit 2.0)) (var two expr (expr/lit 2.0))

3
tests/sexc.module.scm Normal file
View File

@@ -0,0 +1,3 @@
(module sexc
*
"../sexc.scm")

50
tests/types.module.scm Normal file
View File

@@ -0,0 +1,50 @@
(module types
(add-struct
add-union
add-enum
add-typedef
add-define
type-match
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
current-type-of
get-return-type
get-type-info
get-tag-info
get-fields
get-underlying-type
type-head?
named-arg?
named-arg-type
arglist-types
strip-pub
array-bound?
array-element-type)
"../types.scm")

View File

@@ -42,17 +42,14 @@
#f #f
(get-fields 't-color)) (get-fields 't-color))
(add-typedef 't-u8 '(typedef t-u8 gl-ubyte)) (add-typedef 't-u8 '(typedef t-u8 uint8-t))
(test "a typedef resolves to its target" (test "a typedef resolves to its target"
'gl-ubyte 'uint8-t
(get-underlying-type 't-u8)) (get-underlying-type 't-u8))
(add-typedef 't-byte '(typedef t-byte t-u8)) (add-typedef 't-byte '(typedef t-byte t-u8))
(test "and chains are followed to the end" (test "and chains are followed to the end"
'gl-ubyte 'uint8-t
(get-underlying-type 't-byte)) (get-underlying-type 't-byte))
(test "stdint.h's exact-width types are C's own"
'(unsigned char)
(get-underlying-type 'uint8-t))
(test "a struct is not a typedef" (test "a struct is not a typedef"
#f #f
(get-underlying-type 't-point)) (get-underlying-type 't-point))
@@ -189,8 +186,8 @@
'yes (type-match '(struct point) ((struct _) 'yes) (else 'no))) 'yes (type-match '(struct point) ((struct _) 'yes) (else 'no)))
(test "and the keyword still has to agree" (test "and the keyword still has to agree"
'no (type-match '(union point) ((struct _) 'yes) (else 'no))) 'no (type-match '(union point) ((struct _) 'yes) (else 'no)))
(test "a function of any signature" (test "a closure of any signature"
'yes (type-match '(fn ((float)) int) ((fn _ _) 'yes) (else 'no))) 'yes (type-match '(closure ((float)) int) ((closure _ _) 'yes) (else 'no)))
(test "an exact pattern is still exact" (test "an exact pattern is still exact"
'no (type-match '(* int) ((* const char) 'yes) (else 'no))) 'no (type-match '(* int) ((* const char) 'yes) (else 'no)))

3
tests/utils.module.scm Normal file
View File

@@ -0,0 +1,3 @@
(module utils
*
"../utils.scm")

View File

@@ -1,166 +0,0 @@
;;; The compiler's modules and the programs built from them, as make
;;; reads them: what each one imports, read off its import forms. A
;;; module is a NAME.scm in the current directory; a program is named
;;; with its source. The files either includes with include-relative
;;; count as its own.
;;;
;;; csi -s tools/module-deps.scm sexc=main.scm > modules.mk
;;;
;;; prints
;;;
;;; MODULES = fmt-c-writer infer reader ...
;;; SOURCES = fmt-c-writer.scm infer.scm ... main.scm
;;; infer.o: types.o utils.o
;;; ...
;;; main.o: sexc.o
;;; sexc: main.o sexc.o
;;; fmt-c-writer.scm:
;;; ...
;;;
;;; and a source deleted since is then one make has nothing to do for,
;;; rather than one it has no rule to make
(import scheme
(chicken base)
(chicken condition)
(chicken eval)
(chicken file)
(chicken io)
(chicken pathname)
(chicken process-context)
(chicken sort)
(chicken string))
;;; As csc reads them, given -K prefix
(keyword-style #:prefix)
;;; (only sex-macros cat) -> sex-macros
(define (spec-name spec)
(if (and (pair? spec) (memq (car spec) '(only except prefix rename)))
(spec-name (cadr spec))
spec))
;;; dependencies.txt names the eggs, so a stray test.scm is not the
;;; module the tests import
(define eggs (call-with-input-file "dependencies.txt" read-list))
;;; A scheme.scm is not the module every unit imports. Asked from /,
;;; since here a NAME.import.scm built from NAME.scm would answer
(define (chicken-module? name)
(let ((here (current-directory)))
(dynamic-wind
(lambda () (change-directory "/"))
(lambda () (handle-exceptions exn #f (module-environment name) #t))
(lambda () (change-directory here)))))
(define (module-file name)
(and (symbol? name)
(not (memq name eggs))
(let ((file (string-append (symbol->string name) ".scm")))
(and (file-exists? file)
(not (chicken-module? name))
file))))
;;; FILE's forms, or the end of the scan, naming the file that has none
(define (forms-of file)
(handle-exceptions exn
(begin
(display (string-append "module-deps: " file ": "
((condition-property-accessor 'exn 'message "") exn)
"\n")
(current-error-port))
(exit 1))
(call-with-input-file file read-list)))
;;; The names FILE imports, and the files it includes, skipping those
;;; SEEN already, so two files that include each other are read once
;;; each; the vendored sex-fmt-c imports inside its (module name
;;; exports ...) form
(define (scan file #!optional (seen (list file)))
(let loop ((forms (forms-of file)) (names '()) (files '()))
(if (null? forms)
(values names files)
(let ((form (car forms)))
(cond
((not (pair? form)) (loop (cdr forms) names files))
((and (eq? (car form) 'module) (list? form) (>= (length form) 3))
(loop (append (cdddr form) (cdr forms)) names files))
((eq? (car form) 'import)
(loop (cdr forms) (append (map spec-name (cdr form)) names) files))
((eq? (car form) 'include-relative)
(let ((included (make-pathname (pathname-directory file) (cadr form)))
(seen (append files seen)))
(if (member included seen)
(loop (cdr forms) names files)
(let-values (((more-names more-files)
(scan included (cons included seen))))
(loop (cdr forms)
(append more-names names)
(append (cons included more-files) files))))))
(else (loop (cdr forms) names files)))))))
(define (symbol<? a b)
(string<? (symbol->string a) (symbol->string b)))
;;; The modules among NAMES, once each
(define (local-modules names)
(let loop ((names names) (acc '()))
(cond ((null? names) (sort acc symbol<?))
((or (memq (car names) acc) (not (module-file (car names))))
(loop (cdr names) acc))
(else (loop (cdr names) (cons (car names) acc))))))
;;; Each module reached from ROOTS, as (name imported-modules . included-files)
(define (module-graph roots)
(let loop ((pending roots) (graph '()))
(cond ((null? pending) (sort graph (lambda (a b) (symbol<? (car a) (car b)))))
((assq (car pending) graph) (loop (cdr pending) graph))
(else
(let-values (((names files) (scan (module-file (car pending)))))
(let ((deps (local-modules names)))
(loop (append (cdr pending) deps)
(cons (cons (car pending) (cons deps files)) graph))))))))
(define (objects names)
(map (lambda (name) (string-append (symbol->string name) ".o")) names))
(define (rule target prerequisites)
(unless (null? prerequisites)
(print target ": " (string-intersperse prerequisites " "))))
;;; sexc=main.scm, read off main.scm and the files it includes
(define-record-type program
(make-program binary object modules sources)
program?
(binary program-binary)
(object program-object)
(modules program-modules)
(sources program-sources))
(define (read-program spec)
(let* ((parts (string-split spec "="))
(source (cadr parts)))
(let-values (((names files) (scan source)))
(make-program (car parts) (pathname-replace-extension source "o")
(local-modules names) (cons source files)))))
;;; Only core here: modules.mk is made before `make deps' installs eggs
(let* ((programs (map read-program (command-line-arguments)))
(graph (module-graph
(local-modules (apply append (map program-modules programs))))))
(define sources
(append (apply append (map (lambda (node) (cons (module-file (car node)) (cddr node)))
graph))
(apply append (map program-sources programs))))
(print "MODULES = " (string-intersperse (map (o symbol->string car) graph) " "))
(print "SOURCES = " (string-intersperse sources " "))
(for-each (lambda (node)
(rule (car (objects (list (car node))))
(append (cddr node) (objects (cadr node)))))
graph)
(for-each (lambda (p)
(let ((modules (objects (program-modules p))))
(rule (program-object p) (append (cdr (program-sources p)) modules))
(rule (program-binary p) (cons (program-object p) modules))))
programs)
(for-each (lambda (source) (print source ":")) sources))

23
tools/sextest/Makefile Normal file
View File

@@ -0,0 +1,23 @@
CHICKEN_C = csc
CSC_FLAGS += -K prefix -static
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
ROOT = ../..
# sextest reuses sexc's reader (and its utils dependency) instead of
# duplicating the S-expression reader. The module wrappers here include
# the shared sources from the project root.
sextest: sextest.scm reader.o utils.o
$(CHICKEN_C) $(CSC_FLAGS) sextest.scm -o sextest -link reader,utils
utils.o: utils.module.scm $(ROOT)/utils.scm
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils
reader.o: reader.module.scm $(ROOT)/reader.scm utils.o
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils
clean:
rm -f *.o *.import.scm *.link sextest
.PHONY: clean

View File

@@ -0,0 +1,6 @@
(module reader (read-from-file
read-raw-forms
current-features
platform-features)
"../../reader.scm")

View File

@@ -0,0 +1,21 @@
(module utils
(get-env-var
set-working-directory
to-absolute-pathname
comment-form?
strip-header-comments
list-split
list-join
recons
current-source-file
set-form-source!
form-source
form-file
form-line
copy-form-source!
stamp-form-source!
form-location
sex-error
with-directory
)
"../../utils.scm")

50
types.module.scm Normal file
View File

@@ -0,0 +1,50 @@
(module types
(add-struct
add-union
add-enum
add-typedef
add-define
type-match
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
current-type-of
get-return-type
get-type-info
get-tag-info
get-fields
get-underlying-type
type-head?
named-arg?
named-arg-type
arglist-types
strip-pub
array-bound?
array-element-type)
"types.scm")

346
types.scm
View File

@@ -12,57 +12,9 @@
scheme scheme
(scheme base) (scheme base)
(chicken base) (chicken base)
(chicken module)
srfi-1 srfi-1
srfi-69) srfi-69)
(export
add-struct
add-union
add-enum
add-typedef
add-define
type-match
type-pattern-matches?
map-fields
add-sum!
get-sum
add-constructor!
get-constructor
variant-fields
reset-declarations!
normalize-fields
add-method!
get-method
qualify-op
ops-key
add-name-type!
get-name-type
unknown-name
type-of
current-type-of
get-return-type
get-type-info
get-tag-info
get-fields
get-underlying-type
type-head?
named-arg?
named-arg-type
arglist-types
strip-pub
array-bound?
array-element-type
array-bound
nest-array-type)
;;; Two namespaces: `struct point' and a `point' typedef are separate ;;; Two namespaces: `struct point' and a `point' typedef are separate
;;; declarations. Tags -- struct, union and enum alike -- share the ;;; declarations. Tags -- struct, union and enum alike -- share the
;;; second table between them ;;; second table between them
@@ -122,16 +74,6 @@
(hash-table-set! +type-db+ name (hash-table-set! +type-db+ name
(list 'typedef name (last (strip-pub form))))) (list 'typedef name (last (strip-pub form)))))
;;; <stdint.h>, which nothing parses, as far as arithmetic asks: the
;;; prelude's `u8' is a `uint8-t', so (+ a a) over two of them is an
;;; `int', promoted like any narrow type. The 64-bit pair is `long' on
;;; some hosts; it ranks above the narrower ones either way.
(for-each (lambda (entry) (add-typedef (car entry) (cons 'typedef entry)))
'((int8-t (signed char)) (uint8-t (unsigned char))
(int16-t short) (uint16-t (unsigned short))
(int32-t int) (uint32-t (unsigned int))
(int64-t (long long)) (uint64-t (unsigned long long))))
;;; (define name value ...) -- a C #define, kept so a macro can read a ;;; (define name value ...) -- a C #define, kept so a macro can read a
;;; compile-time constant rather than re-parse the source. ;;; compile-time constant rather than re-parse the source.
(define (add-define name form) (define (add-define name form)
@@ -148,24 +90,130 @@
(define (type-of form) ((current-type-of) form)) (define (type-of form) ((current-type-of) form))
;;; 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))))
;;; 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))))
;;; Both of these refuse a second declaration of the same name, which
;;; is per translation unit rather than per process -- so a process
;;; that compiles two units has to start the second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
;;; 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)))
;;; The name methods, realizations and sums are filed under. A typedef
;;; is followed to the aggregate it names, and one that ends in anything
;;; else stops at the last typedef, so a scalar does not share them:
;;;
;;; (record v ...) (typedef alias v) alias -> v
;;; (typedef meters float) meters -> meters
;;; (typedef km meters) km -> meters
(define (type-key name)
(let follow ((name name) (seen (list)))
(let ((target (and (not (memq name seen)) (typedef-target name))))
(cond ((not target) name)
((symbol? target)
(if (typedef-target target) (follow target (cons name seen)) name))
((target-tag target))
(else name)))))
(define (typedef-target name)
(let ((info (and (symbol? name) (get-type-info name))))
(and info (eq? (car info) 'typedef) (caddr info))))
(define (add-name-type! name type) (define (add-name-type! name type)
(hash-table-set! +name-db+ name type)) (hash-table-set! +name-db+ name type))
;;; Called with each name a lookup finds nothing for. A module's
;;; interface is read before its declarations are, so a macro call there
;;; asking after one -- (field-count box), box being its record -- is
;;; told nothing, and fails for that rather than for being wrong
(define unknown-name (make-parameter void))
(define (known name info)
(unless info ((unknown-name) name))
info)
;;; #f for a name never declared, which is what `printf' looks like ;;; #f for a name never declared, which is what `printf' looks like
;;; until something parses stdio.h. Not an error here; the caller ;;; until something parses stdio.h. Not an error here; the caller
;;; decides. ;;; decides.
(define (get-name-type name) (define (get-name-type name)
(known name (hash-table-ref/default +name-db+ name #f))) (hash-table-ref/default +name-db+ name #f))
;;; What `(make-adder 10)' has for a type: `make-adder's return type, ;;; What `(make-adder 10)' has for a type: `make-adder's return type,
;;; or #f when NAME is not a function with a signature on record ;;; or #f when NAME is not a function with a signature on record
@@ -177,7 +225,7 @@
(third type)))) (third type))))
(define (get-tag-info name) (define (get-tag-info name)
(known name (hash-table-ref/default +tag-db+ name #f))) (hash-table-ref/default +tag-db+ name #f))
;;; First look up the ordinary identifier, then tag of that id when ;;; First look up the ordinary identifier, then tag of that id when
;;; no ordinary one was declared, as C does ;;; no ordinary one was declared, as C does
@@ -239,94 +287,6 @@
(and tag (or (get-tag-info tag) (get-type-info tag)))) (and tag (or (get-tag-info tag) (get-type-info tag))))
info)))) 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)
(known type (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)))
;;; Sums, constructors and methods 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)))
;;; Type matcher macro ;;; Type matcher macro
;;; (type-match type ;;; (type-match type
;;; (int ...) ;;; (int ...)
@@ -343,8 +303,8 @@
;;; ;;;
;;; `_' in a pattern matches anything in that position, the same thing ;;; `_' in a pattern matches anything in that position, the same thing
;;; it means in a type. Without it every spelling has to be enumerated: ;;; it means in a type. Without it every spelling has to be enumerated:
;;; `(fn ((int)) int)' and `(fn ((float)) int)' are separate clauses for ;;; `(closure ((int)) int)' and `(closure ((float)) int)' are separate
;;; what is one case. ;;; clauses for what is one case.
;;; ;;;
;;; A `_' written last takes everything that remains, because a type's ;;; A `_' written last takes everything that remains, because a type's
;;; words are spread rather than nested -- `(* const char)' is three ;;; words are spread rather than nested -- `(* const char)' is three
@@ -449,14 +409,14 @@
arglist)) arglist))
;;; The last element is a bound unless what precedes it is still ;;; The last element is a bound unless what precedes it is still
;;; waiting for a type name -- a `*', a tag's keyword, a qualifier with ;;; waiting for a type name -- a `*', a qualifier, a tag's keyword. C
;;; no type before it. C spells a type with one name at most, so a name ;;; spells a type with one name at most, so a name after a name, or
;;; after a name, or after a grouped type, can only be the bound: ;;; after a grouped type, can only be the bound:
;;; ;;;
;;; (¤ int 4) four of int (¤ unsigned int) unsized ;;; (¤ int 4) four of int (¤ unsigned int) unsized
;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized ;;; (¤ pthread-t CAP) CAP of pthread-t (¤ struct point) unsized
;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized ;;; (¤ (* T) CAP) CAP of (* T) (¤ const mytype) unsized
;;; (¤ int const N) N of const int (¤ * size-t) unsized ;;; (¤ * size-t) unsized
;;; ;;;
;;; TYPE is the whole `(¤ ...)' form. ;;; TYPE is the whole `(¤ ...)' form.
(define (array-bound? type) (define (array-bound? type)
@@ -464,65 +424,19 @@
(let ((bound (last type)) (let ((bound (last type))
(preceding (last (drop-right type 1)))) (preceding (last (drop-right type 1))))
(cond (cond
((and (pair? bound) (every pair? bound)
(aggregate-head? (drop-right (cdr type) 1)))
#f)
((not (symbol? bound)) #t) ((not (symbol? bound)) #t)
((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f) ((or (memq bound +c-specifiers+) (memq bound +c-qualifiers+)) #f)
((memq preceding '(* struct union enum)) #f) (else (not (or (memq preceding '(* struct union enum))
((memq preceding +c-qualifiers+) (memq preceding +c-qualifiers+))))))))
(any (lambda (word)
(not (or (memq word '(* struct union enum))
(memq word +c-qualifiers+))))
(drop-right (cdr type) 2)))
(else #t)))))
;;; Do WORDS end the way a struct's head does, so that a list of fields
;;; after them is its body? A list of anything else is a bound, as in
;;; (¤ struct point (* 2 N)):
;;;
;;; (struct) (struct point) heads (* struct point) (int) not
(define (aggregate-head? words)
(let ((tag-words (if (and (pair? words) (symbol? (last words))
(not (memq (last words) '(struct union enum))))
(drop-right words 1)
words)))
(and (pair? tag-words)
(memq (last tag-words) '(struct union enum))
#t)))
;;; [int 2 3] is two of [int 3], so it declares what [m 1 2] indexes,
;;; m[1][2]. Every trailing bound is a dimension, the first outermost:
;;;
;;; (¤ int 2 3) -> (¤ (¤ int 3) 2)
;;; (¤ char N 3) -> (¤ (¤ char 3) N)
;;; (¤ int 4) -> (¤ int 4)
(define (nest-array-type type)
(let peel ((base type) (bounds (list)))
(if (array-bound? base)
(peel (drop-right base 1) (cons (last base) bounds))
(if (< (length bounds) 2)
type
(let ((inner-first (reverse bounds)))
(fold (lambda (bound inner) (list '¤ inner bound))
(append base (list (car inner-first)))
(cdr inner-first)))))))
;;; How many elements a written array type has, when array-bound? says
;;; it says: (¤ int 4) -> 4, (¤ int 2 3) -> 2
(define (array-bound type)
(last (nest-array-type type)))
;;; What one element of a written array type is: ;;; What one element of a written array type is:
;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char), ;;; (¤ struct point 2) -> (struct point), (¤ * const char 2) -> (* const char)
;;; (¤ int 2 3) -> (¤ int 3)
(define (array-element-type type) (define (array-element-type type)
(and (pair? type) (and (pair? type)
(eq? '¤ (car type)) (eq? '¤ (car type))
(pair? (cdr type)) (pair? (cdr type))
(let* ((type (nest-array-type type)) (let ((words (if (array-bound? type)
(words (if (array-bound? type) (drop-right (cdr type) 1)
(drop-right (cdr type) 1) (cdr type))))
(cdr type))))
(and (pair? words) (and (pair? words)
(if (null? (cdr words)) (car words) words))))) (if (null? (cdr words)) (car words) words)))))

25
utils.module.scm Normal file
View File

@@ -0,0 +1,25 @@
(module utils
(get-env-var
set-working-directory
to-absolute-pathname
comment-form?
strip-header-comments
list-split
list-join
recons
current-source-file
set-form-source!
form-source
form-file
form-line
form-end-line
copy-form-source!
stamp-form-source!
form-location
set-form-type!
form-type
sex-error
sex-warning
with-directory
)
"utils.scm")

View File

@@ -2,32 +2,11 @@
scheme scheme
(scheme base) ; make-parameter (scheme base) ; make-parameter
(chicken base) (chicken base)
(chicken module)
(chicken pathname) (chicken pathname)
(chicken process-context) (chicken process-context)
srfi-1 srfi-1
srfi-69) srfi-69)
(export
get-env-var
to-absolute-pathname
comment-form?
strip-header-comments
list-split
list-join
recons
current-source-file
set-form-source!
form-source
form-file
form-line
form-end-line
copy-form-source!
stamp-form-source!
sex-error
sex-warning
(with-directory set-working-directory))
(define-syntax prog1 (define-syntax prog1
(syntax-rules () (syntax-rules ()
((prog1 form . forms) ((prog1 form . forms)
@@ -125,6 +104,19 @@
;;; The file `parse-all' is currently reading. Bound by the reader ;;; The file `parse-all' is currently reading. Bound by the reader
(define current-source-file (make-parameter "<unknown>")) (define current-source-file (make-parameter "<unknown>"))
;;; What type a form has, once something has worked it out. Keyed by
;;; cons cell like the sources above, so one form has one type: a body
;;; typed at two instantiations has to be copied before the second.
(define +form-types+ (make-hash-table eq?))
(define (set-form-type! form type)
(when (pair? form)
(hash-table-set! +form-types+ form type))
type)
(define (form-type form)
(hash-table-ref/default +form-types+ form #f))
(define (set-form-source! form file line #!optional (end-line line)) (define (set-form-source! form file line #!optional (end-line line))
(hash-table-set! +form-sources+ form (list file line end-line))) (hash-table-set! +form-sources+ form (list file line end-line)))