forked from alex-eg/sex
Compare commits
6 Commits
feature/ls
...
sdl-exampl
| Author | SHA1 | Date | |
|---|---|---|---|
| c709c69176 | |||
| 1e435f7fdf | |||
| c976378363 | |||
| 5af2e99f5f | |||
| bb1614a123 | |||
| c1fbb02c50 |
@@ -1,67 +0,0 @@
|
|||||||
name: Sex CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
branches: [main]
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-linux:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Fetch repository
|
|
||||||
env:
|
|
||||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
git config --global --add safe.directory "$PWD"
|
|
||||||
git init
|
|
||||||
git remote add origin "${GITHUB_SERVER_URL%/}/${GITHUB_REPOSITORY}.git"
|
|
||||||
git -c http.extraHeader="Authorization: token ${GITEA_TOKEN}" \
|
|
||||||
fetch --depth 1 origin "${GITHUB_SHA}"
|
|
||||||
git checkout --force FETCH_HEAD
|
|
||||||
|
|
||||||
- name: Install toolchain
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
if [ "$(id -u)" -eq 0 ]; then
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends build-essential git wget ca-certificates
|
|
||||||
else
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y --no-install-recommends build-essential git wget ca-certificates
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Install Chicken
|
|
||||||
env:
|
|
||||||
CHICKEN_VERSION: "6.0.0"
|
|
||||||
CHICKEN_SHA256: 92835552b1b687ad26737e429b5aba36510bf429f8816ec0f6d336c8cb41f443
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
tarball="chicken-${CHICKEN_VERSION}.tar.gz"
|
|
||||||
wget -N "https://code.call-cc.org/releases/${CHICKEN_VERSION}/${tarball}"
|
|
||||||
echo "${CHICKEN_SHA256} ${tarball}" | sha256sum -c
|
|
||||||
tar zxf "${tarball}"
|
|
||||||
(
|
|
||||||
cd "chicken-${CHICKEN_VERSION}"
|
|
||||||
./configure --prefix=/usr/local
|
|
||||||
make -j"$(nproc)"
|
|
||||||
if [ "$(id -u)" -eq 0 ]; then
|
|
||||||
make install
|
|
||||||
else
|
|
||||||
sudo make install
|
|
||||||
fi
|
|
||||||
)
|
|
||||||
hash -r
|
|
||||||
csc -version
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: make deps
|
|
||||||
|
|
||||||
- name: Build sexc
|
|
||||||
run: make && ./sexc --help
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: make check
|
|
||||||
55
.github/workflows/build.yaml
vendored
Normal file
55
.github/workflows/build.yaml
vendored
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
name: Sex CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-linux:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Install chicken
|
||||||
|
run: |
|
||||||
|
wget -N https://code.call-cc.org/releases/6.0.0/chicken-6.0.0.tar.gz
|
||||||
|
tar zxf chicken-6.0.0.tar.gz
|
||||||
|
sudo apt install -y make
|
||||||
|
make -C chicken-6.0.0 PLATFORM=linux
|
||||||
|
sudo make -C chicken-6.0.0 PLATFORM=linux install
|
||||||
|
- name: Install dependencies
|
||||||
|
# FIXME: [project-local deps]: use venv or something
|
||||||
|
# run: make deps
|
||||||
|
run: sudo chicken-install $(cat dependencies.txt)
|
||||||
|
- name: Make sure that sexc builds
|
||||||
|
# FIXME: sexc being built with local .eggs/ libs needs the path at runtime.
|
||||||
|
# Without it there will be `Error: cannot load extension: fmt`.
|
||||||
|
run: make sexc && ./sexc --help
|
||||||
|
- name: Run tests
|
||||||
|
# FIXME: [project-local deps]: use local deps or build with -static
|
||||||
|
# run: make run-tests
|
||||||
|
run: make sex-tests && ./sex-tests
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
|
||||||
|
runs-on: macos-15
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Install chicken
|
||||||
|
run: brew install chicken make
|
||||||
|
- name: Install dependencies
|
||||||
|
# FIXME: [project-local deps]: use venv or something
|
||||||
|
# run: make deps
|
||||||
|
run: chicken-install $(cat dependencies.txt)
|
||||||
|
- name: Make sure that sexc builds
|
||||||
|
# FIXME: sexc being built with local .eggs/ libs needs the path at runtime.
|
||||||
|
# Without it there will be `Error: cannot load extension: fmt`.
|
||||||
|
run: make sexc && ./sexc --help
|
||||||
|
- name: Run tests
|
||||||
|
# FIXME: [project-local deps]: use local deps or build with -static
|
||||||
|
# run: make run-tests
|
||||||
|
run: make sex-tests && ./sex-tests
|
||||||
15
.gitignore
vendored
15
.gitignore
vendored
@@ -1,16 +1,5 @@
|
|||||||
# Project-local Chicken egg repository
|
|
||||||
/.eggs
|
|
||||||
|
|
||||||
# Compilation artifacts
|
|
||||||
*.o
|
*.o
|
||||||
*.import.scm
|
*.import.scm
|
||||||
*.link
|
*.link
|
||||||
/modules.mk
|
sexc
|
||||||
/modules.stamp
|
sex-tests
|
||||||
/sexc
|
|
||||||
/sex-tests
|
|
||||||
/sextest
|
|
||||||
/sex-lsp
|
|
||||||
|
|
||||||
# Scrapped design docs, kept for reference
|
|
||||||
/attic
|
|
||||||
|
|||||||
137
Makefile
137
Makefile
@@ -1,6 +1,4 @@
|
|||||||
CHICKEN_C ?= csc
|
CHICKEN_C = csc
|
||||||
# beside csc, whatever it is called: chicken-csc comes with chicken-csi
|
|
||||||
CSI ?= $(patsubst %csc,%csi,$(CHICKEN_C))
|
|
||||||
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.
|
||||||
@@ -14,108 +12,69 @@ CSC_FLAGS += -K prefix -static
|
|||||||
# error.
|
# error.
|
||||||
# -c: Stop after compilation to object files. This one is obvious.
|
# -c: Stop after compilation to object files. This one is obvious.
|
||||||
|
|
||||||
# GNU directory variables. Command line overrides, e.g.
|
|
||||||
# make prefix=$(HOME)/.local install
|
|
||||||
# make DESTDIR=/tmp/stage prefix=/usr install
|
|
||||||
prefix = /usr/local
|
|
||||||
exec_prefix = $(prefix)
|
|
||||||
bindir = $(exec_prefix)/bin
|
|
||||||
datarootdir = $(prefix)/share
|
|
||||||
datadir = $(datarootdir)
|
|
||||||
# sexc looks for the standard library beside itself: next to the binary
|
|
||||||
# in a work tree, and bindir/../share/sex once installed
|
|
||||||
sexlibdir = $(datadir)/sex
|
|
||||||
INSTALL = install
|
|
||||||
INSTALL_PROGRAM = $(INSTALL)
|
|
||||||
INSTALL_DATA = $(INSTALL) -m 644
|
|
||||||
|
|
||||||
SEX_LIB = $(wildcard lib/*.sex)
|
|
||||||
|
|
||||||
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
|
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
|
||||||
|
|
||||||
all: sexc
|
# Order matters, since module check correctness on compilation
|
||||||
|
MODULES = utils types sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc
|
||||||
|
OBJ = $(MODULES:%=%.o)
|
||||||
|
|
||||||
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 sex-lsp=sex-lsp.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):
|
sex-macros.o: sex-macros.module.scm sex-macros.scm
|
||||||
$(CHICKEN_C) $(CSC_FLAGS) $< -o $@
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-macros.module.scm -o sex-macros.o -unit sex-macros
|
||||||
|
|
||||||
# A program directly in tests/sex-programs is a test; lib/ holds what
|
reader.o: reader.module.scm reader.scm utils.o
|
||||||
# they import
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils
|
||||||
SEX_TEST_PROGRAMS = $(wildcard tests/sex-programs/*.sex)
|
|
||||||
|
|
||||||
check run-tests: sexc sex-tests sextest sex-lsp
|
sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o utils.o
|
||||||
./sex-tests
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils
|
||||||
./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
|
semen.o: semen.module.scm semen.scm sex-macros.o sex-modules.o types.o utils.o
|
||||||
check-modules check-exit-code check-command-line: check-%: sexc
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,types,utils
|
||||||
cd tests/$* && SEXC='$(CURDIR)/sexc' $(CSI) -s check.scm
|
|
||||||
|
|
||||||
install: all installdirs
|
sex-fmt-c.o: sex-fmt-c.scm
|
||||||
$(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-fmt-c.scm -o sex-fmt-c.o -unit sex-fmt-c
|
||||||
$(INSTALL_PROGRAM) sex-lsp $(DESTDIR)$(bindir)/sex-lsp
|
|
||||||
$(INSTALL_DATA) $(SEX_LIB) $(DESTDIR)$(sexlibdir)
|
|
||||||
|
|
||||||
install-strip:
|
fmt-c-writer.o: fmt-c-writer.module.scm fmt-c-writer.scm sex-fmt-c.o utils.o
|
||||||
$(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) fmt-c-writer.module.scm -o fmt-c-writer.o -unit fmt-c-writer -link sex-fmt-c,utils
|
||||||
|
|
||||||
installdirs:
|
sexc.o: sexc.module.scm types.o sexc.scm fmt-c-writer.o sex-macros.o sex-modules.o reader.o semen.o utils.o
|
||||||
$(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(sexlibdir)
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sexc.module.scm -o sexc.o -unit sexc -link fmt-c-writer,sex-macros,sex-modules,reader,semen,types,utils
|
||||||
|
|
||||||
uninstall:
|
# Unit testing
|
||||||
rm -f $(DESTDIR)$(bindir)/sexc $(DESTDIR)$(bindir)/sex-lsp
|
sex-tests:
|
||||||
rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%)
|
$(MAKE) -C ./tests sex-tests
|
||||||
-rmdir $(DESTDIR)$(sexlibdir)
|
cp ./tests/sex-tests ./
|
||||||
|
|
||||||
|
sextest:
|
||||||
|
$(MAKE) -C ./tools/sextest sextest
|
||||||
|
cp ./tools/sextest/sextest .
|
||||||
|
|
||||||
|
SEX_TEST_PROGRAMS = hello-world lists comments unicode serialize
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
run-tests: sexc sex-tests sextest
|
||||||
|
./sex-tests && ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS:%=./tests/sex-programs/%.sex) && $(MAKE) check-modules
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -f *.o $(PROGRAM_OBJ) modules.mk modules.stamp
|
rm -f $(OBJ) main.o
|
||||||
rm -f *.import.scm
|
rm -f *.import.scm
|
||||||
rm -f *.link $(PROGRAM_OBJ:.o=.link)
|
rm -f *.link
|
||||||
rm -f $(PROGRAM_NAMES)
|
rm -f sexc sex-tests sextest
|
||||||
|
$(MAKE) -C ./tests/modules clean
|
||||||
|
|
||||||
.PHONY: all check run-tests check-modules check-exit-code check-command-line install install-strip installdirs uninstall clean FORCE
|
.PHONY: clean run-tests sex-tests sextest check-modules
|
||||||
|
|||||||
227
Readme.org
227
Readme.org
@@ -12,51 +12,16 @@ Sex is statically typed, compiled general purpose language.
|
|||||||
First, get yourself a Chicken, then, some Chicken deps. You also will
|
First, get yourself a Chicken, then, some Chicken deps. You also will
|
||||||
need a C compiler.
|
need a C compiler.
|
||||||
|
|
||||||
** Development
|
** Install Chicken Eggs
|
||||||
#+begin_src sh
|
Tip: there's a way to make Chicken install eggs non-globally. You need
|
||||||
make deps
|
to export ~CHICKEN_INSTALL_REPOSITORY~ and ~CHICKEN_REPOSITORY_PATH~
|
||||||
make
|
environment variables. Refer to the documentation for more info:
|
||||||
#+end_src
|
https://wiki.call-cc.org/man/5/Extension%20tools#changing-the-repository-location
|
||||||
|
|
||||||
~make deps~ installs pinned eggs from ~eggs.lock~ into a project-local
|
~chicken-install `cat dependencies.txt`~
|
||||||
~.eggs/~ repository. ~dependencies.txt~ is the unpinned request list.
|
|
||||||
To refresh ~eggs.lock~ after changing it:
|
|
||||||
|
|
||||||
#+begin_src sh
|
** Compilation
|
||||||
make deps-update
|
~make~
|
||||||
#+end_src
|
|
||||||
|
|
||||||
** Packaging for system package managers
|
|
||||||
- Depend ~sex~ package on Chicken-6 (with ~libchicken.a~) and all eggs from ~dependencies.txt~.
|
|
||||||
- Compile and install with ~make~ (usually no other arguments required).
|
|
||||||
- Move resulting ~sexc~ binary to the appropriate place.
|
|
||||||
|
|
||||||
** Static compilation
|
|
||||||
The default ~CSC_FLAGS~ include ~-static~, so ~sexc~ does not need
|
|
||||||
~.eggs~ at runtime and ~make install~ stays relocatable. Chicken must
|
|
||||||
provide ~libchicken.a~ (E.g. for gentoo: ~dev-scheme/chicken~ with
|
|
||||||
~static-libs~ use flag).
|
|
||||||
|
|
||||||
To link dynamically instead (the binary will look for eggs under this
|
|
||||||
tree's ~.eggs~ path):
|
|
||||||
|
|
||||||
#+begin_src sh
|
|
||||||
make CSC_FLAGS='-K prefix'
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
** Installation
|
|
||||||
GNU directory variables: ~prefix~, ~exec_prefix~, ~bindir~, ~datadir~,
|
|
||||||
~DESTDIR~. The binary goes to ~bindir~ and the standard library to
|
|
||||||
~$(datadir)/sex~.
|
|
||||||
|
|
||||||
#+begin_src sh
|
|
||||||
# default installation (/usr/local/bin/)
|
|
||||||
make install
|
|
||||||
# customize the prefix (installs to ~/.local/bin)
|
|
||||||
make prefix=$(HOME)/.local install
|
|
||||||
# staged install for packaging
|
|
||||||
make DESTDIR=/tmp/stage prefix=/usr install
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
* Usage
|
* Usage
|
||||||
** Summary
|
** Summary
|
||||||
@@ -66,21 +31,13 @@ Options:
|
|||||||
--c-compiler=ARG Select C compiler. Defaults to value of SEX_CC
|
--c-compiler=ARG Select C compiler. Defaults to value of SEX_CC
|
||||||
environment variable, or if it is empty, to cc
|
environment variable, or if it is empty, to cc
|
||||||
-c, --compile-object Compile object file instead of executable program
|
-c, --compile-object Compile object file instead of executable program
|
||||||
-f, --features=ARG Comma-separated feature names, added to the host's own
|
-C, --preprocess Emit C code
|
||||||
for #+ and #- feature expressions. May be given
|
|
||||||
more than once
|
|
||||||
--no-platform-features Leave out the host's own features. With --features,
|
|
||||||
this reads a file the way another platform would
|
|
||||||
-C, --emit-c Emit C code
|
|
||||||
--public-interface Get module's public interface
|
--public-interface Get module's public interface
|
||||||
-h, --help Show this help
|
-h, --help Show this help
|
||||||
-m, --macro-expand Emit macro-expanded semantically processed Sex code
|
-m, --macro-expand Emit macro-expanded semantically processed Sex code
|
||||||
|
(sort of IR). May be useful for debugging
|
||||||
-o, --output=ARG Write output to file. Default file name is a.out.
|
-o, --output=ARG Write output to file. Default file name is a.out.
|
||||||
If -E or -m options are provided, defaults to stdout
|
If -E or -m options are provided, defaults to stdout
|
||||||
--line-directives=ARG How much #line information to emit: statement (default),
|
|
||||||
toplevel, or none. `statement' is what makes a debugger
|
|
||||||
land on the right source line; `none' is for reading -C
|
|
||||||
output by eye
|
|
||||||
#+end_src
|
#+end_src
|
||||||
** Compiling Hello World
|
** Compiling Hello World
|
||||||
#+begin_src shell
|
#+begin_src shell
|
||||||
@@ -90,8 +47,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:
|
||||||
|
|
||||||
@@ -123,28 +79,10 @@ Alex
|
|||||||
Hello, Alex!
|
Hello, Alex!
|
||||||
#+end_src
|
#+end_src
|
||||||
|
|
||||||
* Editor
|
|
||||||
[[file:sex-mode.el][sex-mode.el]] is the editing mode, [[file:sex-lsp.el][sex-lsp.el]] is the language-server client.
|
|
||||||
The install form under "sex-mode.el" below fetches both, and its ~:config~
|
|
||||||
line loads the client.
|
|
||||||
|
|
||||||
With that line, either client starts ~sex-lsp~. The hook is
|
|
||||||
~eglot-ensure~ or ~lsp-deferred~. Eldoc, xref,
|
|
||||||
and diagnostics are the ordinary LSP ones. ~sexpand~, ~sexpand-defun~,
|
|
||||||
~sexpand-region~, and ~sexpand-buffer~ show the generated C in a C
|
|
||||||
buffer. Without a server they call ~sexc --expand-lines~.
|
|
||||||
|
|
||||||
~sex-c-backend~ set to ~clangd~, as that form does, asks the server for
|
|
||||||
C headers too: completion, prototypes, and definitions of names Sex
|
|
||||||
itself does not declare. Flags are a one-line ~sex-cflags~ file, or
|
|
||||||
~sex-cflags~ in Emacs, the same words that go after ~sexc~'s ~--~.
|
|
||||||
Leave out ~:custom~, ~:hook~, and ~:config~ for the editing mode alone.
|
|
||||||
|
|
||||||
* Features
|
* Features
|
||||||
** Full C interoperability
|
** Full C interoperability
|
||||||
Just ~(include "Your/Favourite/Library.h")~ and use it as you would
|
Just ~(include "Your/Favourite/Library.h")~ and use it as you would
|
||||||
have is C. One ~include~ takes as many headers as you care to name:
|
have is C.
|
||||||
~(include stdio.h stdlib.h string.h)~.
|
|
||||||
|
|
||||||
*** Auto kebabification
|
*** Auto kebabification
|
||||||
For hardcore fans of traditional Lisp naming convention,
|
For hardcore fans of traditional Lisp naming convention,
|
||||||
@@ -152,136 +90,22 @@ Sex offers automatic kebabification of all symbols, i.e. no more
|
|||||||
ugly ~GL_ARRAY_BUFFER~ s in your code, they may be written in their
|
ugly ~GL_ARRAY_BUFFER~ s in your code, they may be written in their
|
||||||
proper form: ~GL-ARRAY-BUFFER~.
|
proper form: ~GL-ARRAY-BUFFER~.
|
||||||
|
|
||||||
** Member access
|
|
||||||
~(. x field ...)~ reads a path, and writes C's ~.~ or its ~->~ according
|
|
||||||
to what it is reading from. Each step asks the type in hand, so one path
|
|
||||||
may be both:
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
(struct line ((a (* struct point)) (b (struct point))))
|
|
||||||
|
|
||||||
(. p x) ; p : (struct point) -> p.x
|
|
||||||
(. pp x) ; pp : (* struct point) -> pp->x
|
|
||||||
(. l a x) ; l.a is a pointer -> l.a->x
|
|
||||||
(. lp b y) ; lp is, l.b is not -> lp->b.y
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
A receiver whose type cannot be worked out --- something out of a header
|
|
||||||
nothing has parsed --- is read as a value, with a warning saying so. For a
|
|
||||||
pointer there, ~(%-> p x)~ writes ~p->x~ whatever ~p~ is.
|
|
||||||
|
|
||||||
A method is ~(.name receiver args ...)~ and a field is ~(. receiver
|
|
||||||
name)~, so the shape of a form says which of the two it is without
|
|
||||||
knowing any types: ~(. a b c)~ is a path and ~(.b a c)~ is a call.
|
|
||||||
|
|
||||||
** Modules
|
** Modules
|
||||||
Each source file is a module. Module can provide public interface and
|
Each source file is a module. Module can provide public interface and
|
||||||
be imported by using ~(import path/to/module)~ expression. Module
|
be imported by using ~(import path/to/module)~ expression. Module
|
||||||
search path has three parts: first is relative to the source being
|
search path consists of two parts: first is relative to the source
|
||||||
compiled location, then the ~SEX_MODULE_PATH~ environment variable,
|
being compiled location, and the second is ~SEX_MODULE_PATH~
|
||||||
and last the standard library.
|
environment variable.
|
||||||
|
|
||||||
Module's public interface consists of everything declared
|
Module's public interface consists of everything declared
|
||||||
~pub~. Structures, function, macros, types, variables can be
|
~pub~. Structures, function, macros, types, variables can be
|
||||||
public.
|
public.
|
||||||
|
|
||||||
** Standard library
|
|
||||||
~lib/~ holds the modules that come with the compiler. They are imported
|
|
||||||
like any other, and being searched last, a module of your own by the
|
|
||||||
same name wins over one of ours.
|
|
||||||
|
|
||||||
~sexc~ looks for them beside itself, so a work tree needs nothing set
|
|
||||||
up; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~.
|
|
||||||
|
|
||||||
Each module is documented in a file of its own beside it:
|
|
||||||
|
|
||||||
- [[file:lib/threading-macros.org][threading-macros]] --- ~->~, threading a value through a chain of calls
|
|
||||||
|
|
||||||
** Read-time feature expressions
|
|
||||||
Sex is able to use ~#+~ and ~#-~ for conditional compilation: the form that
|
|
||||||
follows is kept only when the feature expression is true, and otherwise
|
|
||||||
is read and thrown away.
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
#+macosx (include OpenGL/gl3.h)
|
|
||||||
#-macosx (include GL/gl.h)
|
|
||||||
|
|
||||||
#+(and unix (not macosx)) (define HAVE-EPOLL 1)
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
An expression is a feature name, or ~and~, ~or~ and ~not~ of them.
|
|
||||||
|
|
||||||
This is read time, not compile time. What does not apply never reaches macro
|
|
||||||
expansion, the type database or the generated C.
|
|
||||||
|
|
||||||
The features are the host's ~(software-version)~, ~(software-type)~
|
|
||||||
and ~(machine-type)~, e.g. ~macosx unix arm64~ or ~linux unix
|
|
||||||
x86-64~. ~--features~ adds to them:
|
|
||||||
|
|
||||||
#+begin_src shell
|
|
||||||
sexc prog.sex -f debug,with-sdl
|
|
||||||
sexc prog.sex --features=debug --features=with-sdl
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
A feature is never taken away. The host's features can be disabled,
|
|
||||||
e.g. for checking output for other platform:
|
|
||||||
|
|
||||||
#+begin_src shell
|
|
||||||
sexc example/sdl3-triangle.sex -C --no-platform-features --features=linux,unix,x86-64
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
** Aggregate initializers and compound literals
|
|
||||||
~#(...)~ is a brace initializer. On its own it has no type and takes one
|
|
||||||
from where it is written:
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
(var p (struct point) #(1 2))
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
A ~:~ inside one ends a type and makes the whole thing a compound
|
|
||||||
literal --- an unnamed object of that type, usable anywhere an
|
|
||||||
expression is:
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
(var q (struct point) #(struct point : 3 4))
|
|
||||||
(var a (* int) #([int 3] : 10 20 30))
|
|
||||||
(draw-line ui #(struct point : 0 0) end)
|
|
||||||
(var p (* struct point) (& #(struct point : 9 9))) ; an lvalue, so `&' works
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
The type is written as bare words, the way it is everywhere else in the
|
|
||||||
language; ~:~ is what ends it.
|
|
||||||
|
|
||||||
A leading ~.~ names a field, so initializers may be designated, given in
|
|
||||||
any order, and mixed with positional ones:
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
(var r (struct named) #(struct named : .n 7 .first-name "zoe"))
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
A compound literal written inside a block lives until the end of that
|
|
||||||
block and no longer, so returning its address is a dangling pointer.
|
|
||||||
|
|
||||||
** Syntactic macros
|
** Syntactic macros
|
||||||
Sex has support for syntactic macros. Macro definitions look like
|
Sex has support for syntactic macros. Macro definitions look like
|
||||||
functions: they have a name, an argument list and a body. Macro should
|
functions: they have a name, an argument list and a body. Macro should
|
||||||
return Sex code.
|
return Sex code.
|
||||||
|
|
||||||
A macro returns *one* form. To return several --- a function beside the
|
|
||||||
struct it works on, say --- return them under =$=, which splices them in
|
|
||||||
where the macro was written:
|
|
||||||
|
|
||||||
#+begin_src scheme
|
|
||||||
(defmacro (pair-of-fns a b)
|
|
||||||
`($ (fn ,a () int (return 1))
|
|
||||||
(fn ,b () int (return 2))))
|
|
||||||
#+end_src
|
|
||||||
|
|
||||||
=($)= expands to nothing. Everything else is a single form, including
|
|
||||||
one whose head is itself a form: =`((make-adder 10) 5)= calls what
|
|
||||||
=make-adder= returned, and is not two forms.
|
|
||||||
|
|
||||||
*** Examples:
|
*** Examples:
|
||||||
**** Structure with templated value type
|
**** Structure with templated value type
|
||||||
#+begin_src scheme
|
#+begin_src scheme
|
||||||
@@ -334,23 +158,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" "sex-lsp.el")
|
|
||||||
:upgrade t)
|
|
||||||
:custom (sex-c-backend 'clangd)
|
|
||||||
:hook (sex-mode . eglot-ensure) ; if you use eglot
|
|
||||||
:hook (sex-mode . lsp-deferred) ; if you use lsp-mode
|
|
||||||
:config (require 'sex-lsp))
|
|
||||||
#+end_src
|
#+end_src
|
||||||
|
|
||||||
~.sex~ files then open in ~sex-mode~. The ~:config~ line loads the
|
|
||||||
client and registers it with whichever of eglot and lsp-mode is
|
|
||||||
installed. The hook is what starts one of them: ~lsp-deferred~ or
|
|
||||||
~eglot-ensure~. Without ~:custom~, ~:hook~, and ~:config~, only the
|
|
||||||
editing mode is loaded.
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
fmt getopt-long brev-separate test srfi-1 srfi-13 srfi-69 matchable medea
|
fmt getopt-long brev-separate test srfi-1 srfi-13 srfi-69 matchable
|
||||||
|
|||||||
12
eggs.lock
12
eggs.lock
@@ -1,12 +0,0 @@
|
|||||||
(brev-separate "1.100")
|
|
||||||
(comparse "5")
|
|
||||||
(fmt "0.8.14")
|
|
||||||
(getopt-long "4.0")
|
|
||||||
(lazy-seq "3")
|
|
||||||
(matchable "1.2")
|
|
||||||
(medea "5")
|
|
||||||
(srfi-1 "0.5.1")
|
|
||||||
(srfi-13 "0.3.8")
|
|
||||||
(srfi-69 "0.5.3")
|
|
||||||
(test "1.3")
|
|
||||||
(trie "3")
|
|
||||||
52
eggs.mk
52
eggs.mk
@@ -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
|
|
||||||
@@ -6,16 +6,16 @@
|
|||||||
(pub fn main () int
|
(pub fn main () int
|
||||||
(var a int 10)
|
(var a int 10)
|
||||||
(var b int 20)
|
(var b int 20)
|
||||||
(var sum-fn (fn ((int) (int)) int) sum)
|
(var (fn ((int) (int)) int) sum-fn sum)
|
||||||
|
|
||||||
(var sum-lambda (fn ((int) (int)) int)
|
(var (fn ((int) (int)) int) sum-lambda
|
||||||
|
|
||||||
(lambda ((a int) (b int)) int
|
(lambda ((a int) (b int)) int ()
|
||||||
(return (+ a b))))
|
(return (+ a b))))
|
||||||
|
|
||||||
(var sum-lambda-2 (fn ((int)) int)
|
(var (fn ((int)) int) sum-lambda-2
|
||||||
|
|
||||||
(lambda ((a int)) int
|
(lambda ((a int)) int ()
|
||||||
(return (+ a 20))))
|
(return (+ a 20))))
|
||||||
|
|
||||||
(printf "Hello from main fn!\n")
|
(printf "Hello from main fn!\n")
|
||||||
@@ -24,15 +24,28 @@
|
|||||||
(printf "Calling fn ptr: %d\n" (sum-fn a b))
|
(printf "Calling fn ptr: %d\n" (sum-fn a b))
|
||||||
(printf "Calling lambda: %d\n" (sum-lambda a b))
|
(printf "Calling lambda: %d\n" (sum-lambda a b))
|
||||||
(printf "Calling other lambda: %d\n" (sum-lambda-2 a))
|
(printf "Calling other lambda: %d\n" (sum-lambda-2 a))
|
||||||
(printf "Calling lambda inplace: %d\n" ((lambda ((a int) (b int)) int
|
(printf "Calling lambda inplace: %d\n" ((lambda ((a int) (b int)) int ()
|
||||||
(return (+ a b 100)))
|
(return (+ a b 100)))
|
||||||
a b))
|
a b))
|
||||||
|
|
||||||
(var l-1 (fn ((int)) int)
|
(var (fn ((int)) int) l-1
|
||||||
(lambda ((a int)) int
|
(lambda ((a int)) int ()
|
||||||
(var l-2 (fn ((int)) int)
|
(var (fn ((int)) int) l-2
|
||||||
(lambda ((a int)) int
|
(lambda ((a int)) int ()
|
||||||
(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))
|
||||||
|
|
||||||
|
;; Not supported yet
|
||||||
|
;; Closure
|
||||||
|
;; (var (fn (fn ((int)) int) ((int))) make-adder
|
||||||
|
;; (lambda (fn int ((int a))) ()
|
||||||
|
;; (return (lambda int ((int b)) (a)
|
||||||
|
;; (return (+ a b))))))
|
||||||
|
;;
|
||||||
|
;; (var (fn int ((int))) add-10
|
||||||
|
;; (make-adder 10))
|
||||||
|
;; (var (fn int ((int))) add-20
|
||||||
|
;; (make-adder 20))
|
||||||
|
;; (printf "Calling closures: %d\n" (add-10 24))
|
||||||
(return 0))
|
(return 0))
|
||||||
|
|||||||
@@ -9,25 +9,25 @@
|
|||||||
(fn-name (cat 'make-list- type)))
|
(fn-name (cat 'make-list- type)))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type)
|
`(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type)
|
||||||
(var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type)))
|
(var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type)))
|
||||||
(= (. list next) NULL)
|
(= (-> list next) NULL)
|
||||||
(return list))))
|
(return list))))
|
||||||
|
|
||||||
(pub defmacro (add-value-list-T type is-public?)
|
(pub defmacro (add-value-list-T type is-public?)
|
||||||
(let ((list-type (list 'struct (cat 'list- type)))
|
(let ((list-type (list 'struct (cat 'list- type)))
|
||||||
(fn-name (cat 'add-value-list- type)))
|
(fn-name (cat 'add-value-list- type)))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void
|
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void
|
||||||
(while (!= (. list next) NULL)
|
(while (!= (-> list next) NULL)
|
||||||
(= list (. list next)))
|
(= list (-> list next)))
|
||||||
(= (. list next) (,(cat 'make-list- type)))
|
(= (-> list next) (,(cat 'make-list- type)))
|
||||||
(= (. list value) value))))
|
(= (-> list value) value))))
|
||||||
|
|
||||||
(pub defmacro (length-list-T type is-public?)
|
(pub defmacro (length-list-T type is-public?)
|
||||||
(let ((fn-name (cat 'length-list- type))
|
(let ((fn-name (cat 'length-list- type))
|
||||||
(list-type (list 'struct (cat 'list- type))))
|
(list-type (list 'struct (cat 'list- type))))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t
|
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t
|
||||||
(var n size-t 0)
|
(var n size-t 0)
|
||||||
(while (!= (. list next) NULL)
|
(while (!= (-> list next) NULL)
|
||||||
(= list (. list next))
|
(= list (-> list next))
|
||||||
(++ n))
|
(++ n))
|
||||||
(return n))))
|
(return n))))
|
||||||
|
|
||||||
@@ -35,14 +35,14 @@
|
|||||||
`(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type)
|
`(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type)
|
||||||
((list ,(list '* 'struct (cat 'list- type))))
|
((list ,(list '* 'struct (cat 'list- type))))
|
||||||
bool
|
bool
|
||||||
(return (== (. list next) NULL))))
|
(return (== (-> list next) NULL))))
|
||||||
|
|
||||||
(pub defmacro (list-for-each list-type list-var elt-type elt-var what-do)
|
(pub defmacro (list-for-each list-type list-var elt-type elt-var what-do)
|
||||||
(let ((list-var-2 (cat list-var '-2)))
|
(let ((list-var-2 (cat list-var '-2)))
|
||||||
`(do
|
`(do
|
||||||
(var ,list-var-2 (* ,list-type) ,list-var)
|
(var ,list-var-2 (* ,list-type) ,list-var)
|
||||||
(var ,elt-var ,elt-type (. ,list-var-2 value))
|
(var ,elt-var ,elt-type (-> ,list-var-2 value))
|
||||||
(while (!= (. ,list-var-2 next) NULL)
|
(while (!= (-> ,list-var-2 next) NULL)
|
||||||
,what-do
|
,what-do
|
||||||
(= ,list-var-2 (. ,list-var-2 next))
|
(= ,list-var-2 (-> ,list-var-2 next))
|
||||||
(= ,elt-var (. ,list-var-2 value))))))
|
(= ,elt-var (-> ,list-var-2 value))))))
|
||||||
|
|||||||
@@ -8,29 +8,13 @@
|
|||||||
;;; triangle is and how far it has spun are passed in as uniforms, so
|
;;; triangle is and how far it has spun are passed in as uniforms, so
|
||||||
;;; the geometry itself is uploaded once and never touched again.
|
;;; the geometry itself is uploaded once and never touched again.
|
||||||
;;;
|
;;;
|
||||||
;;; Build, macOS:
|
;;; Build:
|
||||||
;;; ./sexc example/sdl3-triangle.sex -o sdl3-triangle -- `pkg-config --cflags --libs sdl3` -framework OpenGL
|
;;; ./sexc example/sdl3-triangle.sex -o sdl3-triangle -- `pkg-config --cflags --libs sdl3` -framework OpenGL
|
||||||
;;;
|
|
||||||
;;; Build, Linux:
|
|
||||||
;;; ./sexc example/sdl3-triangle.sex -o sdl3-triangle -- `pkg-config --cflags --libs sdl3 gl`
|
|
||||||
;;;
|
|
||||||
;;; The GL header is the one platform difference, and #+ / #- picks it.
|
|
||||||
;;; Apple keeps the core-profile entry points in <OpenGL/gl3.h> and
|
|
||||||
;;; links them through -framework OpenGL, which no pkg-config file
|
|
||||||
;;; describes; everywhere else the prototypes come from <GL/glext.h>
|
|
||||||
;;; with GL_GLEXT_PROTOTYPES defined, and -lGL -- `pkg-config --libs
|
|
||||||
;;; gl' -- resolves them. SDL3/SDL_opengl.h is not the shortcut it
|
|
||||||
;;; looks like: on Apple it resolves to the 2.1 header, which has no
|
|
||||||
;;; glGenVertexArrays and so cannot bind the VAO this program needs.
|
|
||||||
|
|
||||||
#+macosx (define GL-SILENCE-DEPRECATION 1) ; OpenGL is deprecated on macOS
|
(define GL-SILENCE-DEPRECATION 1) ; OpenGL is deprecated on macOS
|
||||||
|
|
||||||
(include SDL3/SDL.h)
|
(include SDL3/SDL.h)
|
||||||
|
(include OpenGL/gl3.h)
|
||||||
#+macosx (include OpenGL/gl3.h)
|
|
||||||
#-macosx (define GL-GLEXT-PROTOTYPES 1)
|
|
||||||
#-macosx (include GL/gl.h)
|
|
||||||
#-macosx (include GL/glext.h)
|
|
||||||
|
|
||||||
(define WINDOW-WIDTH 800)
|
(define WINDOW-WIDTH 800)
|
||||||
(define WINDOW-HEIGHT 600)
|
(define WINDOW-HEIGHT 600)
|
||||||
|
|||||||
@@ -32,7 +32,7 @@
|
|||||||
((* char) "%s")
|
((* char) "%s")
|
||||||
(else (error "serialize-struct: unsupported field type"
|
(else (error "serialize-struct: unsupported field type"
|
||||||
type-name name type))))
|
type-name name type))))
|
||||||
(. v ,name))))))
|
(-> v ,name))))))
|
||||||
(if (not printers)
|
(if (not printers)
|
||||||
(error "serialize-struct: no such struct" type-name)
|
(error "serialize-struct: no such struct" type-name)
|
||||||
`(pub fn ,(cat 'serialize- type-name)
|
`(pub fn ,(cat 'serialize- type-name)
|
||||||
|
|||||||
3
fmt-c-writer.module.scm
Normal file
3
fmt-c-writer.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module fmt-c-writer (emit-c
|
||||||
|
sex-line-directives)
|
||||||
|
"fmt-c-writer.scm")
|
||||||
444
fmt-c-writer.scm
444
fmt-c-writer.scm
@@ -4,24 +4,17 @@
|
|||||||
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?
|
|
||||||
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 +34,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 ,(cdr 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
|
||||||
@@ -53,10 +45,10 @@ source location. Only statement positions may be walked this way: a
|
|||||||
(append-map (lambda (s)
|
(append-map (lambda (s)
|
||||||
(let ((src (form-source s)))
|
(let ((src (form-source s)))
|
||||||
(if src
|
(if src
|
||||||
(list (line-directive src) (walk-statement s))
|
(list (line-directive src) (walk-expr s))
|
||||||
(list (walk-statement s)))))
|
(list (walk-expr s)))))
|
||||||
(pack-comments stmts))
|
(pack-comments stmts))
|
||||||
(map walk-statement (pack-comments stmts))))
|
(map walk-expr (pack-comments stmts))))
|
||||||
|
|
||||||
(define (walk-stmt s)
|
(define (walk-stmt s)
|
||||||
"A statement in a slot that holds exactly one form -- an `if' arm.
|
"A statement in a slot that holds exactly one form -- an `if' arm.
|
||||||
@@ -66,18 +58,8 @@ as an `else if' chain, so the anchor and the statement are wrapped in
|
|||||||
surrounding c-block supplies them)."
|
surrounding c-block supplies them)."
|
||||||
(let ((src (and (pair? s) (anchor-statements?) (form-source s))))
|
(let ((src (and (pair? s) (anchor-statements?) (form-source s))))
|
||||||
(if src
|
(if src
|
||||||
`(%begin ,(line-directive src) ,(walk-statement s))
|
`(%begin ,(line-directive src) ,(walk-expr s))
|
||||||
(walk-statement s))))
|
(walk-expr s))))
|
||||||
|
|
||||||
;;; Only here is an `if' a statement, with statements for arms that can
|
|
||||||
;;; each be anchored. Anywhere else it is `?:', and a #line between its
|
|
||||||
;;; parts does not compile
|
|
||||||
(define (walk-statement s)
|
|
||||||
(match s
|
|
||||||
(('if . clauses)
|
|
||||||
(with-comments (filter comment-form? clauses)
|
|
||||||
(cons 'if (walk-if-clauses (remove comment-form? clauses)))))
|
|
||||||
(_ (walk-expr s))))
|
|
||||||
|
|
||||||
;;; A `;' comment reads as a form, so one written inside a construct
|
;;; A `;' comment reads as a form, so one written inside a construct
|
||||||
;;; with positional slots lands in a slot and shifts everything after
|
;;; with positional slots lands in a slot and shifts everything after
|
||||||
@@ -101,22 +83,6 @@ forms, and what remains."
|
|||||||
form
|
form
|
||||||
`(%begin ,@(map walk-expr comments) ,form)))
|
`(%begin ,@(map walk-expr comments) ,form)))
|
||||||
|
|
||||||
;;; (for init test step body ...). C's parens around the header, carried
|
|
||||||
;;; over, leave all three parts in init's slot and the body in test's
|
|
||||||
(define (check-for-header form slots)
|
|
||||||
(cond ((and (pair? slots) (list? (car slots)) (= 3 (length (car slots)))
|
|
||||||
(every pair? (car slots)))
|
|
||||||
(sex-error form "a for header is not grouped: write (for init test step body ...)"))
|
|
||||||
((< (length slots) 3)
|
|
||||||
(sex-error form "malformed for: write (for init test step body ...)"))))
|
|
||||||
|
|
||||||
;;; A case body that declares is a block, so two cases can each declare
|
|
||||||
;;; a `bits', and a declaration can follow the label before C23
|
|
||||||
(define (walk-case-body body)
|
|
||||||
(if (any (lambda (form) (and (pair? form) (eq? 'var (car form)))) body)
|
|
||||||
(list (cons '%block-begin (walk-body body)))
|
|
||||||
(walk-body body)))
|
|
||||||
|
|
||||||
(define (walk-if-clauses clauses)
|
(define (walk-if-clauses clauses)
|
||||||
"(test stmt test stmt ... [else-stmt]) -- tests stay expressions."
|
"(test stmt test stmt ... [else-stmt]) -- tests stay expressions."
|
||||||
(let loop ((cs clauses) (acc (list)))
|
(let loop ((cs clauses) (acc (list)))
|
||||||
@@ -127,32 +93,15 @@ forms, and what remains."
|
|||||||
(cons (walk-stmt (cadr cs))
|
(cons (walk-stmt (cadr cs))
|
||||||
(cons (walk-expr (car cs)) acc)))))))
|
(cons (walk-expr (car cs)) acc)))))))
|
||||||
|
|
||||||
;;; mouse-x -> mouse_x, vec2/length -> vec2ːlength.
|
|
||||||
;;;
|
|
||||||
;;; `ː' is U+02D0, a modifier letter, because C takes letters in an
|
|
||||||
;;; identifier and not symbols -- clang rejects `§' outright. Not `__',
|
|
||||||
;;; because the compiler composes these names and the user does not: a
|
|
||||||
;;; hand-written vec2__length would collide, and an identifier holding
|
|
||||||
;;; `__' is reserved in C++, which a pub header may be included from.
|
|
||||||
;;; Lifted lambdas carry a λ for the same reason.
|
|
||||||
;;;
|
|
||||||
;;; zero? -> zeroʔ, clear! -> clearꜝ: a glottal stop and a raised
|
|
||||||
;;; exclamation mark, both letters. Not the retroflex click ǃ, which
|
|
||||||
;;; looks more like `!' -- enough that clang warns at every use.
|
|
||||||
(define +name-spellings+
|
|
||||||
(map (lambda (spelling) (cons (irregex (car spelling)) (cdr spelling)))
|
|
||||||
'(("-(?!>)" . "_") ("/" . "ː") ("\\?" . "ʔ") ("!" . "ꜝ"))))
|
|
||||||
|
|
||||||
(define (unkebabify sym)
|
(define (unkebabify sym)
|
||||||
(let ((name (symbol->string sym)))
|
(case sym
|
||||||
(if (or (memq sym '(- -- -> -= / /= ! != ?)) ; bare operators, not names
|
((-) sym)
|
||||||
(not (string-index name (lambda (c) (memv c '(#\- #\/ #\? #\!))))))
|
((--) sym)
|
||||||
sym
|
((->) sym)
|
||||||
(string->symbol
|
((-=) sym)
|
||||||
(fold (lambda (spelling name)
|
(else
|
||||||
(irregex-replace/all (car spelling) name (cdr spelling)))
|
(string->symbol
|
||||||
name
|
(irregex-replace/all "-(?!>)" (symbol->string sym) "_")))))
|
||||||
+name-spellings+)))))
|
|
||||||
|
|
||||||
(define (atom-to-fmt-c atom)
|
(define (atom-to-fmt-c atom)
|
||||||
(case atom
|
(case atom
|
||||||
@@ -165,34 +114,30 @@ forms, and what remains."
|
|||||||
((attribute) '%attribute)
|
((attribute) '%attribute)
|
||||||
((¤) 'vector-ref)
|
((¤) 'vector-ref)
|
||||||
((include) '%include)
|
((include) '%include)
|
||||||
((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
|
||||||
((|\||) 'bit-or)
|
((|\||) 'bit-or)
|
||||||
((|\|\||) '%or)
|
((|\|\||) '%or)
|
||||||
((|\|=|) 'bit-or=)
|
((|\|=|) 'bit-or=)
|
||||||
|
;; uh things we do for c89 compatibility
|
||||||
|
((bool) 'int)
|
||||||
|
((true) 1)
|
||||||
|
((false) 0)
|
||||||
(else
|
(else
|
||||||
(if (symbol? atom)
|
(if (symbol? atom)
|
||||||
(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)))
|
||||||
(car type)
|
(car type)
|
||||||
type))
|
type))
|
||||||
|
|
||||||
|
(define (comment-form? f)
|
||||||
|
(and (pair? f) (eq? (car f) 'comment)))
|
||||||
|
|
||||||
;;; Strip ;s so ;;; Foo becomes /* Foo */ and not /* ;; Foo */
|
;;; Strip ;s so ;;; Foo becomes /* Foo */ and not /* ;; Foo */
|
||||||
(define (strip-comment-marker text)
|
(define (strip-comment-marker text)
|
||||||
(string-trim-both (string-trim text #\;)))
|
(string-trim-both (string-trim text #\;)))
|
||||||
@@ -227,26 +172,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?)
|
||||||
|
(list->vector
|
||||||
|
(walk-expr (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
|
|
||||||
;; path lowers to where the thing it reads from is a pointer
|
|
||||||
(('%-> . 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
|
|
||||||
;; in scope that make `(* p)' one or the other
|
|
||||||
(('sizeof ('%type type)) `(%sizeof-type ,(walk-type type)))
|
|
||||||
;; semen has already put the target first, the way C writes it
|
|
||||||
(('typedef type name)
|
|
||||||
`(typedef ,(walk-type type) ,(name-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)
|
||||||
@@ -261,14 +204,15 @@ forms, and what remains."
|
|||||||
;; and each is spliced or wrapped according to what the
|
;; and each is spliced or wrapped according to what the
|
||||||
;; corresponding fmt-c procedure accepts.
|
;; corresponding fmt-c procedure accepts.
|
||||||
(('do . stmts) (cons '%block-begin (walk-body stmts)))
|
(('do . stmts) (cons '%block-begin (walk-body stmts)))
|
||||||
(('if . clauses) (cons 'if (map walk-expr (remove comment-form? clauses))))
|
(('if . clauses)
|
||||||
|
(with-comments (filter comment-form? clauses)
|
||||||
|
(cons 'if (walk-if-clauses (remove comment-form? clauses)))))
|
||||||
(('while . rest)
|
(('while . rest)
|
||||||
(let-values (((comments slots body) (take-slots rest 1)))
|
(let-values (((comments slots body) (take-slots rest 1)))
|
||||||
(with-comments comments
|
(with-comments comments
|
||||||
(cons* 'while (walk-expr (car slots)) (walk-body body)))))
|
(cons* 'while (walk-expr (car slots)) (walk-body body)))))
|
||||||
(('for . rest)
|
(('for . rest)
|
||||||
(let-values (((comments slots body) (take-slots rest 3)))
|
(let-values (((comments slots body) (take-slots rest 3)))
|
||||||
(check-for-header form slots)
|
|
||||||
(with-comments comments
|
(with-comments comments
|
||||||
(cons* 'for (walk-expr (car slots)) (walk-expr (cadr slots))
|
(cons* 'for (walk-expr (car slots)) (walk-expr (cadr slots))
|
||||||
(walk-expr (caddr slots))
|
(walk-expr (caddr slots))
|
||||||
@@ -281,140 +225,21 @@ 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))))))
|
||||||
(('case . rest)
|
(('case . rest)
|
||||||
(let-values (((comments slots body) (take-slots rest 1)))
|
(let-values (((comments slots body) (take-slots rest 1)))
|
||||||
(with-comments comments
|
(with-comments comments
|
||||||
(cons* 'case (walk-expr (car slots)) (walk-case-body body)))))
|
(cons* 'case (walk-expr (car slots)) (walk-body body)))))
|
||||||
(('case/fallthrough . rest)
|
(('case/fallthrough . rest)
|
||||||
(let-values (((comments slots body) (take-slots rest 1)))
|
(let-values (((comments slots body) (take-slots rest 1)))
|
||||||
(with-comments comments
|
(with-comments comments
|
||||||
(cons* 'case/fallthrough (walk-expr (car slots)) (walk-case-body body)))))
|
(cons* 'case/fallthrough (walk-expr (car slots)) (walk-body body)))))
|
||||||
(('default . body) (cons 'default (walk-case-body body)))
|
(('default . body) (cons 'default (walk-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
|
|
||||||
;;; turns the whole thing into a C99 compound literal:
|
|
||||||
;;; #(struct point : 1 2) is (struct point){1, 2}, and the type is
|
|
||||||
;;; written as bare words, the way it is everywhere else in the
|
|
||||||
;;; 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
|
|
||||||
;;; 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)
|
|
||||||
(let ((parts (list-split (remove comment-form? elements) ':))
|
|
||||||
(filled (lambda (es) (if (null? es) (list 0) (walk-designators es)))))
|
|
||||||
(if (null? (cdr parts))
|
|
||||||
(list->vector (filled (car parts)))
|
|
||||||
(cons* '%compound
|
|
||||||
(walk-type (maybe-unwrap-type (car parts)))
|
|
||||||
(filled (cadr parts))))))
|
|
||||||
|
|
||||||
;;; `.field value' is a designated initializer; anything else is
|
|
||||||
;;; positional. C lets the two be mixed, and nothing here stops it. A
|
|
||||||
;;; leading `.' cannot begin a C identifier, so a field name needs no
|
|
||||||
;;; keyword to introduce it and cannot collide with one.
|
|
||||||
(define (walk-designators elements)
|
|
||||||
(let loop ((es elements) (acc (list)))
|
|
||||||
(match es
|
|
||||||
(() (reverse acc))
|
|
||||||
(((or (? designator? d) (and ('¤ _) d)))
|
|
||||||
(sex-error elements "designated initializer without a value" d))
|
|
||||||
(((? designator? d) value . rest)
|
|
||||||
(loop rest
|
|
||||||
(cons (list '%designate
|
|
||||||
(name-to-fmt-c (designator-field d))
|
|
||||||
(walk-expr value))
|
|
||||||
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))))))
|
|
||||||
|
|
||||||
(define (designator? x)
|
|
||||||
(and (symbol? x)
|
|
||||||
(let ((s (symbol->string x)))
|
|
||||||
(and (> (string-length s) 1)
|
|
||||||
(char=? #\. (string-ref s 0))))))
|
|
||||||
|
|
||||||
(define (designator-field d)
|
|
||||||
(string->symbol (substring (symbol->string d) 1)))
|
|
||||||
|
|
||||||
(define (walk-var form)
|
(define (walk-var form)
|
||||||
;; (var a int) -> (%var int a)
|
;; (var a int) -> (%var int a)
|
||||||
@@ -427,7 +252,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,15 +267,19 @@ 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 (integer? (last array-type))
|
||||||
`(%array ,(walk-type (array-element-type form))
|
;; sized array
|
||||||
,(walk-expr (array-bound form)))
|
(let* ((type-list (drop-right array-type 1))
|
||||||
|
(type (maybe-unwrap-type type-list))
|
||||||
|
(size (last array-type)))
|
||||||
|
`(%array ,(walk-type type)
|
||||||
|
,size))
|
||||||
;; 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 (maybe-unwrap-type array-type)))))
|
||||||
(('fn arglist ret-type)
|
(('fn arglist ret-type)
|
||||||
`(%fun ,(walk-type ret-type) ,(walk-arg-types arglist)))
|
`(%fun ,(walk-type ret-type) ,(walk-arglist arglist)))
|
||||||
(('fn . _)
|
(('fn . _)
|
||||||
(sex-error form "malformed function type" form))
|
(sex-error form "malformed function type" form))
|
||||||
|
|
||||||
@@ -462,14 +291,8 @@ forms, and what remains."
|
|||||||
(else
|
(else
|
||||||
(type-convert-to-c form))))
|
(type-convert-to-c form))))
|
||||||
|
|
||||||
;;; An array or a function type
|
|
||||||
(define (structured-type? form)
|
|
||||||
(and (pair? form) (memq (car form) '(¤ fn))))
|
|
||||||
|
|
||||||
(define (has-pointer-star? form)
|
(define (has-pointer-star? form)
|
||||||
(and (pair? form)
|
(and (pair? 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)))))
|
||||||
|
|
||||||
@@ -481,10 +304,6 @@ forms, and what remains."
|
|||||||
(and (pair? type)
|
(and (pair? type)
|
||||||
(any has-pointer-star? (filter pair? type))))
|
(any has-pointer-star? (filter pair? type))))
|
||||||
|
|
||||||
(define (nested-structured-type type)
|
|
||||||
(and (pair? type)
|
|
||||||
(find structured-type? (filter pair? type))))
|
|
||||||
|
|
||||||
(define (type-convert-to-c type)
|
(define (type-convert-to-c type)
|
||||||
;; Our pointers to C pointers
|
;; Our pointers to C pointers
|
||||||
;; int -> int
|
;; int -> int
|
||||||
@@ -492,79 +311,52 @@ forms, and what remains."
|
|||||||
;; const * const char -> const char * const
|
;; const * const char -> const char * const
|
||||||
(when (nested-pointer? type)
|
(when (nested-pointer? type)
|
||||||
(sex-error type "pointer chains are written flat, as (* * T), not nested" type))
|
(sex-error type "pointer chains are written flat, as (* * T), not nested" type))
|
||||||
(let ((inner (nested-structured-type type)))
|
(if (atom? type) (atom-to-fmt-c type)
|
||||||
(when inner
|
(flatten
|
||||||
(if (eq? (car inner) 'fn)
|
(tree-map atom-to-fmt-c
|
||||||
;; (fn ...) is spelled as the pointer it already is in C
|
(flatten
|
||||||
(sex-error type "a fn type is a function pointer already: write (fn ...), not (* (fn ...))" type)
|
(list-join (reverse (list-split type '*))
|
||||||
(sex-error type "a pointer to an array is not supported" type))))
|
'(*)))))))
|
||||||
(if (atom? type) (name-to-fmt-c type)
|
|
||||||
(type-words (list-join (reverse (list-split type '*)) '(*)))))
|
|
||||||
|
|
||||||
;;; A type's words, flat, except that an aggregate written out in full is
|
|
||||||
;;; one of them, walked: (* (struct ((c int)))) is `struct {...} *'
|
|
||||||
(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)
|
;;; TODO: isn't there a better way?
|
||||||
(and (pair? form) (eq? (car form) '%line)))
|
(define (is-probably-type form)
|
||||||
|
(case (car form)
|
||||||
|
((¤ * const volatile struct union) #t)
|
||||||
|
(else #f)))
|
||||||
|
|
||||||
;;; The type of one parameter
|
|
||||||
(define (arg-type arg)
|
|
||||||
(if (named-arg? arg)
|
|
||||||
(walk-type (maybe-unwrap-type (cdr arg)))
|
|
||||||
;; A lone type may arrive wrapped in parens of its own, and those
|
|
||||||
;; are not part of it: ((* const char)), (int)
|
|
||||||
(walk-type (maybe-unwrap-type arg))))
|
|
||||||
|
|
||||||
;;; fmt-c reads a parameter as `(type name)', taking the name with
|
|
||||||
;;; `cadr'. A nameless one is the type and an explicit #f:
|
|
||||||
;;;
|
|
||||||
;;; (* const char) -> const char the star read as the name
|
|
||||||
;;; ((* const char) #f) -> const char *
|
|
||||||
;;; (int) -> (cadr) error
|
|
||||||
;;; (int #f) -> int
|
|
||||||
(define (walk-arglist form)
|
(define (walk-arglist form)
|
||||||
;; E.g.:
|
;; E.g.:
|
||||||
;; ((float) (int) (const char) (* const char) (¤ (* const struct res) 32))
|
;; ((float) (int) (const char) (* const char) (¤ (* const struct res) 32))
|
||||||
;; ((f1 float) (f2 float) (f3 float) (res (¤ float 4)))
|
;; ((f1 float) (f2 float) (f3 float) (res (¤ float 4)))
|
||||||
(map (lambda (arg)
|
(map (fn
|
||||||
(list (arg-type arg)
|
(match x
|
||||||
(and (named-arg? arg) (walk-type (car arg)))))
|
(('¤ . _) (walk-type x))
|
||||||
|
|
||||||
|
;; yeah shitty, but I don't know yet how to determine if the
|
||||||
|
;; first entry is part of the type and not an argument name
|
||||||
|
;; :(
|
||||||
|
((? is-probably-type) (walk-type x))
|
||||||
|
|
||||||
|
;; 1 element args are always type
|
||||||
|
((_) (walk-type x))
|
||||||
|
|
||||||
|
((var . type) (append (list (walk-type (maybe-unwrap-type type)))
|
||||||
|
(list (walk-type var))))))
|
||||||
(remove comment-form? form)))
|
(remove comment-form? form)))
|
||||||
|
|
||||||
(define (walk-arg-types form)
|
|
||||||
(map arg-type (remove comment-form? form)))
|
|
||||||
|
|
||||||
(define (walk-function form)
|
(define (walk-function form)
|
||||||
;; (fn name arglist ret-type body) -> normal function
|
;; (fn ret-type name arglist body) -> normal function
|
||||||
;; (fn name arglist ret-type) -> prototype
|
;; (fn ret-type name arglist) -> prototype
|
||||||
(if (>= (length form) 5)
|
(if (>= (length form) 5)
|
||||||
(walk-fn-def form)
|
(walk-fn-def form)
|
||||||
(cons '%prototype (cdr (walk-fn-def form)))))
|
(cons '%prototype (cdr (walk-fn-def form)))))
|
||||||
@@ -572,7 +364,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,38 +373,19 @@ 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))))
|
||||||
|
|
||||||
(define (walk-enum form)
|
(define (walk-enum form)
|
||||||
(match form
|
(match form
|
||||||
;; Naming one without defining it: `(var m (enum mood))', the same
|
|
||||||
;; shape walk-struct accepts for `(struct foo)'. Guarded, and
|
|
||||||
;; before the anonymous case, since `(enum (red green))' is also a
|
|
||||||
;; two-element form
|
|
||||||
(('enum (? symbol? name))
|
|
||||||
`(enum ,(name-to-fmt-c name)))
|
|
||||||
(('enum (values ...))
|
(('enum (values ...))
|
||||||
`(enum ,(map walk-enumerator values)))
|
`(enum ,(map atom-to-fmt-c values)))
|
||||||
(('enum name (values ...))
|
(('enum name (values ...))
|
||||||
`(enum ,(name-to-fmt-c name) ,(map walk-enumerator values)))
|
`(enum ,(atom-to-fmt-c name) ,(map atom-to-fmt-c values)))))
|
||||||
(else (sex-error form "malformed enum" form))))
|
|
||||||
|
|
||||||
;;; red -> red, (wire-varint 0) -> wire_varint = 0
|
|
||||||
(define (walk-enumerator value)
|
|
||||||
(match value
|
|
||||||
(((? enumerator-name? name) expr) (list (name-to-fmt-c name) (walk-expr expr)))
|
|
||||||
((? enumerator-name?) (name-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
|
||||||
@@ -637,7 +410,6 @@ forms, and what remains."
|
|||||||
|
|
||||||
('struct . _)
|
('struct . _)
|
||||||
('union . _)
|
('union . _)
|
||||||
('enum . _)
|
|
||||||
|
|
||||||
('typedef . _))
|
('typedef . _))
|
||||||
;; ignore here, used in generating public interface
|
;; ignore here, used in generating public interface
|
||||||
@@ -651,45 +423,21 @@ forms, and what remains."
|
|||||||
(('fn . _) (list 'static (walk-function form)))
|
(('fn . _) (list 'static (walk-function form)))
|
||||||
(('var . _) (list 'static (walk-var form)))
|
(('var . _) (list 'static (walk-var form)))
|
||||||
(('extern . rest) (walk-extern rest))
|
(('extern . rest) (walk-extern rest))
|
||||||
;; The cdr of a form has no location of its own, so hand it the
|
(('pub . rest) (walk-public rest))
|
||||||
;; `pub' form's -- otherwise a complaint about what follows `pub'
|
|
||||||
;; cannot say where it was written
|
|
||||||
(('pub . rest) (walk-public (copy-form-source! form rest)))
|
|
||||||
((or ('struct . _)
|
((or ('struct . _)
|
||||||
('union . _)) (walk-struct form))
|
('union . _)) (walk-struct form))
|
||||||
(('enum . _) (walk-enum form))
|
(('enum . _) (walk-enum form))
|
||||||
;; A target is a filename and not an identifier: GL/gl.h is a path,
|
(('define name . rest) `(%define ,(atom-to-fmt-c name) ,@rest))
|
||||||
;; and unkebabify would spell it GLːgl.h
|
|
||||||
(('include target) (list '%include target))
|
|
||||||
(('define name . body) `(%define ,(walk-expr name) ,@(map walk-expr body)))
|
|
||||||
(else (walk-expr form))))
|
(else (walk-expr form))))
|
||||||
|
|
||||||
;;; Two toplevel forms are separated by a blank line only if they were
|
|
||||||
;;; written that way: the prelude's typedefs come out packed, and so do
|
|
||||||
;;; the three includes at the top of a program that wrote them as three
|
|
||||||
;;; adjacent lines. Forms from different files -- the prelude, then an
|
|
||||||
;;; imported module, then the unit itself -- always get one.
|
|
||||||
(define (blank-line-between? prev next)
|
|
||||||
(if (equal? (form-file prev) (form-file next))
|
|
||||||
(let ((end (form-end-line prev))
|
|
||||||
(start (form-line next)))
|
|
||||||
(and end start (> (- start end) 1)))
|
|
||||||
#t))
|
|
||||||
|
|
||||||
(define (emit-c sex-forms)
|
(define (emit-c sex-forms)
|
||||||
(let emit ((forms (pack-comments sex-forms)) (prev #f))
|
(for-each (lambda (form)
|
||||||
(unless (null? forms)
|
;; Forms the reader did not produce -- the prelude, and
|
||||||
(let ((form (car forms)))
|
;; anything a macro built that we could not attribute --
|
||||||
(when (and prev (blank-line-between? prev form))
|
;; have no location and get no directive.
|
||||||
(fmt #t nl))
|
(let ((src (and (not (eq? (sex-line-directives) 'none))
|
||||||
;; Forms the reader did not produce -- the prelude, and
|
(form-source form))))
|
||||||
;; anything a macro built that we could not attribute --
|
(when src
|
||||||
;; have no location and get no directive.
|
(fmt #t (c-expr (line-directive src)))))
|
||||||
(let ((src (and (not (eq? (sex-line-directives) 'none))
|
(fmt #t (c-expr (process-toplevel-form form)) nl))
|
||||||
(form-source form))))
|
(pack-comments sex-forms)))
|
||||||
(when src
|
|
||||||
(fmt #t (c-expr (line-directive src)))))
|
|
||||||
;; `fl', not `nl': a comment leaves the cursor at the end of
|
|
||||||
;; its line while everything else has already broken it
|
|
||||||
(fmt #t (c-expr (process-toplevel-form form)) fl)
|
|
||||||
(emit (cdr forms) form)))))
|
|
||||||
|
|||||||
437
infer.scm
437
infer.scm
@@ -1,437 +0,0 @@
|
|||||||
;;; Type inference, layer 0: the type representation and unification.
|
|
||||||
;;;
|
|
||||||
;;; semen solves the wildcards of a declared type with it -- `(var n _
|
|
||||||
;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand
|
|
||||||
;;; decays or promotes to.
|
|
||||||
;;;
|
|
||||||
;;; Two representations meet here. *Surface* types are the forms the
|
|
||||||
;;; rest of the compiler passes around -- `int', `(* const char)',
|
|
||||||
;;; `(¤ int 16)', `(fn ((int)) int)'. They are what the reader
|
|
||||||
;;; produces, what the C writer consumes and what `type-match' compares
|
|
||||||
;;; with `equal?', and they are hopeless for unification. The *IR*
|
|
||||||
;;; below is the other one: mutable cells, so that solving a type
|
|
||||||
;;; variable is a side effect rather than a substitution rebuilt at
|
|
||||||
;;; every step.
|
|
||||||
;;;
|
|
||||||
;;; `parse-type' and `unparse-type' are the boundary between the two,
|
|
||||||
;;; and they carry the whole compatibility burden: `unparse-type' must
|
|
||||||
;;; produce the exact spelling `type-match' compares against, or the
|
|
||||||
;;; reflection macros break by silently falling into their `else'
|
|
||||||
;;; branch. That is what the round-trip test in tests/infer.scm is for,
|
|
||||||
;;; and why it is driven by every type spelling that appears in the
|
|
||||||
;;; repository.
|
|
||||||
|
|
||||||
(import
|
|
||||||
scheme
|
|
||||||
(scheme base)
|
|
||||||
(chicken base)
|
|
||||||
(chicken module)
|
|
||||||
matchable
|
|
||||||
srfi-1
|
|
||||||
types
|
|
||||||
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
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
|
|
||||||
;;; A type variable is a mutable cell. `ref' is #f while unsolved and
|
|
||||||
;;; the type it stands for once bound -- union-find, with the path
|
|
||||||
;;; compression done in `resolve'. `quals' are the ones written on it --
|
|
||||||
;;; `(const _)' -- and go onto whatever it is bound to.
|
|
||||||
(define-record-type <tvar>
|
|
||||||
(%make-tvar ref quals)
|
|
||||||
tvar?
|
|
||||||
(ref tvar-ref tvar-ref-set!)
|
|
||||||
(quals tvar-quals tvar-quals-set!))
|
|
||||||
|
|
||||||
;;; A primitive or otherwise nominal type. `name' is the list of words
|
|
||||||
;;; making it up, so `int', `(unsigned int)' and `(long long)' are all
|
|
||||||
;;; one node, and so is a name we have never parsed a declaration for
|
|
||||||
;;; (`size-t', `GLuint'). The two cases are told apart by
|
|
||||||
;;; `c-primitive?'.
|
|
||||||
(define-record-type <prim>
|
|
||||||
(make-prim name quals)
|
|
||||||
prim-type?
|
|
||||||
(name prim-name)
|
|
||||||
(quals prim-quals))
|
|
||||||
|
|
||||||
(define-record-type <ptr>
|
|
||||||
(make-ptr target quals)
|
|
||||||
ptr-type?
|
|
||||||
(target ptr-target)
|
|
||||||
(quals ptr-quals))
|
|
||||||
|
|
||||||
;;; `size' is the length as written -- 4, N, (* 2 N) -- or #f for
|
|
||||||
;;; `(¤ int)', an array of unwritten length. Two are one length when
|
|
||||||
;;; they are written alike.
|
|
||||||
(define-record-type <array>
|
|
||||||
(make-array-type elt size)
|
|
||||||
array-type?
|
|
||||||
(elt array-elt)
|
|
||||||
(size array-size))
|
|
||||||
|
|
||||||
(define-record-type <fn>
|
|
||||||
(make-fn-type ret args variadic?)
|
|
||||||
fn-type?
|
|
||||||
(ret fn-ret)
|
|
||||||
(args fn-args)
|
|
||||||
(variadic? fn-variadic?))
|
|
||||||
|
|
||||||
;;; struct / union / enum. Nominal: two of them are the same type when
|
|
||||||
;;; they are the same kind and the same name. `spelling' is the surface
|
|
||||||
;;; form it was written as, kept verbatim so that an aggregate defined
|
|
||||||
;;; inline in a type position round-trips unchanged.
|
|
||||||
(define-record-type <agg>
|
|
||||||
(make-agg kind name spelling quals)
|
|
||||||
agg-type?
|
|
||||||
(kind agg-kind)
|
|
||||||
(name agg-name)
|
|
||||||
(spelling agg-spelling)
|
|
||||||
(quals agg-quals))
|
|
||||||
|
|
||||||
;;; A typedef. Transparent to unification -- it unifies as whatever it
|
|
||||||
;;; expands to -- and opaque to printing, so a diagnostic and a
|
|
||||||
;;; generated declaration both say `size-t' rather than `unsigned long'.
|
|
||||||
(define-record-type <alias>
|
|
||||||
(make-alias name expansion quals)
|
|
||||||
alias-type?
|
|
||||||
(name alias-name)
|
|
||||||
(expansion alias-expansion)
|
|
||||||
(quals alias-quals))
|
|
||||||
|
|
||||||
(define (fresh-tvar)
|
|
||||||
(%make-tvar #f (list)))
|
|
||||||
|
|
||||||
;;; Follow a bound variable to what it stands for, compressing the path
|
|
||||||
;;; on the way out. Every procedure that looks at a type's shape starts
|
|
||||||
;;; here.
|
|
||||||
(define (resolve type)
|
|
||||||
(if (and (tvar? type) (tvar-ref type))
|
|
||||||
(let ((target (resolve (tvar-ref type))))
|
|
||||||
(tvar-ref-set! type target)
|
|
||||||
target)
|
|
||||||
type))
|
|
||||||
|
|
||||||
;;; ...and through any typedef as well, for the places that care what a
|
|
||||||
;;; type *is* rather than what it is called.
|
|
||||||
(define (underlying type)
|
|
||||||
(let ((t (resolve type)))
|
|
||||||
(if (alias-type? t)
|
|
||||||
(underlying (alias-expansion t))
|
|
||||||
t)))
|
|
||||||
|
|
||||||
(define (type-quals type)
|
|
||||||
(cond ((prim-type? type) (prim-quals type))
|
|
||||||
((ptr-type? type) (ptr-quals type))
|
|
||||||
((agg-type? type) (agg-quals type))
|
|
||||||
((alias-type? type) (alias-quals type))
|
|
||||||
(else (list))))
|
|
||||||
|
|
||||||
;;; Array-to-pointer and function-to-function-pointer, for the
|
|
||||||
;;; positions where C decays: a call argument, an operand of `+', the
|
|
||||||
;;; subscripted half of `(¤ a i)'.
|
|
||||||
(define (decay type)
|
|
||||||
(let ((t (underlying type)))
|
|
||||||
(cond ((array-type? t) (make-ptr (array-elt t) (list)))
|
|
||||||
((fn-type? t) (make-ptr t (list)))
|
|
||||||
(else (resolve type)))))
|
|
||||||
|
|
||||||
;;; TYPE as a value has it: qualifiers belong to an object, not to what
|
|
||||||
;;; is read out of one. `(const int)' -> `int', `(* const char)' as is.
|
|
||||||
(define (unqualified type)
|
|
||||||
(let ((t (resolve type)))
|
|
||||||
(cond ((prim-type? t) (make-prim (prim-name t) (list)))
|
|
||||||
((ptr-type? t) (make-ptr (ptr-target t) (list)))
|
|
||||||
((agg-type? t) (make-agg (agg-kind t) (agg-name t) (agg-spelling t) (list)))
|
|
||||||
((alias-type? t) (make-alias (alias-name t) (alias-expansion t) (list)))
|
|
||||||
(else t))))
|
|
||||||
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
;;; Surface -> IR
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
|
|
||||||
(define +qualifiers+ '(const volatile restrict))
|
|
||||||
|
|
||||||
(define (qualifier? word) (memq word +qualifiers+))
|
|
||||||
|
|
||||||
;;; `(const char)' written as `((const char))' is the same type: a
|
|
||||||
;;; sublist that merely groups. The C writer unwraps these too.
|
|
||||||
(define (maybe-unwrap type)
|
|
||||||
(if (and (list? type) (= 1 (length type)))
|
|
||||||
(car type)
|
|
||||||
type))
|
|
||||||
|
|
||||||
(define (parse-type surface)
|
|
||||||
(cond
|
|
||||||
((symbol? surface) (parse-words (list surface) (list) surface))
|
|
||||||
((not (pair? surface)) (sex-error surface "not a type" surface))
|
|
||||||
((eq? (car surface) '¤) (parse-array surface))
|
|
||||||
((eq? (car surface) 'fn) (parse-fn surface))
|
|
||||||
((memq '* surface) (parse-pointer-chain surface))
|
|
||||||
(else (parse-words surface (list) surface))))
|
|
||||||
|
|
||||||
;;; A `*'-free run of words: qualifiers, then whatever they qualify.
|
|
||||||
;;; `form' is only carried along so a complaint can say where it was
|
|
||||||
;;; written.
|
|
||||||
(define (parse-words words quals form)
|
|
||||||
(cond
|
|
||||||
((null? words) (sex-error form "type is nothing but qualifiers" form))
|
|
||||||
((qualifier? (car words))
|
|
||||||
(parse-words (cdr words) (cons (car words) quals) form))
|
|
||||||
;; A single sublist left: grouping parens, as in (* (const struct s))
|
|
||||||
((and (null? (cdr words)) (pair? (car words)))
|
|
||||||
(with-quals (parse-type (car words)) (reverse quals)))
|
|
||||||
((memq (car words) '(struct union enum)) (parse-agg words (reverse quals)))
|
|
||||||
((eq? (car words) '¤) (parse-array words))
|
|
||||||
((eq? (car words) 'fn) (parse-fn words))
|
|
||||||
((memq '* words) (parse-pointer-chain (append (reverse quals) words)))
|
|
||||||
(else (parse-name words (reverse quals) form))))
|
|
||||||
|
|
||||||
;;; A name, one word or several: `int', `size-t', `(unsigned int)'.
|
|
||||||
(define (parse-name words quals form)
|
|
||||||
(cond
|
|
||||||
((not (every symbol? words)) (sex-error form "malformed type" form))
|
|
||||||
;; The type-level wildcard. It is a fresh variable wherever it
|
|
||||||
;; appears, which is what makes partial types -- `(* _)', `(¤ _ 4)'
|
|
||||||
;; -- fall out for free rather than needing their own grammar.
|
|
||||||
((equal? words '(_)) (with-quals (fresh-tvar) quals))
|
|
||||||
((and (null? (cdr words)) (get-underlying-type (car words)))
|
|
||||||
=> (lambda (target)
|
|
||||||
(make-alias (car words) (parse-type target) quals)))
|
|
||||||
(else (make-prim words quals))))
|
|
||||||
|
|
||||||
;;; ([pub] struct name), (struct name (fields ...)), (struct (fields ...))
|
|
||||||
(define (parse-agg words quals)
|
|
||||||
(let* ((kind (car words))
|
|
||||||
(name (and (pair? (cdr words)) (symbol? (cadr words)) (cadr words))))
|
|
||||||
(make-agg kind name words quals)))
|
|
||||||
|
|
||||||
;;; (¤ elt ... size) -- the size is the bound `types' finds there: an
|
|
||||||
;;; integer, a name, an expression, or absent. The element words are
|
|
||||||
;;; unwrapped the way the C writer unwraps them, so `[int 16]' and
|
|
||||||
;;; `[(int) 16]' are one type.
|
|
||||||
(define (parse-array surface)
|
|
||||||
(let* ((nested (nest-array-type surface))
|
|
||||||
(sized? (array-bound? nested))
|
|
||||||
(size (and sized? (array-bound nested)))
|
|
||||||
(words (if sized? (drop-right (cdr nested) 1) (cdr nested))))
|
|
||||||
(when (null? words)
|
|
||||||
(sex-error surface "array type without an element type" surface))
|
|
||||||
(make-array-type (parse-type (maybe-unwrap words)) size)))
|
|
||||||
|
|
||||||
;;; (fn ((int) (float)) void). Argument entries are types, not named
|
|
||||||
;;; parameters -- a `fn' in type position has no room for names.
|
|
||||||
(define (parse-fn surface)
|
|
||||||
(match surface
|
|
||||||
(('fn (? list? arglist) ret)
|
|
||||||
(let* ((variadic? (and (pair? arglist) (variadic-marker? (last arglist))))
|
|
||||||
(entries (if variadic? (drop-right arglist 1) arglist)))
|
|
||||||
(make-fn-type (parse-type ret)
|
|
||||||
(map (lambda (entry) (parse-type (maybe-unwrap entry)))
|
|
||||||
entries)
|
|
||||||
variadic?)))
|
|
||||||
(else (sex-error surface "malformed function type" surface))))
|
|
||||||
|
|
||||||
;;; `...' in an arglist, written bare or wrapped the way every other
|
|
||||||
;;; entry is.
|
|
||||||
(define (variadic-marker? entry)
|
|
||||||
(or (eq? entry '...) (equal? entry '(...))))
|
|
||||||
|
|
||||||
;;; Pointer chains are written flat and read right to left: the last
|
|
||||||
;;; `*'-separated run is the pointed-to type, and each run before it
|
|
||||||
;;; qualifies one level of indirection. `(const * const char)' is a
|
|
||||||
;;; const pointer to a const char.
|
|
||||||
(define (parse-pointer-chain words)
|
|
||||||
(let* ((segments (list-split words '*))
|
|
||||||
(base (last segments))
|
|
||||||
(levels (reverse (drop-right segments 1))))
|
|
||||||
(when (null? base)
|
|
||||||
(sex-error words "pointer to nothing" words))
|
|
||||||
(fold (lambda (level acc)
|
|
||||||
(unless (every qualifier? level)
|
|
||||||
(sex-error words "only qualifiers may sit between two `*'" words))
|
|
||||||
(make-ptr acc level))
|
|
||||||
(parse-words (maybe-unwrap-segment base) (list) words)
|
|
||||||
levels)))
|
|
||||||
|
|
||||||
(define (maybe-unwrap-segment segment)
|
|
||||||
(let ((s (maybe-unwrap segment)))
|
|
||||||
(if (list? s) s (list 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
|
|
||||||
;;; variable solved to a type: `(* const _)' against `(const int)' says
|
|
||||||
;;; const once.
|
|
||||||
(define (with-quals type quals)
|
|
||||||
(define (plus written) (append quals (remove (lambda (q) (memq q quals)) written)))
|
|
||||||
(if (null? quals)
|
|
||||||
type
|
|
||||||
(cond ((prim-type? type) (make-prim (prim-name type) (plus (prim-quals type))))
|
|
||||||
((ptr-type? type) (make-ptr (ptr-target type) (plus (ptr-quals type))))
|
|
||||||
((agg-type? type) (make-agg (agg-kind type) (agg-name type)
|
|
||||||
(agg-spelling type)
|
|
||||||
(plus (agg-quals type))))
|
|
||||||
((alias-type? type) (make-alias (alias-name type)
|
|
||||||
(alias-expansion type)
|
|
||||||
(plus (alias-quals type))))
|
|
||||||
((tvar? type) (tvar-quals-set! type (plus (tvar-quals type))) type)
|
|
||||||
(else type))))
|
|
||||||
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
;;; IR -> surface
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
|
|
||||||
;;; Every result here has to be the spelling the rest of the compiler
|
|
||||||
;;; already writes by hand, since `type-match' compares with `equal?'
|
|
||||||
;;; and a near miss is silent.
|
|
||||||
(define (unparse-type type)
|
|
||||||
(let ((t (resolve type)))
|
|
||||||
(cond
|
|
||||||
((tvar? t) '_)
|
|
||||||
((alias-type? t) (qualify (alias-quals t) (list (alias-name t))))
|
|
||||||
((prim-type? t) (qualify (prim-quals t) (prim-name t)))
|
|
||||||
((agg-type? t) (qualify (agg-quals t) (agg-spelling t)))
|
|
||||||
((ptr-type? t)
|
|
||||||
(append (ptr-quals t) (list '*) (as-words (unparse-type (ptr-target t)))))
|
|
||||||
((array-type? t)
|
|
||||||
(let ((elt (as-words (unparse-type (array-elt t)))))
|
|
||||||
(append (list '¤)
|
|
||||||
(if (and (pair? elt) (eq? (car elt) '¤)) (list elt) elt)
|
|
||||||
(if (array-size t) (list (array-size t)) (list)))))
|
|
||||||
((fn-type? t)
|
|
||||||
(list 'fn
|
|
||||||
(append (map (lambda (arg) (as-arg (unparse-type arg))) (fn-args t))
|
|
||||||
(if (fn-variadic? t) (list '(...)) (list)))
|
|
||||||
(unparse-type (fn-ret t))))
|
|
||||||
(else (error "unparse-type: not a type" t)))))
|
|
||||||
|
|
||||||
;;; A one-word type is written bare, anything longer as a list --
|
|
||||||
;;; `int', but `(const int)' and `(struct point)'.
|
|
||||||
(define (qualify quals words)
|
|
||||||
(let ((all (append quals words)))
|
|
||||||
(if (and (null? quals) (= 1 (length all)))
|
|
||||||
(car all)
|
|
||||||
all)))
|
|
||||||
|
|
||||||
;;; An argument in a `fn' type is written as a list even when it is one
|
|
||||||
;;; word -- `((int) (float))' -- so only an atom needs wrapping.
|
|
||||||
(define (as-arg surface)
|
|
||||||
(if (pair? surface) surface (list surface)))
|
|
||||||
|
|
||||||
;;; Splice a type into a surrounding word list, the way `(* const char)'
|
|
||||||
;;; and `[* const char]' splice theirs. An array keeps its parentheses:
|
|
||||||
;;; `(¤ ¤ char 4)' would read back as something else entirely.
|
|
||||||
(define (as-words surface)
|
|
||||||
(cond ((not (pair? surface)) (list surface))
|
|
||||||
((memq (car surface) '(¤ fn)) (list surface))
|
|
||||||
(else surface)))
|
|
||||||
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
;;; C's own types
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
|
|
||||||
(define +integer-words+ '(char short int long signed unsigned bool _Bool))
|
|
||||||
(define +float-words+ '(float double))
|
|
||||||
(define +known-words+ (append '(void) +integer-words+ +float-words+))
|
|
||||||
|
|
||||||
;;; A prim built only out of words we recognise. Anything else is a
|
|
||||||
;;; name from a header, and we have no opinion about it.
|
|
||||||
(define (c-primitive? t)
|
|
||||||
(and (prim-type? t)
|
|
||||||
(every (lambda (word) (memq word +known-words+)) (prim-name t))))
|
|
||||||
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
;;; Unification
|
|
||||||
;;; ---------------------------------------------------------------
|
|
||||||
|
|
||||||
;;; FORM is carried only so a failure can say where it was written.
|
|
||||||
(define (unify t1 t2 form)
|
|
||||||
(let ((a (resolve t1))
|
|
||||||
(b (resolve t2)))
|
|
||||||
(cond
|
|
||||||
((eq? a b) #t)
|
|
||||||
((tvar? a) (bind-tvar! a b form))
|
|
||||||
((tvar? b) (bind-tvar! b a form))
|
|
||||||
;; A typedef unifies as what it stands for. Its name survives in
|
|
||||||
;; whichever side is printed later, since neither side is rebuilt.
|
|
||||||
((alias-type? a) (unify (alias-expansion a) b form))
|
|
||||||
((alias-type? b) (unify a (alias-expansion b) form))
|
|
||||||
((and (prim-type? a) (prim-type? b))
|
|
||||||
(check-quals a b form)
|
|
||||||
(or (equal? (prim-name a) (prim-name b))
|
|
||||||
(type-mismatch a b form)))
|
|
||||||
((and (ptr-type? a) (ptr-type? b))
|
|
||||||
(check-quals a b form)
|
|
||||||
(unify (ptr-target a) (ptr-target b) form))
|
|
||||||
((and (array-type? a) (array-type? b))
|
|
||||||
;; One of them may be `(¤ int)': an unwritten length constrains
|
|
||||||
;; nothing, the way it does not in C either.
|
|
||||||
(when (and (array-size a) (array-size b)
|
|
||||||
(not (equal? (array-size a) (array-size b))))
|
|
||||||
(type-mismatch a b form))
|
|
||||||
(unify (array-elt a) (array-elt b) form))
|
|
||||||
((and (fn-type? a) (fn-type? b))
|
|
||||||
(unless (and (= (length (fn-args a)) (length (fn-args b)))
|
|
||||||
(eq? (fn-variadic? a) (fn-variadic? b)))
|
|
||||||
(type-mismatch a b form))
|
|
||||||
(unify (fn-ret a) (fn-ret b) form)
|
|
||||||
(for-each (lambda (x y) (unify x y form)) (fn-args a) (fn-args b))
|
|
||||||
#t)
|
|
||||||
((and (agg-type? a) (agg-type? b))
|
|
||||||
(check-quals a b form)
|
|
||||||
(or (and (eq? (agg-kind a) (agg-kind b))
|
|
||||||
(if (and (agg-name a) (agg-name b))
|
|
||||||
(eq? (agg-name a) (agg-name b))
|
|
||||||
(equal? (agg-spelling a) (agg-spelling b))))
|
|
||||||
(type-mismatch a b form)))
|
|
||||||
(else (type-mismatch a b form)))))
|
|
||||||
|
|
||||||
(define (type-mismatch a b form)
|
|
||||||
(sex-error form "type mismatch: expected"
|
|
||||||
(unparse-type a) 'got (unparse-type b)))
|
|
||||||
|
|
||||||
;;; Qualifiers are compared, and a mismatch is a warning rather than a
|
|
||||||
;;; failure: C's const-correctness is not this pass's fight yet, and
|
|
||||||
;;; making it one would reject programs that compile today.
|
|
||||||
(define (check-quals a b form)
|
|
||||||
(let ((qa (type-quals a))
|
|
||||||
(qb (type-quals b)))
|
|
||||||
(unless (lset= eq? qa qb)
|
|
||||||
(sex-warning form "qualifiers differ between"
|
|
||||||
(unparse-type a) "and" (unparse-type b)))))
|
|
||||||
|
|
||||||
(define (bind-tvar! v t form)
|
|
||||||
(cond
|
|
||||||
;; Without recursive types this cannot trigger. It is four lines,
|
|
||||||
;; and the alternative to having it is a hang.
|
|
||||||
((occurs? v t) (sex-error form "recursive type" (unparse-type v)))
|
|
||||||
(else (tvar-ref-set! v (with-quals t (tvar-quals v))) #t)))
|
|
||||||
|
|
||||||
(define (occurs? v type)
|
|
||||||
(let ((t (resolve type)))
|
|
||||||
(cond ((eq? v t) #t)
|
|
||||||
((ptr-type? t) (occurs? v (ptr-target t)))
|
|
||||||
((array-type? t) (occurs? v (array-elt t)))
|
|
||||||
((alias-type? t) (occurs? v (alias-expansion t)))
|
|
||||||
((fn-type? t) (or (occurs? v (fn-ret t))
|
|
||||||
(any (lambda (a) (occurs? v a)) (fn-args t))))
|
|
||||||
(else #f))))
|
|
||||||
@@ -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)~.
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
;;; Threading macros
|
|
||||||
;;;
|
|
||||||
;;; `->' passes a value through a chain of forms, each step taking what
|
|
||||||
;;; came before it as its first argument, so a chain of calls reads in
|
|
||||||
;;; the order it happens rather than inside out. Clojure spells it this
|
|
||||||
;;; way and this is the same thing:
|
|
||||||
;;;
|
|
||||||
;;; (-> 5 double-it (add 3)) == (add (double-it 5) 3)
|
|
||||||
;;;
|
|
||||||
;;; A step that is not a list is a call of one argument, so `(-> x f)'
|
|
||||||
;;; is `(f x)' and a method is a step like any other.
|
|
||||||
|
|
||||||
(pub defmacro (-> x . steps)
|
|
||||||
(let thread ((acc x) (steps steps))
|
|
||||||
(if (null? steps)
|
|
||||||
acc
|
|
||||||
(thread (if (pair? (car steps))
|
|
||||||
(cons (car (car steps)) (cons acc (cdr (car steps))))
|
|
||||||
(list (car steps) acc))
|
|
||||||
(cdr steps)))))
|
|
||||||
3
reader.module.scm
Normal file
3
reader.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module reader (read-from-file
|
||||||
|
read-raw-forms)
|
||||||
|
"reader.scm")
|
||||||
413
reader.scm
413
reader.scm
@@ -7,8 +7,6 @@
|
|||||||
;;; - a leading `.' rewritten to the symbol `dot-access'
|
;;; - a leading `.' rewritten to the symbol `dot-access'
|
||||||
;;; - `;' comments preserved as (comment "...") forms, so they can be
|
;;; - `;' comments preserved as (comment "...") forms, so they can be
|
||||||
;;; re-emitted into the generated C (keeping the source mapping)
|
;;; re-emitted into the generated C (keeping the source mapping)
|
||||||
;;; - #+ / #- feature expressions, which decide at read time what the
|
|
||||||
;;; compiler gets to see at all
|
|
||||||
;;; It also records the source location of every form it reads (see
|
;;; It also records the source location of every form it reads (see
|
||||||
;;; utils' form-source), so the C writer can emit #line directives.
|
;;; utils' form-source), so the C writer can emit #line directives.
|
||||||
|
|
||||||
@@ -16,28 +14,9 @@
|
|||||||
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 port) ; open-input-string
|
|
||||||
(only (chicken string) substring-index)
|
|
||||||
(only srfi-1 every any) ; srfi-1 also has an append-reverse
|
|
||||||
utils)
|
utils)
|
||||||
|
|
||||||
(export
|
|
||||||
read-from-file
|
|
||||||
read-raw-forms
|
|
||||||
read-sex-string
|
|
||||||
|
|
||||||
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))
|
||||||
@@ -55,13 +34,11 @@
|
|||||||
(define (peek port)
|
(define (peek port)
|
||||||
(peek-char port))
|
(peek-char port))
|
||||||
|
|
||||||
;;; Record where a form started and where it ended. Called with the
|
;;; Record where a form started. Called with the line of the opening
|
||||||
;;; line of the opening delimiter, sampled before it is consumed, once
|
;;; delimiter, sampled before it is consumed
|
||||||
;;; the form itself has been read -- so the current line is the one its
|
|
||||||
;;; closing delimiter sits on
|
|
||||||
(define (stamp form line)
|
(define (stamp form line)
|
||||||
(when (pair? form)
|
(when (pair? form)
|
||||||
(set-form-source! form (current-source-file) line (current-line)))
|
(set-form-source! form (current-source-file) line))
|
||||||
form)
|
form)
|
||||||
|
|
||||||
(define (delimiter? c)
|
(define (delimiter? c)
|
||||||
@@ -102,18 +79,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)
|
||||||
@@ -134,31 +111,13 @@
|
|||||||
((eq? tok dot-token) (error "Unexpected ."))
|
((eq? tok dot-token) (error "Unexpected ."))
|
||||||
(else tok))))
|
(else tok))))
|
||||||
|
|
||||||
;;; A token that stands for a datum
|
|
||||||
(define (datum-token? tok)
|
|
||||||
(not (or (eof-object? tok)
|
|
||||||
(eq? tok close-paren)
|
|
||||||
(eq? tok close-bracket)
|
|
||||||
(eq? tok dot-token))))
|
|
||||||
|
|
||||||
;;; next-token, sans the comments
|
|
||||||
(define (next-code-token port)
|
|
||||||
(let loop ()
|
|
||||||
(let ((tok (next-token port)))
|
|
||||||
(if (comment-form? tok)
|
|
||||||
(loop)
|
|
||||||
tok))))
|
|
||||||
|
|
||||||
;;; 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)
|
||||||
@@ -195,187 +154,13 @@
|
|||||||
(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)
|
(else (string->symbol s))))
|
||||||
(error
|
|
||||||
"a leading 0 is octal to C; write the number without it, or #o for octal"
|
|
||||||
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
|
;;; #-dispatch: booleans, characters, vectors, block/datum comments
|
||||||
;;; 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
|
|
||||||
;;; numbers: the C written from them says 224 and 5
|
|
||||||
(define (radix-number s)
|
|
||||||
(let ((radix (c-radix s)))
|
|
||||||
(and radix
|
|
||||||
(let* ((negative? (char=? #\- (string-ref s 0)))
|
|
||||||
(body (substring s (if negative? 3 2))))
|
|
||||||
(and (not (memv (string-ref body 0) '(#\+ #\-)))
|
|
||||||
(let ((n (string->number body radix)))
|
|
||||||
(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
|
|
||||||
;;; a dash, and an operator that does goes on with a non-letter: -> --
|
|
||||||
(define (negated-name? s)
|
|
||||||
(and (negating?)
|
|
||||||
(> (string-length s) 1)
|
|
||||||
(char=? #\- (string-ref s 0))
|
|
||||||
(let ((c (string-ref s 1)))
|
|
||||||
(or (char-alphabetic? c) (char=? c #\_)))))
|
|
||||||
|
|
||||||
;;; #-dispatch: booleans, characters, vectors, numbers in a radix,
|
|
||||||
;;; block/datum comments, feature expressions
|
|
||||||
(define (read-hash port)
|
(define (read-hash port)
|
||||||
(let ((c (get-ch port)))
|
(let ((c (get-ch port)))
|
||||||
(cond
|
(cond
|
||||||
@@ -383,71 +168,11 @@
|
|||||||
((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 '(#\b #\B)) (read-radix port 2))
|
|
||||||
((memv c '(#\o #\O)) (read-radix port 8))
|
|
||||||
((char=? c #\|) (skip-block-comment port 1) (next-token port))
|
((char=? c #\|) (skip-block-comment port 1) (next-token port))
|
||||||
((char=? c #\;) (read-datum port) (next-token port)) ; datum comment
|
((char=? c #\;) (read-datum port) (next-token port)) ; datum comment
|
||||||
((char=? c #\+) (read-conditional port #t))
|
|
||||||
((char=? c #\-) (read-conditional port #f))
|
|
||||||
(else (error "Unsupported # syntax" c)))))
|
(else (error "Unsupported # syntax" c)))))
|
||||||
|
|
||||||
;;; Feature expressions
|
|
||||||
;;;
|
|
||||||
;;; #+linux (include GL/gl.h) kept on Linux
|
|
||||||
;;; #-macosx (foo) kept only on other than macOS
|
|
||||||
;;; #+(and unix (not macosx)) (bar) and / or / not combine them
|
|
||||||
;;;
|
|
||||||
(define (platform-features)
|
|
||||||
(list (software-version) (software-type) (machine-type)))
|
|
||||||
|
|
||||||
;;; The host's features are the default, so anything reading Sex sees
|
|
||||||
;;; what the compiler would. sexc rebinds this to add --features
|
|
||||||
(define current-features (make-parameter (platform-features)))
|
|
||||||
|
|
||||||
(define (feature-true? test)
|
|
||||||
(cond
|
|
||||||
((symbol? test) (and (memq test (current-features)) #t))
|
|
||||||
((pair? test)
|
|
||||||
(case (car test)
|
|
||||||
((and) (every feature-true? (cdr test)))
|
|
||||||
((or) (any feature-true? (cdr test)))
|
|
||||||
((not)
|
|
||||||
(if (and (pair? (cdr test)) (null? (cddr test)))
|
|
||||||
(not (feature-true? (cadr test)))
|
|
||||||
(error "Feature expression `not' takes exactly one operand" test)))
|
|
||||||
(else (error "Unknown operator in feature expression" (car test)))))
|
|
||||||
(else (error "Malformed feature expression" test))))
|
|
||||||
|
|
||||||
;;; The #-/#+ preceded datum is always read -- there is no other way
|
|
||||||
;;; to know where it ends -- and then either returned or dropped. What
|
|
||||||
;;; follows a dropped datum is read in its place: `#+x #+y (a) (b)'
|
|
||||||
;;; with only x is (b).
|
|
||||||
;;;
|
|
||||||
;;; That next thing may be nothing: the end of the file, or the
|
|
||||||
;;; paren closing the list we are in
|
|
||||||
(define (read-conditional port keep-when)
|
|
||||||
(let* ((test (next-code-token port))
|
|
||||||
(keep (begin
|
|
||||||
(unless (datum-token? test)
|
|
||||||
(error "Unexpected end of input in feature expression"))
|
|
||||||
(eq? keep-when (feature-true? test))))
|
|
||||||
(guarded (next-code-token port)))
|
|
||||||
(cond
|
|
||||||
(keep guarded)
|
|
||||||
;; A datum was dropped, so the next one stands in for it
|
|
||||||
((datum-token? guarded) (next-token port))
|
|
||||||
(else guarded))))
|
|
||||||
|
|
||||||
;;; #x80, #b101, #o10
|
|
||||||
(define (read-radix port radix)
|
|
||||||
(let* ((digits (read-atom-string port))
|
|
||||||
(n (string->number (or (ungrouped digits radix) digits) radix)))
|
|
||||||
(if (exact-integer? n)
|
|
||||||
n
|
|
||||||
(error "Malformed number" digits))))
|
|
||||||
|
|
||||||
;;; #t / #true / #f / #false. `val' is the boolean; consume any
|
;;; #t / #true / #f / #false. `val' is the boolean; consume any
|
||||||
;;; trailing name characters and validate
|
;;; trailing name characters and validate
|
||||||
(define (read-bool port val)
|
(define (read-bool port val)
|
||||||
@@ -471,15 +196,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 "")
|
||||||
@@ -499,65 +219,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)
|
||||||
@@ -572,31 +249,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
|
||||||
@@ -615,9 +282,3 @@
|
|||||||
(parameterize ((current-source-file "stdin"))
|
(parameterize ((current-source-file "stdin"))
|
||||||
(parse-all (current-input-port)))
|
(parse-all (current-input-port)))
|
||||||
(read-from-file input-source)))
|
(read-from-file input-source)))
|
||||||
|
|
||||||
;;; TEXT is a buffer the editor holds, named SOURCE-FILE so locations
|
|
||||||
;;; and imports agree with the file it will be saved as.
|
|
||||||
(define (read-sex-string text source-file)
|
|
||||||
(parameterize ((current-source-file source-file))
|
|
||||||
(parse-all (open-input-string text))))
|
|
||||||
|
|||||||
2
semen.module.scm
Normal file
2
semen.module.scm
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
(module semen ()
|
||||||
|
"semen.scm")
|
||||||
351
sex-fmt-c.scm
351
sex-fmt-c.scm
@@ -14,7 +14,6 @@
|
|||||||
c-in-expr c-in-stmt c-in-test
|
c-in-expr c-in-stmt c-in-test
|
||||||
c-paren c-maybe-paren c-type c-literal? c-literal char->c-char
|
c-paren c-maybe-paren c-type c-literal? c-literal char->c-char
|
||||||
c-struct c-union c-class c-enum c-typedef c-cast
|
c-struct c-union c-class c-enum c-typedef c-cast
|
||||||
c-braced-list c-compound c-designate
|
|
||||||
c-expr c-expr/sexp c-apply c-op c-indent c-current-indent-string
|
c-expr c-expr/sexp c-apply c-op c-indent c-current-indent-string
|
||||||
c-wrap-stmt c-open-brace c-close-brace
|
c-wrap-stmt c-open-brace c-close-brace
|
||||||
c-block c-braced-block c-begin
|
c-block c-braced-block c-begin
|
||||||
@@ -36,7 +35,6 @@
|
|||||||
scheme
|
scheme
|
||||||
(scheme base) ; string->utf8, bytevector accessors
|
(scheme base) ; string->utf8, bytevector accessors
|
||||||
(chicken base)
|
(chicken base)
|
||||||
(chicken flonum) ; flonum-print-precision
|
|
||||||
fmt
|
fmt
|
||||||
srfi-1
|
srfi-1
|
||||||
srfi-13)
|
srfi-13)
|
||||||
@@ -81,7 +79,6 @@
|
|||||||
((dot arrow post-decrement post-increment) 10)
|
((dot arrow post-decrement post-increment) 10)
|
||||||
((**) 15) ; Perl
|
((**) 15) ; Perl
|
||||||
((unary+ unary- ! ~ cast unary-* unary-& sizeof) 20) ; ++ --
|
((unary+ unary- ! ~ cast unary-* unary-& sizeof) 20) ; ++ --
|
||||||
((cast-operand) 25) ; see c-cast
|
|
||||||
((=~ !~) 25) ; Perl
|
((=~ !~) 25) ; Perl
|
||||||
((* / %) 30)
|
((* / %) 30)
|
||||||
((+ -) 35)
|
((+ -) 35)
|
||||||
@@ -98,7 +95,6 @@
|
|||||||
;;((|\|\||) 75)
|
;;((|\|\||) 75)
|
||||||
;;((.. ...) 77) ; Perl
|
;;((.. ...) 77) ; Perl
|
||||||
((?) 80)
|
((?) 80)
|
||||||
((conditional-else) 81) ; see c-if/expr
|
|
||||||
((= *= /= %= &= ^= <<= >>=) 85) ; |\|=| ; += -=
|
((= *= /= %= &= ^= <<= >>=) 85) ; |\|=| ; += -=
|
||||||
((comma) 90)
|
((comma) 90)
|
||||||
((=>) 90) ; Perl
|
((=>) 90) ; Perl
|
||||||
@@ -113,26 +109,10 @@
|
|||||||
|
|
||||||
(define (c-paren x) (cat "(" (c-expr x) ")"))
|
(define (c-paren x) (cat "(" (c-expr x) ")"))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: a subscript is postfix, tighter than
|
|
||||||
;; any operator, so what it subscripts is written at the level of
|
|
||||||
;; `.' -- (* q) comes out `(*q)[i]', not `*q[i]', which is *(q[i]).
|
|
||||||
;; The index has brackets of its own and starts afresh.
|
|
||||||
(define (c-subscript array index)
|
|
||||||
(cat (c-with-op "." (c-expr array)) "[" (c-with-op 'paren (c-expr index)) "]"))
|
|
||||||
|
|
||||||
;; `.' and `->' associate left, and their right operand is always a
|
|
||||||
;; name, so a member access written inside another is the left one
|
|
||||||
;; and needs no parens of its own: `s.u.circle.r', not `((s.u).circle).r'
|
|
||||||
(define (c-member-op? x)
|
|
||||||
(let ((str (display-to-string x)))
|
|
||||||
(or (string=? str ".") (string=? str "->"))))
|
|
||||||
|
|
||||||
(define (c-maybe-paren op x)
|
(define (c-maybe-paren op x)
|
||||||
(lambda (st)
|
(lambda (st)
|
||||||
((fmt-let 'op op
|
((fmt-let 'op op
|
||||||
(if (and (c-op<= (fmt-op st) op)
|
(if (and (c-op<= (fmt-op st) op)
|
||||||
(not (and (c-member-op? (fmt-op st))
|
|
||||||
(c-member-op? op)))
|
|
||||||
(not (vector? x)))
|
(not (vector? x)))
|
||||||
(c-paren x)
|
(c-paren x)
|
||||||
x))
|
x))
|
||||||
@@ -193,43 +173,19 @@
|
|||||||
((8) (cat "0" (number->string x 8)))
|
((8) (cat "0" (number->string x 8)))
|
||||||
(else (dsp (number->string x))))
|
(else (dsp (number->string x))))
|
||||||
st))
|
st))
|
||||||
(dsp (c-format-flonum x))))
|
(dsp (number->string x))))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: a double in as few digits as read
|
|
||||||
;; back as the same double. number->string stops at
|
|
||||||
;; flonum-print-precision, 15 unless set, and 0.16666666666666666 came
|
|
||||||
;; out 0.166666666666667: a different double in the C. Seventeen
|
|
||||||
;; always do.
|
|
||||||
(define (c-format-flonum x)
|
|
||||||
(let ((precision (flonum-print-precision)))
|
|
||||||
(let try ((digits 15))
|
|
||||||
(flonum-print-precision digits)
|
|
||||||
(let ((written (number->string x)))
|
|
||||||
(if (or (= digits 17) (= (string->number written) x))
|
|
||||||
(begin (flonum-print-precision precision) written)
|
|
||||||
(try (+ digits 1)))))))
|
|
||||||
|
|
||||||
(define (c-format-string x)
|
(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)))))
|
||||||
|
|
||||||
@@ -282,9 +238,12 @@
|
|||||||
;; non C-keywords must have some character invalid in a C
|
;; non C-keywords must have some character invalid in a C
|
||||||
;; identifier to avoid conflicts - by default we prefix %
|
;; identifier to avoid conflicts - by default we prefix %
|
||||||
((vector-ref)
|
((vector-ref)
|
||||||
((c-wrap-stmt (c-subscript (cadr x) (caddr x))) st))
|
((c-wrap-stmt
|
||||||
|
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
|
||||||
|
st))
|
||||||
((vector-set!)
|
((vector-set!)
|
||||||
((c= (c-in-expr (c-subscript (cadr x) (caddr x)))
|
((c= (c-in-expr
|
||||||
|
(cat (c-expr (cadr x)) "[" (c-expr (caddr x)) "]"))
|
||||||
(c-expr (cadddr x)))
|
(c-expr (cadddr x)))
|
||||||
st))
|
st))
|
||||||
((extern/C) ((apply c-extern/C (cdr x)) st))
|
((extern/C) ((apply c-extern/C (cdr x)) st))
|
||||||
@@ -304,7 +263,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)
|
||||||
@@ -319,10 +277,6 @@
|
|||||||
((%comment) ((apply c-comment (cdr x)) st))
|
((%comment) ((apply c-comment (cdr x)) st))
|
||||||
((:) ((apply c-label (cdr x)) st))
|
((:) ((apply c-label (cdr x)) st))
|
||||||
((%cast) ((apply c-cast (cdr x)) st))
|
((%cast) ((apply c-cast (cdr x)) st))
|
||||||
((%sizeof-type) ((cat "sizeof(" (c-type (cadr x)) ")") st))
|
|
||||||
((%compound) ((apply c-compound (cdr x)) st))
|
|
||||||
((%designate) ((apply c-designate (cdr x)) st))
|
|
||||||
((%designate-index) ((apply c-designate-index (cdr x)) st))
|
|
||||||
((+ - & * / % ! ~ ^ && < > <= >= == != << >>
|
((+ - & * / % ! ~ ^ && < > <= >= == != << >>
|
||||||
= *= /= %= &= ^= >>= <<=) ; |\|| |\|\|| |\|=|
|
= *= /= %= &= ^= >>= <<=) ; |\|| |\|\|| |\|=|
|
||||||
((apply c-op x) st))
|
((apply c-op x) st))
|
||||||
@@ -340,6 +294,8 @@
|
|||||||
(cond
|
(cond
|
||||||
((eq? (car x) (string->symbol "."))
|
((eq? (car x) (string->symbol "."))
|
||||||
((apply c-op "." (cdr x)) st))
|
((apply c-op "." (cdr x)) st))
|
||||||
|
((eq? (car x) (string->symbol "->"))
|
||||||
|
((apply c-op "->" (cdr x)) st))
|
||||||
((eq? (car x) (string->symbol "++"))
|
((eq? (car x) (string->symbol "++"))
|
||||||
((apply c-op "++" (cdr x)) st))
|
((apply c-op "++" (cdr x)) st))
|
||||||
((eq? (car x) (string->symbol "--"))
|
((eq? (car x) (string->symbol "--"))
|
||||||
@@ -350,7 +306,17 @@
|
|||||||
((apply c-op "-=" (cdr x)) st))
|
((apply c-op "-=" (cdr x)) st))
|
||||||
(else ((c-apply x) st))))))
|
(else ((c-apply x) st))))))
|
||||||
((vector? x)
|
((vector? x)
|
||||||
((c-wrap-stmt (c-braced-list (vector->list x))) st))
|
((c-wrap-stmt
|
||||||
|
(fmt-try-fit
|
||||||
|
(fmt-let 'no-wrap? #t
|
||||||
|
(cat "{" (fmt-join c-expr (vector->list x) ", ") "}"))
|
||||||
|
(lambda (st)
|
||||||
|
(let* ((col (fmt-col st))
|
||||||
|
(sep (string-append "," (make-nl-space col))))
|
||||||
|
((cat "{" (fmt-join c-expr (vector->list x) sep)
|
||||||
|
"}" nl)
|
||||||
|
st)))))
|
||||||
|
st))
|
||||||
(else
|
(else
|
||||||
((c-literal x) st))))))
|
((c-literal x) st))))))
|
||||||
|
|
||||||
@@ -466,15 +432,6 @@
|
|||||||
((pair? x) (cons (replace (car x)) (replace (cdr x))))
|
((pair? x) (cons (replace (car x)) (replace (cdr x))))
|
||||||
(else x))))
|
(else x))))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: an object-like body is parenthesised
|
|
||||||
;; as a function-like one is. Upstream left it bare, so with
|
|
||||||
;; `#define D -1.0 / 6.0', `x * D' was `(x * -1.0) / 6.0'. Only a
|
|
||||||
;; name or a literal that cannot lose its sign to a neighbour is
|
|
||||||
;; left as written.
|
|
||||||
(define (c-atomic-body? x)
|
|
||||||
(or (symbol? x)
|
|
||||||
(and (c-literal? x) (not (and (number? x) (negative? x))))))
|
|
||||||
|
|
||||||
(define (cpp-define x . body)
|
(define (cpp-define x . body)
|
||||||
(define (name-of x) (c-expr (if (pair? x) (cadr x) x)))
|
(define (name-of x) (c-expr (if (pair? x) (cadr x) x)))
|
||||||
(lambda (st)
|
(lambda (st)
|
||||||
@@ -492,8 +449,9 @@
|
|||||||
(cat " "
|
(cat " "
|
||||||
(fmt-let 'writer (make-cpp-writer st)
|
(fmt-let 'writer (make-cpp-writer st)
|
||||||
(fmt-let 'macro-params params
|
(fmt-let 'macro-params params
|
||||||
((if (and (null? (cdr body))
|
((if (or (not (pair? x))
|
||||||
(c-atomic-body? (car body)))
|
(and (null? (cdr body))
|
||||||
|
(c-literal? (car body))))
|
||||||
(lambda (x) x)
|
(lambda (x) x)
|
||||||
c-paren)
|
c-paren)
|
||||||
(c-in-expr (apply c-begin body))))))
|
(c-in-expr (apply c-begin body))))))
|
||||||
@@ -620,33 +578,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,36 +634,22 @@
|
|||||||
"")
|
"")
|
||||||
(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))
|
||||||
(define (c-class . args) (apply c-struct/aux "class" args))
|
(define (c-class . args) (apply c-struct/aux "class" args))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: an enum may also be named without
|
|
||||||
;; being defined -- `enum color m;' -- exactly as c-struct/aux
|
|
||||||
;; already allows `struct point p;'. Upstream assumed a value list
|
|
||||||
;; was always present and mapped over whatever stood in its place.
|
|
||||||
(define (c-enum x . o)
|
(define (c-enum x . o)
|
||||||
(define (c-enum-one x)
|
(define (c-enum-one x)
|
||||||
(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 (car o) x)))
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: (enum mood * const) is a
|
(c-wrap-stmt
|
||||||
;; pointer, and its star was taken for the list of values
|
(cat
|
||||||
(if (pair? vals)
|
(c-braced-block
|
||||||
(c-wrap-stmt
|
(if name (cat "enum " name) (dsp "enum"))
|
||||||
(cat
|
(c-in-expr (apply c-begin (map c-enum-one vals))))))))
|
||||||
(c-braced-block
|
|
||||||
(if name (cat "enum " name) (dsp "enum"))
|
|
||||||
(c-in-expr (apply c-begin (map c-enum-one vals))))))
|
|
||||||
(c-wrap-stmt (cat "enum " name (or vals "") (c-type-words (if vals (cdr o) '())))))))
|
|
||||||
|
|
||||||
(define (c-attribute . args)
|
(define (c-attribute . args)
|
||||||
(cat "__attribute__ ((" (fmt-join c-expr args ", ") "))"))
|
(cat "__attribute__ ((" (fmt-join c-expr args ", ") "))"))
|
||||||
@@ -738,24 +665,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 +702,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,21 +727,14 @@
|
|||||||
(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
|
|
||||||
;; array parameter of a function type, where C has no room
|
|
||||||
;; for a name -- arrives as #f, and upstream printed it
|
|
||||||
((%array)
|
((%array)
|
||||||
(let ((name (cat (or name "") "[" (if (pair? (cddr type))
|
(let ((name (cat name "[" (if (pair? (cddr type))
|
||||||
(c-expr (caddr type))
|
(c-expr (caddr type))
|
||||||
"")
|
"")
|
||||||
"]")))
|
"]")))
|
||||||
(c-type (cadr type) name)))
|
(c-type (cadr type) name)))
|
||||||
((%pointer *)
|
((%pointer *)
|
||||||
@@ -838,13 +743,7 @@
|
|||||||
(if (and (pair? (cadr type)) (eq? '%array (caadr type)))
|
(if (and (pair? (cadr type)) (eq? '%array (caadr type)))
|
||||||
(c-paren name)
|
(c-paren name)
|
||||||
name))))
|
name))))
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: upstream passed the
|
((enum) (apply c-enum name (cdr type)))
|
||||||
;; declarator's name to c-enum as the enum's tag, so
|
|
||||||
;; `(var m (enum color))' emitted `enum m {...}' and lost the
|
|
||||||
;; variable. Enums are laid out like structs: the type, then
|
|
||||||
;; the name being declared.
|
|
||||||
((enum)
|
|
||||||
(cat (apply c-enum (cdr type)) (if name (cat " " name) "")))
|
|
||||||
((struct union class)
|
((struct union class)
|
||||||
(cat (apply c-struct/aux (car type) (cdr type)) (if name (cat " " name) "")))
|
(cat (apply c-struct/aux (car type) (cdr type)) (if name (cat " " name) "")))
|
||||||
(else (fmt-join/last c-expr (lambda (x) (c-type x name)) type " "))))
|
(else (fmt-join/last c-expr (lambda (x) (c-type x name)) type " "))))
|
||||||
@@ -858,21 +757,14 @@
|
|||||||
(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
|
|
||||||
;; array parameter of a function type, where C has no room
|
|
||||||
;; for a name -- arrives as #f, and upstream printed it
|
|
||||||
((%array)
|
((%array)
|
||||||
(let ((name (cat (or name "") "[" (if (pair? (cddr type))
|
(let ((name (cat name "[" (if (pair? (cddr type))
|
||||||
(c-expr (caddr type))
|
(c-expr (caddr type))
|
||||||
"")
|
"")
|
||||||
"]")))
|
"]")))
|
||||||
(c-type (cadr type) name)))
|
(c-type (cadr type) name)))
|
||||||
((%pointer *)
|
((%pointer *)
|
||||||
@@ -895,45 +787,32 @@
|
|||||||
(fmt-join c-expr name ", ")
|
(fmt-join c-expr name ", ")
|
||||||
(c-expr name))))))
|
(c-expr name))))))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: take part in precedence, both ways.
|
;; MODIFIED FROM UPSTREAM fmt-c: parenthesise a binary operand.
|
||||||
;;
|
;;
|
||||||
;; Upstream's bare (cat "(" type ")" expr) cast only the first operand
|
;; A cast binds tighter than every binary operator, so upstream's
|
||||||
;; of a looser one -- (cast (* 2 (sizeof GLfloat)) (* void)) came out
|
;; unparenthesised (cat "(" type ")" expr) silently casts only the
|
||||||
;; `(void *)2 * sizeof(GLfloat)' -- and was itself taken apart by a
|
;; first operand: (cast (* 2 (sizeof GLfloat)) (* void)) came out as
|
||||||
;; tighter operator around it: `(const wanted *)pa->distance'.
|
;; `(void *)2 * sizeof(GLfloat)'. Unary operands -- &x, *p, -n,
|
||||||
;;
|
;; sizeof, calls, identifiers, literals -- are already
|
||||||
;; The operand is written at `cast-operand', just looser than a unary
|
;; unary-expressions and are left alone, so this changes nothing that
|
||||||
;; operator, so a unary operand stays bare -- `(int *)&a' -- while
|
;; was previously correct.
|
||||||
;; anything looser parenthesises itself. The cast is parenthesised
|
(define c-binary-operators
|
||||||
;; only under something strictly tighter: `-(int)a', `*(int *)v'.
|
'(+ - * / % << >> < > <= >= == != & ^ && %and %or
|
||||||
|
= *= /= %= &= ^= <<= >>=))
|
||||||
|
|
||||||
|
(define (c-binary-expression? expr)
|
||||||
|
(and (pair? expr)
|
||||||
|
(memq (car expr) c-binary-operators)
|
||||||
|
(pair? (cdr expr))
|
||||||
|
(pair? (cddr expr)))) ; two or more operands
|
||||||
|
|
||||||
(define (c-cast type expr)
|
(define (c-cast type expr)
|
||||||
(lambda (st)
|
(cat "(" (c-type type) ")"
|
||||||
(let ((cast (cat "(" (c-type type) ")"
|
(if (c-binary-expression? expr)
|
||||||
(c-with-op 'cast-operand (c-expr expr)))))
|
;; c-with-op stops the operand from parenthesising itself
|
||||||
((if (c-op< (fmt-op st) 'cast) (c-paren cast) cast) st))))
|
;; a second time inside the parens we just added.
|
||||||
|
(cat "(" (c-with-op 'paren (c-expr expr)) ")")
|
||||||
;; { a, b, c } -- on one line if it fits, one element per line if not.
|
(c-expr expr))))
|
||||||
(define (c-braced-list ls)
|
|
||||||
(fmt-try-fit
|
|
||||||
(fmt-let 'no-wrap? #t (cat "{" (fmt-join c-expr ls ", ") "}"))
|
|
||||||
(lambda (st)
|
|
||||||
(let* ((col (fmt-col st))
|
|
||||||
(sep (string-append "," (make-nl-space col))))
|
|
||||||
((cat "{" (fmt-join c-expr ls sep) "}" nl) st)))))
|
|
||||||
|
|
||||||
;; (T){ ... } -- a C99 compound literal, not a cast: the result is an
|
|
||||||
;; unnamed object and an lvalue, so `&' on it is legal. At block scope
|
|
||||||
;; it lives until the end of the enclosing block and no longer.
|
|
||||||
(define (c-compound type . init)
|
|
||||||
(cat "(" (c-type type) ")" (c-braced-list init)))
|
|
||||||
|
|
||||||
;; .field = value, inside a braced list
|
|
||||||
(define (c-designate field 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
|
||||||
@@ -965,31 +844,20 @@
|
|||||||
tail))))
|
tail))))
|
||||||
st))))
|
st))))
|
||||||
|
|
||||||
;; MODIFIED FROM UPSTREAM fmt-c: parenthesised as the operator it is.
|
|
||||||
;; Upstream wrote it bare whatever surrounded it, and `?:' binds
|
|
||||||
;; looser than every binary operator: (/ 300 (if c c 1)) came out
|
|
||||||
;; `300 / c ? c : 1', a conditional on the quotient.
|
|
||||||
;;
|
|
||||||
;; It groups to the right, so its else arm is written at
|
|
||||||
;; `conditional-else', just looser: a chain there stays bare,
|
|
||||||
;; `a ? x : b ? y : z', and an assignment does not.
|
|
||||||
(define (c-if/expr c p . rest)
|
(define (c-if/expr c p . rest)
|
||||||
(c-maybe-paren
|
(let lp ((c c) (p p) (ls rest))
|
||||||
'?
|
(cond
|
||||||
(let lp ((c c) (p p) (ls rest))
|
((or (eq? c 'else) (eq? c #t))
|
||||||
(cond
|
(if (not (null? ls))
|
||||||
((or (eq? c 'else) (eq? c #t))
|
(error "forms after else clause in IF" c p ls)
|
||||||
(if (not (null? ls))
|
(c-expr p)))
|
||||||
(error "forms after else clause in IF" c p ls)
|
((pair? ls)
|
||||||
(c-expr p)))
|
(cat (c-in-test (c-expr c)) " ? " (c-expr p) " : "
|
||||||
((pair? ls)
|
(if (pair? (cdr ls))
|
||||||
(cat (c-in-test (c-expr c)) " ? " (c-expr p) " : "
|
(lp (car ls) (cadr ls) (cddr ls))
|
||||||
(c-with-op 'conditional-else
|
(lp 'else (car ls) '()))))
|
||||||
(if (pair? (cdr ls))
|
(else
|
||||||
(lp (car ls) (cadr ls) (cddr ls))
|
(c-or (c-in-test (c-expr c)) (c-expr p))))))
|
||||||
(lp 'else (car ls) '())))))
|
|
||||||
(else
|
|
||||||
(c-or (c-in-test (c-expr c)) (c-expr p)))))))
|
|
||||||
|
|
||||||
(define (c-if . args)
|
(define (c-if . args)
|
||||||
(fmt-if fmt-expression?
|
(fmt-if fmt-expression?
|
||||||
@@ -1117,30 +985,9 @@
|
|||||||
(cat nl (make-space (+ 2 (fmt-col st))) str " "))
|
(cat nl (make-space (+ 2 (fmt-col st))) str " "))
|
||||||
st))))))))))
|
st))))))))))
|
||||||
|
|
||||||
;; `-' arrives as the symbol binary minus uses, and so with binary
|
|
||||||
;; precedence: `(+ (- b) b)' asked under that spelling comes out
|
|
||||||
;; `(-b) + b'.
|
|
||||||
(define (unary-operator op)
|
|
||||||
(case op
|
|
||||||
((-) 'unary-)
|
|
||||||
((+) 'unary+)
|
|
||||||
((*) 'unary-*)
|
|
||||||
((&) 'unary-&)
|
|
||||||
(else op)))
|
|
||||||
|
|
||||||
;; Parenthesises the whole expression rather than the operand: the
|
|
||||||
;; other way round, `(. (* p) x)' came out `*(p).x', which C reads as
|
|
||||||
;; `*(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)
|
(cat (display-to-string op) (c-maybe-paren op (c-expr x)))))
|
||||||
(cat (display-to-string op)
|
|
||||||
(if (and (number? x)
|
|
||||||
(char=? #\- (string-ref (number->string x) 0)))
|
|
||||||
(c-paren x)
|
|
||||||
(c-expr x))))))
|
|
||||||
|
|
||||||
;; some convenience definitions
|
;; some convenience definitions
|
||||||
|
|
||||||
|
|||||||
178
sex-lsp.el
178
sex-lsp.el
@@ -1,178 +0,0 @@
|
|||||||
;;; sex-lsp.el --- Language server client for Sex -*- 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:
|
|
||||||
|
|
||||||
;; Client for `sex-lsp', the Sex language server.
|
|
||||||
|
|
||||||
;; `sex-c-backend' set to `clangd' asks the server for C headers too.
|
|
||||||
|
|
||||||
;;; Code:
|
|
||||||
|
|
||||||
(require 'sex-mode)
|
|
||||||
(require 'thingatpt)
|
|
||||||
|
|
||||||
(defgroup sex-lsp nil
|
|
||||||
"Language server client for Sex."
|
|
||||||
:prefix "sex-"
|
|
||||||
:group 'sex-mode)
|
|
||||||
|
|
||||||
(defcustom sex-lsp-program "sex-lsp"
|
|
||||||
"Program that speaks LSP for Sex."
|
|
||||||
:type 'string
|
|
||||||
:group 'sex-lsp)
|
|
||||||
|
|
||||||
(defcustom sex-sexc-program "sexc"
|
|
||||||
"sexc, used by sexpand when no language server is running."
|
|
||||||
:type 'string
|
|
||||||
:group 'sex-lsp)
|
|
||||||
|
|
||||||
(defcustom sex-c-backend nil
|
|
||||||
"C header backend for `sex-lsp'.
|
|
||||||
nil leaves C names to the C compiler. `clangd' asks clangd."
|
|
||||||
:type '(choice (const nil) (const clangd))
|
|
||||||
:group 'sex-lsp)
|
|
||||||
|
|
||||||
(defcustom sex-cflags nil
|
|
||||||
"C compiler flags for the clangd probe, as one string of words."
|
|
||||||
:type '(choice (const nil) string)
|
|
||||||
:group 'sex-lsp)
|
|
||||||
|
|
||||||
(defun sex-lsp-command (&optional _interactive)
|
|
||||||
"The `sex-lsp' command line, including the C backend when one is set."
|
|
||||||
(append (list sex-lsp-program)
|
|
||||||
(and (eq sex-c-backend 'clangd) '("--c-backend=clangd"))
|
|
||||||
(and sex-cflags (not (string-empty-p sex-cflags))
|
|
||||||
(list (concat "--cflags=" sex-cflags)))))
|
|
||||||
|
|
||||||
(define-key sex-mode-map (kbd "C-c C-e") #'sexpand)
|
|
||||||
(define-key sex-mode-map (kbd "C-c C-d") #'sexpand-defun)
|
|
||||||
(define-key sex-mode-map (kbd "C-c C-b") #'sexpand-buffer)
|
|
||||||
(define-key sex-mode-map (kbd "C-c C-r") #'sexpand-region)
|
|
||||||
|
|
||||||
(defun sex-lsp-running-p ()
|
|
||||||
"Whether this buffer has an eglot or lsp-mode server."
|
|
||||||
(or (and (fboundp 'eglot-current-server) (eglot-current-server))
|
|
||||||
(and (fboundp 'lsp-workspaces) (lsp-workspaces))))
|
|
||||||
|
|
||||||
(defun sex-buffer-uri ()
|
|
||||||
"The LSP URI of the current buffer."
|
|
||||||
(cond
|
|
||||||
((and (fboundp 'eglot-path-to-uri) buffer-file-name)
|
|
||||||
(eglot-path-to-uri buffer-file-name))
|
|
||||||
((and (fboundp 'lsp--buffer-uri) (lsp--buffer-uri)))
|
|
||||||
(buffer-file-name (concat "file://" buffer-file-name))))
|
|
||||||
|
|
||||||
(defun sex--field (object key)
|
|
||||||
"KEY's value in a plist or hash-table OBJECT. KEY is a symbol."
|
|
||||||
(cond
|
|
||||||
((hash-table-p object) (gethash (symbol-name key) object))
|
|
||||||
((listp object)
|
|
||||||
(plist-get object (intern (concat ":" (symbol-name key)))))))
|
|
||||||
|
|
||||||
(defun sex-lsp-request (method params)
|
|
||||||
"Send METHOD to whichever LSP client is managing this buffer.
|
|
||||||
METHOD is a string, such as \"sex/expand\". PARAMS is a plist."
|
|
||||||
(cond
|
|
||||||
((and (fboundp 'eglot-current-server) (eglot-current-server))
|
|
||||||
(jsonrpc-request (eglot-current-server)
|
|
||||||
(intern (concat ":" method))
|
|
||||||
params))
|
|
||||||
((and (fboundp 'lsp-workspaces) (lsp-workspaces))
|
|
||||||
(lsp-request method params))))
|
|
||||||
|
|
||||||
(defun sex-show-c (text)
|
|
||||||
"Show TEXT in `*sexpand*' under a C mode."
|
|
||||||
(let ((buffer (get-buffer-create "*sexpand*")))
|
|
||||||
(with-current-buffer buffer
|
|
||||||
(let ((inhibit-read-only t))
|
|
||||||
(erase-buffer)
|
|
||||||
(insert text)
|
|
||||||
(goto-char (point-min))
|
|
||||||
(if (fboundp 'c-ts-mode) (c-ts-mode) (c-mode))))
|
|
||||||
(pop-to-buffer buffer)))
|
|
||||||
|
|
||||||
(defun sex-expand-via-server (start end)
|
|
||||||
"Ask the language server for the C of lines START through END.
|
|
||||||
END nil is the whole buffer."
|
|
||||||
(let ((uri (sex-buffer-uri)))
|
|
||||||
(when (and uri (sex-lsp-running-p))
|
|
||||||
(let ((params (list :textDocument (list :uri uri) :startLine start)))
|
|
||||||
(when end (setq params (append params (list :endLine end))))
|
|
||||||
(sex--field (sex-lsp-request "sex/expand" params) 'text)))))
|
|
||||||
|
|
||||||
(defun sex-expand-via-cli (start end)
|
|
||||||
"Run sexc --expand-lines on the buffer. END nil is the whole buffer."
|
|
||||||
(let ((spec (if end
|
|
||||||
(format "--expand-lines=%d:%d" start end)
|
|
||||||
"--expand-lines=1"))
|
|
||||||
(output (generate-new-buffer " *sexpand*")))
|
|
||||||
(unwind-protect
|
|
||||||
(when (eq 0 (call-process-region (point-min) (point-max)
|
|
||||||
sex-sexc-program nil output nil
|
|
||||||
spec "-"))
|
|
||||||
(with-current-buffer output (buffer-string)))
|
|
||||||
(kill-buffer output))))
|
|
||||||
|
|
||||||
(defun sex-expand-lines (start end)
|
|
||||||
"Show the C generated for lines START through END."
|
|
||||||
(let ((text (or (ignore-errors (sex-expand-via-server start end))
|
|
||||||
(sex-expand-via-cli start end))))
|
|
||||||
(if text
|
|
||||||
(sex-show-c text)
|
|
||||||
(error "sexpand produced no C"))))
|
|
||||||
|
|
||||||
;;;###autoload
|
|
||||||
(defun sexpand ()
|
|
||||||
"Show the C for the sexp at point."
|
|
||||||
(interactive)
|
|
||||||
(let ((bounds (bounds-of-thing-at-point 'sexp)))
|
|
||||||
(unless bounds (error "No sexp at point"))
|
|
||||||
(sex-expand-lines (line-number-at-pos (car bounds))
|
|
||||||
(line-number-at-pos (1- (cdr bounds))))))
|
|
||||||
|
|
||||||
;;;###autoload
|
|
||||||
(defun sexpand-defun ()
|
|
||||||
"Show the C for the top-level form at point."
|
|
||||||
(interactive)
|
|
||||||
(save-excursion
|
|
||||||
(beginning-of-defun)
|
|
||||||
(let ((start (line-number-at-pos)))
|
|
||||||
(end-of-defun)
|
|
||||||
(sex-expand-lines start (line-number-at-pos (1- (point)))))))
|
|
||||||
|
|
||||||
;;;###autoload
|
|
||||||
(defun sexpand-region (begin end)
|
|
||||||
"Show the C for the lines of the region."
|
|
||||||
(interactive "r")
|
|
||||||
(sex-expand-lines (line-number-at-pos begin) (line-number-at-pos end)))
|
|
||||||
|
|
||||||
;;;###autoload
|
|
||||||
(defun sexpand-buffer ()
|
|
||||||
"Show the C for the whole buffer."
|
|
||||||
(interactive)
|
|
||||||
(sex-expand-lines 1 nil))
|
|
||||||
|
|
||||||
(with-eval-after-load 'eglot
|
|
||||||
(add-to-list 'eglot-server-programs '(sex-mode . sex-lsp-command)))
|
|
||||||
|
|
||||||
(with-eval-after-load 'lsp-mode
|
|
||||||
(add-to-list 'lsp-language-id-configuration '(sex-mode . "sex"))
|
|
||||||
(lsp-register-client
|
|
||||||
(make-lsp-client
|
|
||||||
:new-connection (lsp-stdio-connection #'sex-lsp-command)
|
|
||||||
:activation-fn (lambda (_file-name _mode) (derived-mode-p 'sex-mode))
|
|
||||||
:major-modes '(sex-mode)
|
|
||||||
:priority 1
|
|
||||||
:server-id 'sex-lsp)))
|
|
||||||
|
|
||||||
(provide 'sex-lsp)
|
|
||||||
;;; sex-lsp.el ends here
|
|
||||||
889
sex-lsp.scm
889
sex-lsp.scm
@@ -1,889 +0,0 @@
|
|||||||
;;; Sex language server. Speaks LSP on stdin and stdout. Sex names,
|
|
||||||
;;; diagnostics, and expansion come from sex-query. C headers, when
|
|
||||||
;;; asked for with --c-backend=clangd, come from a clangd process
|
|
||||||
;;; looking at a probe of the unit's includes, not at a translation of
|
|
||||||
;;; the buffer.
|
|
||||||
|
|
||||||
(import scheme
|
|
||||||
(scheme base)
|
|
||||||
(chicken base)
|
|
||||||
(chicken condition)
|
|
||||||
(chicken file)
|
|
||||||
(chicken file posix)
|
|
||||||
(chicken io)
|
|
||||||
(chicken pathname)
|
|
||||||
(chicken port)
|
|
||||||
(chicken process)
|
|
||||||
(chicken process-context)
|
|
||||||
(chicken string)
|
|
||||||
medea
|
|
||||||
sex-query
|
|
||||||
srfi-1
|
|
||||||
srfi-13
|
|
||||||
srfi-69)
|
|
||||||
|
|
||||||
(define c-backend #f)
|
|
||||||
(define extra-cflags "")
|
|
||||||
|
|
||||||
(define (parse-args args)
|
|
||||||
(for-each
|
|
||||||
(lambda (arg)
|
|
||||||
(cond
|
|
||||||
((equal? arg "--c-backend=clangd") (set! c-backend 'clangd))
|
|
||||||
((equal? arg "--c-backend=none") (set! c-backend #f))
|
|
||||||
((and (> (string-length arg) 9) (string=? (substring arg 0 9) "--cflags="))
|
|
||||||
(set! extra-cflags (substring arg 9)))
|
|
||||||
(else (error "sex-lsp: unknown argument" arg))))
|
|
||||||
args))
|
|
||||||
|
|
||||||
;;; ------------------------------------------------------------------
|
|
||||||
;;; LSP framing. stdout is the protocol, so nothing else may write it.
|
|
||||||
|
|
||||||
(define (strip-cr line)
|
|
||||||
(let ((n (string-length line)))
|
|
||||||
(if (and (> n 0) (char=? (string-ref line (- n 1)) #\return))
|
|
||||||
(substring line 0 (- n 1))
|
|
||||||
line)))
|
|
||||||
|
|
||||||
(define (prefix-ci? prefix text)
|
|
||||||
(and (<= (string-length prefix) (string-length text))
|
|
||||||
(string-ci=? prefix (substring text 0 (string-length prefix)))))
|
|
||||||
|
|
||||||
(define (read-headers port)
|
|
||||||
(let loop ((len #f))
|
|
||||||
(let ((line (read-line port)))
|
|
||||||
(cond
|
|
||||||
((eof-object? line) #f)
|
|
||||||
(else
|
|
||||||
(let ((line (strip-cr line)))
|
|
||||||
(cond
|
|
||||||
((string=? line "") len)
|
|
||||||
((prefix-ci? "content-length:" line)
|
|
||||||
(loop (string->number (string-trim (substring line 15)))))
|
|
||||||
(else (loop len)))))))))
|
|
||||||
|
|
||||||
(define (read-message port)
|
|
||||||
(let ((len (read-headers port)))
|
|
||||||
(and len
|
|
||||||
(let ((payload (read-string len port)))
|
|
||||||
(and (string? payload)
|
|
||||||
(= (string-length payload) len)
|
|
||||||
(call-with-input-string payload read-json))))))
|
|
||||||
|
|
||||||
(define (write-message obj)
|
|
||||||
(let ((json (json->string obj)))
|
|
||||||
(display "Content-Length: ")
|
|
||||||
(display (string-length json))
|
|
||||||
(display "\r\n\r\n")
|
|
||||||
(display json)
|
|
||||||
(flush-output)))
|
|
||||||
|
|
||||||
(define (jref obj key)
|
|
||||||
(and (pair? obj)
|
|
||||||
(let ((cell (assoc key obj)))
|
|
||||||
(and cell (cdr cell)))))
|
|
||||||
|
|
||||||
(define (msg-id msg)
|
|
||||||
(let ((cell (and (pair? msg) (assoc 'id msg))))
|
|
||||||
(and cell (cdr cell))))
|
|
||||||
|
|
||||||
(define (msg-method msg)
|
|
||||||
(let ((m (jref msg 'method)))
|
|
||||||
(and (string? m) m)))
|
|
||||||
|
|
||||||
(define (reply id result)
|
|
||||||
(write-message `((jsonrpc . "2.0") (id . ,id) (result . ,result))))
|
|
||||||
|
|
||||||
(define (reply-error id code message)
|
|
||||||
(write-message `((jsonrpc . "2.0")
|
|
||||||
(id . ,id)
|
|
||||||
(error . ((code . ,code) (message . ,message))))))
|
|
||||||
|
|
||||||
(define (notify method params)
|
|
||||||
(write-message `((jsonrpc . "2.0") (method . ,method) (params . ,params))))
|
|
||||||
|
|
||||||
(define (pos line character)
|
|
||||||
`((line . ,line) (character . ,character)))
|
|
||||||
|
|
||||||
(define (lsp-range start-line start-char end-line end-char)
|
|
||||||
`((start . ,(pos start-line start-char))
|
|
||||||
(end . ,(pos end-line end-char))))
|
|
||||||
|
|
||||||
;;; ------------------------------------------------------------------
|
|
||||||
;;; Documents. One analysis at a time; the compiler's tables are global.
|
|
||||||
|
|
||||||
(define documents (make-hash-table equal?))
|
|
||||||
|
|
||||||
;;; #(uri path text version analysis dirty?)
|
|
||||||
(define (make-doc uri path text)
|
|
||||||
(vector uri path text 0 #f #t))
|
|
||||||
|
|
||||||
(define (doc-uri d) (vector-ref d 0))
|
|
||||||
(define (doc-path d) (vector-ref d 1))
|
|
||||||
(define (doc-text d) (vector-ref d 2))
|
|
||||||
(define (doc-analysis d) (vector-ref d 4))
|
|
||||||
(define (doc-dirty? d) (vector-ref d 5))
|
|
||||||
|
|
||||||
(define (doc-set-text! d text)
|
|
||||||
(vector-set! d 2 text)
|
|
||||||
(vector-set! d 3 (+ (vector-ref d 3) 1))
|
|
||||||
(vector-set! d 5 #t))
|
|
||||||
|
|
||||||
(define (doc-store-analysis! d analysis)
|
|
||||||
(vector-set! d 4 analysis)
|
|
||||||
(vector-set! d 5 #f))
|
|
||||||
|
|
||||||
(define (get-doc uri)
|
|
||||||
(hash-table-ref/default documents uri #f))
|
|
||||||
|
|
||||||
(define (percent-decode text)
|
|
||||||
(let ((n (string-length text)))
|
|
||||||
(let loop ((i 0) (chars (list)))
|
|
||||||
(cond
|
|
||||||
((>= i n) (list->string (reverse chars)))
|
|
||||||
((and (char=? (string-ref text i) #\%)
|
|
||||||
(< (+ i 2) n))
|
|
||||||
(let ((h (string->number (substring text (+ i 1) (+ i 3)) 16)))
|
|
||||||
(if h
|
|
||||||
(loop (+ i 3) (cons (integer->char h) chars))
|
|
||||||
(loop (+ i 1) (cons (string-ref text i) chars)))))
|
|
||||||
(else (loop (+ i 1) (cons (string-ref text i) chars)))))))
|
|
||||||
|
|
||||||
(define (uri->path uri)
|
|
||||||
(let ((rest (if (and (> (string-length uri) 7)
|
|
||||||
(string-ci=? (substring uri 0 7) "file://"))
|
|
||||||
(substring uri 7)
|
|
||||||
uri)))
|
|
||||||
(percent-decode
|
|
||||||
(if (and (> (string-length rest) 10)
|
|
||||||
(string-ci=? (substring rest 0 10) "localhost/"))
|
|
||||||
(substring rest 9)
|
|
||||||
rest))))
|
|
||||||
|
|
||||||
(define (path->uri path)
|
|
||||||
(string-append "file://" path))
|
|
||||||
|
|
||||||
(define (publish-diagnostics uri analysis)
|
|
||||||
(notify "textDocument/publishDiagnostics"
|
|
||||||
`((uri . ,uri)
|
|
||||||
(diagnostics
|
|
||||||
. ,(list->vector
|
|
||||||
(map (lambda (d)
|
|
||||||
`((range . ,(lsp-range (- (diag-line d) 1) 0
|
|
||||||
(diag-end d) 0))
|
|
||||||
(severity . ,(if (eq? (diag-severity d) 'warning) 2 1))
|
|
||||||
(source . "sexc")
|
|
||||||
(message . ,(diagnostic-text d))))
|
|
||||||
(analysis-diagnostics analysis)))))))
|
|
||||||
|
|
||||||
(define (diagnostic-text d)
|
|
||||||
(if (null? (diag-args d))
|
|
||||||
(diag-message d)
|
|
||||||
(string-append
|
|
||||||
(diag-message d) ": "
|
|
||||||
(string-intersperse
|
|
||||||
(map (lambda (arg)
|
|
||||||
(with-output-to-string (lambda () (write arg))))
|
|
||||||
(diag-args d))
|
|
||||||
" "))))
|
|
||||||
|
|
||||||
(define (analyze-doc! doc)
|
|
||||||
(let ((analysis (analyze-text (doc-text doc) (doc-path doc))))
|
|
||||||
(doc-store-analysis! doc analysis)
|
|
||||||
(publish-diagnostics (doc-uri doc) analysis)
|
|
||||||
analysis))
|
|
||||||
|
|
||||||
(define (ensure-doc! uri)
|
|
||||||
(let ((doc (get-doc uri)))
|
|
||||||
(and doc (if (doc-dirty? doc) (analyze-doc! doc) (doc-analysis doc)))))
|
|
||||||
|
|
||||||
(define (any-dirty?)
|
|
||||||
(let ((dirty? #f))
|
|
||||||
(hash-table-for-each documents
|
|
||||||
(lambda (uri doc)
|
|
||||||
(when (doc-dirty? doc) (set! dirty? #t))))
|
|
||||||
dirty?))
|
|
||||||
|
|
||||||
(define (analyze-dirty!)
|
|
||||||
(hash-table-for-each documents
|
|
||||||
(lambda (uri doc)
|
|
||||||
(when (doc-dirty? doc) (analyze-doc! doc)))))
|
|
||||||
|
|
||||||
;;; ------------------------------------------------------------------
|
|
||||||
;;; The identifier under the cursor. Columns are characters of the
|
|
||||||
;;; line string, which matches the editor for the ASCII Sex is written
|
|
||||||
;;; in. LSP's UTF-16 columns and a non-ASCII line can disagree.
|
|
||||||
|
|
||||||
(define (delimiter? c)
|
|
||||||
(or (char-whitespace? c)
|
|
||||||
(memv c '(#\( #\) #\[ #\] #\" #\; #\' #\` #\,))))
|
|
||||||
|
|
||||||
(define (nth-line text line)
|
|
||||||
(let loop ((i 0) (n 0) (start 0))
|
|
||||||
(cond
|
|
||||||
((>= i (string-length text))
|
|
||||||
(if (= n line) (substring text start i) ""))
|
|
||||||
((char=? (string-ref text i) #\newline)
|
|
||||||
(if (= n line)
|
|
||||||
(substring text start i)
|
|
||||||
(loop (+ i 1) (+ n 1) (+ i 1))))
|
|
||||||
(else (loop (+ i 1) n start)))))
|
|
||||||
|
|
||||||
;;; (start . end) character bounds of the identifier touching COLUMN,
|
|
||||||
;;; or #f. The cursor sits on a boundary, so a name ending at COLUMN
|
|
||||||
;;; counts.
|
|
||||||
(define (identifier-bounds line-text column)
|
|
||||||
(let* ((n (string-length line-text))
|
|
||||||
(i (max 0 (min column n))))
|
|
||||||
(let ((start (let loop ((j i))
|
|
||||||
(if (or (zero? j)
|
|
||||||
(delimiter? (string-ref line-text (- j 1))))
|
|
||||||
j
|
|
||||||
(loop (- j 1)))))
|
|
||||||
(end (let loop ((j i))
|
|
||||||
(if (or (>= j n) (delimiter? (string-ref line-text j)))
|
|
||||||
j
|
|
||||||
(loop (+ j 1))))))
|
|
||||||
(and (< start end) (cons start end)))))
|
|
||||||
|
|
||||||
(define (identifier-at text line column)
|
|
||||||
(let* ((line-text (nth-line text line))
|
|
||||||
(bounds (identifier-bounds line-text column)))
|
|
||||||
(and bounds
|
|
||||||
(list (substring line-text (car bounds) (cdr bounds))
|
|
||||||
(car bounds)
|
|
||||||
(cdr bounds)))))
|
|
||||||
|
|
||||||
(define (completion-kind kind)
|
|
||||||
(case kind
|
|
||||||
((fn) 3) ((var) 6) ((struct union sum) 22) ((enum) 13)
|
|
||||||
((typedef) 7) ((const) 21) (else 6)))
|
|
||||||
|
|
||||||
(define (symbol-kind kind)
|
|
||||||
(case kind
|
|
||||||
((fn) 12) ((var) 13) ((struct union sum) 23) ((enum) 10)
|
|
||||||
((typedef) 11) ((const) 14) (else 13)))
|
|
||||||
|
|
||||||
(define (sex-completion sym line start end)
|
|
||||||
(let ((name (symbol->string (sym-name sym)))
|
|
||||||
(doc (sym-doc sym)))
|
|
||||||
(let ((item `((label . ,name)
|
|
||||||
(kind . ,(completion-kind (sym-kind sym)))
|
|
||||||
(detail . ,(symbol-summary sym))
|
|
||||||
(sortText . ,(string-append "0" name))
|
|
||||||
(textEdit . ((range . ,(lsp-range line start line end))
|
|
||||||
(newText . ,name))))))
|
|
||||||
(if doc (cons `(documentation . ,doc) item) item))))
|
|
||||||
|
|
||||||
;;; ------------------------------------------------------------------
|
|
||||||
;;; clangd, optional. The probe is a C file of the unit's includes and
|
|
||||||
;;; one identifier. clangd never sees Sex.
|
|
||||||
|
|
||||||
(define clangd-pid #f)
|
|
||||||
(define clangd-in-fd #f)
|
|
||||||
(define clangd-out-fd #f)
|
|
||||||
(define clangd-failed? #f)
|
|
||||||
(define clangd-id 0)
|
|
||||||
(define probe-dir #f)
|
|
||||||
(define probe-path #f)
|
|
||||||
(define probe-uri #f)
|
|
||||||
(define probe-version 1)
|
|
||||||
(define probe-open? #f)
|
|
||||||
(define flags-key #f)
|
|
||||||
|
|
||||||
;;; file-select wants a descriptor and a timeout. Without a timeout it
|
|
||||||
;;; does not wake when the byte arrives later.
|
|
||||||
(define (fd-ready? fd timeout)
|
|
||||||
(call-with-values
|
|
||||||
(lambda () (file-select (list fd) '() (or timeout 30)))
|
|
||||||
(lambda (readable writable) (pair? readable))))
|
|
||||||
|
|
||||||
(define (port-ready? port timeout)
|
|
||||||
(fd-ready? (port->fileno port) timeout))
|
|
||||||
|
|
||||||
(define (string->bytes text)
|
|
||||||
(let* ((n (string-length text))
|
|
||||||
(out (make-bytevector n)))
|
|
||||||
(do ((i 0 (+ i 1)))
|
|
||||||
((= i n) out)
|
|
||||||
(bytevector-u8-set! out i (char->integer (string-ref text i))))))
|
|
||||||
|
|
||||||
(define (fd-write-all fd text)
|
|
||||||
(unless (string=? text "")
|
|
||||||
(let ((n (file-write fd (string->bytes text))))
|
|
||||||
(when (< n (string-length text))
|
|
||||||
(fd-write-all fd (substring text n))))))
|
|
||||||
|
|
||||||
(define (clangd-write obj)
|
|
||||||
(let* ((json (json->string obj))
|
|
||||||
(msg (string-append "Content-Length: "
|
|
||||||
(number->string (string-length json))
|
|
||||||
"\r\n\r\n"
|
|
||||||
json)))
|
|
||||||
(fd-write-all clangd-in-fd msg)))
|
|
||||||
|
|
||||||
(define (clangd-request method params)
|
|
||||||
(set! clangd-id (+ clangd-id 1))
|
|
||||||
(clangd-write `((jsonrpc . "2.0")
|
|
||||||
(id . ,clangd-id)
|
|
||||||
(method . ,method)
|
|
||||||
(params . ,params)))
|
|
||||||
(clangd-read-response clangd-id))
|
|
||||||
|
|
||||||
;;; An immediate completion against a just-opened probe is empty: clangd
|
|
||||||
;;; answers before it has read the headers. A diagnostic means the
|
|
||||||
;;; preamble is in.
|
|
||||||
;;; About a second and a half, which is what it takes clangd to read a
|
|
||||||
;;; header the size of stdio.h. Returning on the first diagnostic is
|
|
||||||
;;; too soon: one arrives before the preamble is usable.
|
|
||||||
(define (clangd-settle)
|
|
||||||
(let loop ((tries 10))
|
|
||||||
(when (positive? tries)
|
|
||||||
(when (fd-ready? clangd-out-fd 0.15)
|
|
||||||
(let ((msg (read-fd-message clangd-out-fd)))
|
|
||||||
(when (and msg (msg-method msg) (msg-id msg))
|
|
||||||
(clangd-reply (msg-id msg) 'null))))
|
|
||||||
(loop (- tries 1)))))
|
|
||||||
|
|
||||||
(define (clangd-notify method params)
|
|
||||||
(clangd-write `((jsonrpc . "2.0") (method . ,method) (params . ,params))))
|
|
||||||
|
|
||||||
(define (clangd-reply id result)
|
|
||||||
(clangd-write `((jsonrpc . "2.0") (id . ,id) (result . ,result))))
|
|
||||||
|
|
||||||
;;; clangd asks for configuration and registrations while it answers.
|
|
||||||
;;; Those get an empty result; its notifications are dropped.
|
|
||||||
;;; The child port cannot change its buffering, so clangd is read from
|
|
||||||
;;; the descriptor. file-read returns the buffer and how many bytes of
|
|
||||||
;;; it were filled.
|
|
||||||
;;; file-read returns one value, the list (buffer count). The buffer is
|
|
||||||
;;; allocated at the requested size; only count bytes of it were read.
|
|
||||||
(define (fd-chunk fd n)
|
|
||||||
(let ((got (file-read fd n)))
|
|
||||||
(let ((buf (car got))
|
|
||||||
(count (cadr got)))
|
|
||||||
(and (positive? count)
|
|
||||||
(if (bytevector? buf)
|
|
||||||
(let ((out (make-bytevector count)))
|
|
||||||
(do ((i 0 (+ i 1)))
|
|
||||||
((= i count) (utf8->string out))
|
|
||||||
(bytevector-u8-set! out i (bytevector-u8-ref buf i))))
|
|
||||||
(substring buf 0 count))))))
|
|
||||||
|
|
||||||
(define (read-fd-headers fd)
|
|
||||||
(let loop ((len #f) (line ""))
|
|
||||||
(let ((b (fd-chunk fd 1)))
|
|
||||||
(cond
|
|
||||||
((not b) #f)
|
|
||||||
((char=? (string-ref b 0) #\newline)
|
|
||||||
(let ((line (strip-cr line)))
|
|
||||||
(cond
|
|
||||||
((string=? line "") len)
|
|
||||||
((prefix-ci? "content-length:" line)
|
|
||||||
(loop (string->number (string-trim (substring line 15))) ""))
|
|
||||||
(else (loop len "")))))
|
|
||||||
(else (loop len (string-append line b)))))))
|
|
||||||
|
|
||||||
(define (read-fd-exact fd n)
|
|
||||||
(let loop ((acc ""))
|
|
||||||
(let ((need (- n (string-length acc))))
|
|
||||||
(if (zero? need)
|
|
||||||
acc
|
|
||||||
(let ((chunk (fd-chunk fd need)))
|
|
||||||
(if chunk (loop (string-append acc chunk)) #f))))))
|
|
||||||
|
|
||||||
(define (read-fd-message fd)
|
|
||||||
(let ((len (read-fd-headers fd)))
|
|
||||||
(and len
|
|
||||||
(let ((payload (read-fd-exact fd len)))
|
|
||||||
(and payload (call-with-input-string payload read-json))))))
|
|
||||||
|
|
||||||
(define (clangd-read-response want)
|
|
||||||
(let loop ()
|
|
||||||
(cond
|
|
||||||
((not (fd-ready? clangd-out-fd 15)) #f)
|
|
||||||
(else
|
|
||||||
(let ((msg (read-fd-message clangd-out-fd)))
|
|
||||||
(cond
|
|
||||||
((not msg) #f)
|
|
||||||
((and (msg-method msg) (msg-id msg))
|
|
||||||
(clangd-reply (msg-id msg) 'null)
|
|
||||||
(loop))
|
|
||||||
((and (assoc 'id msg) (equal? (cdr (assoc 'id msg)) want))
|
|
||||||
(if (assoc 'error msg) #f (jref msg 'result)))
|
|
||||||
(else (loop))))))))
|
|
||||||
|
|
||||||
(define (stop-clangd)
|
|
||||||
(when clangd-pid
|
|
||||||
(handle-exceptions exn #f (process-signal clangd-pid 15))
|
|
||||||
(set! clangd-pid #f)
|
|
||||||
(when clangd-in-fd (file-close clangd-in-fd))
|
|
||||||
(when clangd-out-fd (file-close clangd-out-fd))
|
|
||||||
(set! clangd-in-fd #f)
|
|
||||||
(set! clangd-out-fd #f)
|
|
||||||
(set! probe-open? #f)))
|
|
||||||
|
|
||||||
;;; process ports have no descriptor file-select can wait on, so clangd
|
|
||||||
;;; is forked onto a pipe we own.
|
|
||||||
(define (spawn-clangd)
|
|
||||||
(call-with-values
|
|
||||||
create-pipe
|
|
||||||
(lambda (from-child-r from-child-w)
|
|
||||||
(call-with-values
|
|
||||||
create-pipe
|
|
||||||
(lambda (to-child-r to-child-w)
|
|
||||||
(let ((pid (process-fork)))
|
|
||||||
;; The child is #f. The parent receives a process object.
|
|
||||||
(if (not pid)
|
|
||||||
(begin
|
|
||||||
(handle-exceptions exn (exit 127)
|
|
||||||
(duplicate-fileno to-child-r 0)
|
|
||||||
(duplicate-fileno from-child-w 1)
|
|
||||||
(let ((logf (file-open (make-pathname probe-dir "clangd.log")
|
|
||||||
(+ open/wronly open/creat open/trunc)
|
|
||||||
#o644)))
|
|
||||||
(duplicate-fileno logf 2))
|
|
||||||
(process-execute "clangd"
|
|
||||||
'("--background-index=0"
|
|
||||||
"--header-insertion=never"
|
|
||||||
"--log=error")))
|
|
||||||
(exit 127))
|
|
||||||
(begin
|
|
||||||
(file-close to-child-r)
|
|
||||||
(file-close from-child-w)
|
|
||||||
(set! clangd-pid pid)
|
|
||||||
(set! clangd-out-fd from-child-r)
|
|
||||||
(set! clangd-in-fd to-child-w)
|
|
||||||
#t))))))))
|
|
||||||
|
|
||||||
(define (write-flag-file flags)
|
|
||||||
(with-output-to-file (make-pathname probe-dir "compile_flags.txt")
|
|
||||||
(lambda ()
|
|
||||||
(for-each (lambda (flag) (display flag) (newline)) flags))))
|
|
||||||
|
|
||||||
(define (start-clangd)
|
|
||||||
(handle-exceptions exn
|
|
||||||
(begin
|
|
||||||
(display "sex-lsp: clangd did not start: " (current-error-port))
|
|
||||||
(display (or ((condition-property-accessor 'exn 'message "") exn) exn)
|
|
||||||
(current-error-port))
|
|
||||||
(display " " (current-error-port))
|
|
||||||
(write ((condition-property-accessor 'exn 'arguments '()) exn)
|
|
||||||
(current-error-port))
|
|
||||||
(newline (current-error-port))
|
|
||||||
(flush-output (current-error-port))
|
|
||||||
(set! clangd-failed? #t)
|
|
||||||
#f)
|
|
||||||
(spawn-clangd)
|
|
||||||
(let ((init (clangd-request "initialize"
|
|
||||||
`((processId . null)
|
|
||||||
(rootUri . ,(path->uri probe-dir))
|
|
||||||
(capabilities . ())))))
|
|
||||||
(if init
|
|
||||||
(begin
|
|
||||||
(clangd-notify "initialized" '())
|
|
||||||
#t)
|
|
||||||
(begin
|
|
||||||
(display "sex-lsp: clangd initialize failed\n" (current-error-port))
|
|
||||||
(flush-output (current-error-port))
|
|
||||||
(stop-clangd)
|
|
||||||
(set! clangd-failed? #t)
|
|
||||||
#f)))))
|
|
||||||
|
|
||||||
(define (ensure-clangd flags)
|
|
||||||
(and (eq? c-backend 'clangd)
|
|
||||||
(not clangd-failed?)
|
|
||||||
(begin
|
|
||||||
(unless probe-dir
|
|
||||||
(set! probe-dir (create-temporary-directory))
|
|
||||||
(set! probe-path (make-pathname probe-dir "probe.c"))
|
|
||||||
(set! probe-uri (path->uri probe-path)))
|
|
||||||
(let ((key (string-intersperse flags "\n")))
|
|
||||||
(unless (equal? key flags-key)
|
|
||||||
(set! flags-key key)
|
|
||||||
(write-flag-file flags)
|
|
||||||
(stop-clangd)))
|
|
||||||
(or clangd-pid (start-clangd)))))
|
|
||||||
|
|
||||||
(define (update-probe! text)
|
|
||||||
(set! probe-version (+ probe-version 1))
|
|
||||||
(if probe-open?
|
|
||||||
(clangd-notify "textDocument/didChange"
|
|
||||||
`((textDocument . ((uri . ,probe-uri)
|
|
||||||
(version . ,probe-version)))
|
|
||||||
(contentChanges . #(((text . ,text))))))
|
|
||||||
(begin
|
|
||||||
(clangd-notify "textDocument/didOpen"
|
|
||||||
`((textDocument . ((uri . ,probe-uri)
|
|
||||||
(languageId . "c")
|
|
||||||
(version . ,probe-version)
|
|
||||||
(text . ,text)))))
|
|
||||||
(set! probe-open? #t))))
|
|
||||||
|
|
||||||
(define (prefix-line text prefix)
|
|
||||||
(let ((target (sex-name->c (or prefix ""))))
|
|
||||||
(let loop ((lines (string-split text "\n")) (i 0))
|
|
||||||
(cond ((null? lines) 0)
|
|
||||||
((string-prefix? target (car lines)) i)
|
|
||||||
(else (loop (cdr lines) (+ i 1)))))))
|
|
||||||
|
|
||||||
(define (with-c-name includes flags name proc)
|
|
||||||
(and (ensure-clangd flags)
|
|
||||||
(let ((text (probe-text includes name)))
|
|
||||||
(with-output-to-file probe-path (lambda () (display text)))
|
|
||||||
(update-probe! text)
|
|
||||||
(clangd-settle)
|
|
||||||
(proc (prefix-line text name)))))
|
|
||||||
|
|
||||||
(define (completion-list result)
|
|
||||||
(cond
|
|
||||||
((vector? result) (vector->list result))
|
|
||||||
((and (pair? result) (jref result 'items))
|
|
||||||
(let ((items (jref result 'items)))
|
|
||||||
(if (vector? items) (vector->list items) (list))))
|
|
||||||
(else (list))))
|
|
||||||
|
|
||||||
(define (label-head label)
|
|
||||||
(let loop ((i 0))
|
|
||||||
(if (or (>= i (string-length label))
|
|
||||||
(not (or (char-alphabetic? (string-ref label i))
|
|
||||||
(char-numeric? (string-ref label i))
|
|
||||||
(char=? (string-ref label i) #\_))))
|
|
||||||
(substring label 0 i)
|
|
||||||
(loop (+ i 1)))))
|
|
||||||
|
|
||||||
(define (c-completion item line start end typed)
|
|
||||||
(let ((head (let ((filter (jref item 'filterText))
|
|
||||||
(label (jref item 'label)))
|
|
||||||
(cond
|
|
||||||
((and (string? filter) (not (string=? filter "")))
|
|
||||||
(label-head (string-trim filter)))
|
|
||||||
((string? label) (label-head (string-trim label)))
|
|
||||||
(else #f)))))
|
|
||||||
(and head (not (string=? head ""))
|
|
||||||
(let* ((sex (symbol->string (c-name->sex head)))
|
|
||||||
(filter (if (string-contains typed "_") head sex))
|
|
||||||
(detail (jref item 'detail)))
|
|
||||||
`((label . ,sex)
|
|
||||||
(kind . ,(or (jref item 'kind) 3))
|
|
||||||
(detail . ,(if (string? detail) detail head))
|
|
||||||
(sortText . ,(string-append "1" sex))
|
|
||||||
(filterText . ,filter)
|
|
||||||
(textEdit . ((range . ,(lsp-range line start line end))
|
|
||||||
(newText . ,sex))))))))
|
|
||||||
|
|
||||||
(define (clangd-completions includes flags typed line start end)
|
|
||||||
(or (with-c-name includes flags typed
|
|
||||||
(lambda (pline)
|
|
||||||
(let ((result (clangd-request "textDocument/completion"
|
|
||||||
`((textDocument . ((uri . ,probe-uri)))
|
|
||||||
(position . ,(pos pline
|
|
||||||
(string-length
|
|
||||||
(sex-name->c typed))))))))
|
|
||||||
(let ((items (filter-map (lambda (item)
|
|
||||||
(c-completion item line start end typed))
|
|
||||||
(completion-list result))))
|
|
||||||
(take-up-to 40
|
|
||||||
(append (filter (lambda (item)
|
|
||||||
(string-prefix? typed
|
|
||||||
(cdr (assoc 'label item))))
|
|
||||||
items)
|
|
||||||
(filter (lambda (item)
|
|
||||||
(and (string-prefix-ci? typed
|
|
||||||
(cdr (assoc 'label item)))
|
|
||||||
(not (string-prefix? typed
|
|
||||||
(cdr (assoc 'label item))))))
|
|
||||||
items)))))))
|
|
||||||
(list)))
|
|
||||||
|
|
||||||
(define (take-up-to n xs)
|
|
||||||
(if (or (null? xs) (zero? n))
|
|
||||||
(list)
|
|
||||||
(cons (car xs) (take-up-to (- n 1) (cdr xs)))))
|
|
||||||
|
|
||||||
(define (hover-body contents)
|
|
||||||
(cond
|
|
||||||
((string? contents) contents)
|
|
||||||
((vector? contents)
|
|
||||||
(string-intersperse (filter-map hover-body (vector->list contents)) "\n"))
|
|
||||||
((and (pair? contents) (jref contents 'value))
|
|
||||||
(let ((value (jref contents 'value)))
|
|
||||||
(and (string? value) value)))
|
|
||||||
(else #f)))
|
|
||||||
|
|
||||||
(define (clangd-hover-at includes flags name)
|
|
||||||
(with-c-name includes flags name
|
|
||||||
(lambda (pline)
|
|
||||||
(let ((result (clangd-request "textDocument/hover"
|
|
||||||
`((textDocument . ((uri . ,probe-uri)))
|
|
||||||
(position . ,(pos pline 1))))))
|
|
||||||
(and result
|
|
||||||
(let ((body (hover-body (jref result 'contents))))
|
|
||||||
(and body
|
|
||||||
(let ((sex (symbol->string (c-name->sex name))))
|
|
||||||
(if (string=? sex name) body
|
|
||||||
(string-append sex "\n\n" body))))))))))
|
|
||||||
|
|
||||||
(define (location-uri loc)
|
|
||||||
(or (jref loc 'uri) (jref loc 'targetUri)))
|
|
||||||
|
|
||||||
(define (location-range loc)
|
|
||||||
(or (jref loc 'range)
|
|
||||||
(jref loc 'targetSelectionRange)
|
|
||||||
(jref loc 'targetRange)))
|
|
||||||
|
|
||||||
(define (probe-location? loc)
|
|
||||||
(let ((uri (location-uri loc)))
|
|
||||||
(and (string? uri) (string-contains uri "probe.c"))))
|
|
||||||
|
|
||||||
(define (first-real-location result)
|
|
||||||
(let ((locs (cond
|
|
||||||
((vector? result) (vector->list result))
|
|
||||||
((pair? result) (list result))
|
|
||||||
(else (list)))))
|
|
||||||
(find (lambda (loc) (and (location-uri loc) (not (probe-location? loc))))
|
|
||||||
locs)))
|
|
||||||
|
|
||||||
(define (clangd-definition-at includes flags name)
|
|
||||||
(with-c-name includes flags name
|
|
||||||
(lambda (pline)
|
|
||||||
(let ((result (clangd-request "textDocument/definition"
|
|
||||||
`((textDocument . ((uri . ,probe-uri)))
|
|
||||||
(position . ,(pos pline 1))))))
|
|
||||||
(let ((loc (first-real-location result)))
|
|
||||||
(and loc
|
|
||||||
`((uri . ,(location-uri loc))
|
|
||||||
(range . ,(location-range loc)))))))))
|
|
||||||
|
|
||||||
;;; ------------------------------------------------------------------
|
|
||||||
;;; Requests.
|
|
||||||
|
|
||||||
(define (find-up path name)
|
|
||||||
(let loop ((dir (if (and path (directory-exists? path))
|
|
||||||
path
|
|
||||||
(and path (pathname-directory path)))))
|
|
||||||
(and dir (not (string=? dir ""))
|
|
||||||
(let ((candidate (make-pathname dir name)))
|
|
||||||
(if (file-exists? candidate)
|
|
||||||
candidate
|
|
||||||
(let ((parent (pathname-directory dir)))
|
|
||||||
(and parent (not (equal? parent dir)) (loop parent))))))))
|
|
||||||
|
|
||||||
(define (read-whole path)
|
|
||||||
(call-with-input-file path (lambda (port) (read-string #f port))))
|
|
||||||
|
|
||||||
(define (document-flags path)
|
|
||||||
(let ((file (find-up path "sex-cflags"))
|
|
||||||
(extra (if (string=? extra-cflags "") (list) (string-split extra-cflags))))
|
|
||||||
(append (if file (string-split (read-whole file)) (list)) extra)))
|
|
||||||
|
|
||||||
(define (params-uri params)
|
|
||||||
(or (jref params 'uri)
|
|
||||||
(let ((td (jref params 'textDocument)))
|
|
||||||
(and td (jref td 'uri)))))
|
|
||||||
|
|
||||||
(define (position-of params)
|
|
||||||
(let ((position (jref params 'position)))
|
|
||||||
(values (or (jref position 'line) 0)
|
|
||||||
(or (jref position 'character) 0))))
|
|
||||||
|
|
||||||
(define (on-initialize id)
|
|
||||||
(reply id
|
|
||||||
`((capabilities
|
|
||||||
. ((textDocumentSync . 1)
|
|
||||||
(hoverProvider . #t)
|
|
||||||
(definitionProvider . #t)
|
|
||||||
(completionProvider . ((triggerCharacters . #("-"))))
|
|
||||||
(documentSymbolProvider . #t)))
|
|
||||||
(serverInfo . ((name . "sex-lsp") (version . "0.1"))))))
|
|
||||||
|
|
||||||
(define (on-open params)
|
|
||||||
(let* ((td (jref params 'textDocument))
|
|
||||||
(uri (jref td 'uri))
|
|
||||||
(text (or (jref td 'text) "")))
|
|
||||||
(hash-table-set! documents uri (make-doc uri (uri->path uri) text))
|
|
||||||
(analyze-doc! (get-doc uri))))
|
|
||||||
|
|
||||||
(define (on-change params)
|
|
||||||
(let* ((uri (params-uri params))
|
|
||||||
(doc (get-doc uri))
|
|
||||||
(changes (jref params 'contentChanges)))
|
|
||||||
(when (and doc (vector? changes) (> (vector-length changes) 0))
|
|
||||||
(let ((text (jref (vector-ref changes (- (vector-length changes) 1)) 'text)))
|
|
||||||
(when (string? text)
|
|
||||||
;; Published on the next quiet 150ms, or sooner if a request
|
|
||||||
;; arrives. The wait is file-select's timeout; it does wake.
|
|
||||||
(doc-set-text! doc text))))))
|
|
||||||
|
|
||||||
(define (on-save params)
|
|
||||||
(let ((doc (get-doc (params-uri params))))
|
|
||||||
(when doc (analyze-doc! doc))))
|
|
||||||
|
|
||||||
(define (on-close params)
|
|
||||||
(let ((uri (params-uri params)))
|
|
||||||
(hash-table-delete! documents uri)
|
|
||||||
(notify "textDocument/publishDiagnostics"
|
|
||||||
`((uri . ,uri) (diagnostics . #())))))
|
|
||||||
|
|
||||||
(define (markdown text)
|
|
||||||
`((contents . ((kind . "markdown") (value . ,text)))))
|
|
||||||
|
|
||||||
(define (on-hover id params)
|
|
||||||
(let* ((uri (params-uri params))
|
|
||||||
(analysis (ensure-doc! uri))
|
|
||||||
(doc (get-doc uri)))
|
|
||||||
(if (not (and analysis doc))
|
|
||||||
(reply id 'null)
|
|
||||||
(call-with-values (lambda () (position-of params))
|
|
||||||
(lambda (line column)
|
|
||||||
(let ((ident (identifier-at (doc-text doc) line column)))
|
|
||||||
(if (not ident)
|
|
||||||
(reply id 'null)
|
|
||||||
(let ((sym (analysis-lookup analysis
|
|
||||||
(string->symbol (car ident))
|
|
||||||
(+ line 1))))
|
|
||||||
(cond
|
|
||||||
(sym (reply id (markdown (string-append "```sex\n"
|
|
||||||
(symbol-hover sym)
|
|
||||||
"\n```"))))
|
|
||||||
(else
|
|
||||||
(let ((text (clangd-hover-at (analysis-includes analysis)
|
|
||||||
(document-flags (doc-path doc))
|
|
||||||
(car ident))))
|
|
||||||
(reply id (if text (markdown text) 'null)))))))))))))
|
|
||||||
|
|
||||||
(define (on-definition id params)
|
|
||||||
(let* ((uri (params-uri params))
|
|
||||||
(analysis (ensure-doc! uri))
|
|
||||||
(doc (get-doc uri)))
|
|
||||||
(if (not (and analysis doc))
|
|
||||||
(reply id 'null)
|
|
||||||
(call-with-values (lambda () (position-of params))
|
|
||||||
(lambda (line column)
|
|
||||||
(let ((ident (identifier-at (doc-text doc) line column)))
|
|
||||||
(if (not ident)
|
|
||||||
(reply id 'null)
|
|
||||||
(let ((sym (analysis-lookup analysis
|
|
||||||
(string->symbol (car ident))
|
|
||||||
(+ line 1))))
|
|
||||||
(cond
|
|
||||||
(sym
|
|
||||||
(reply id `((uri . ,(path->uri (sym-file sym)))
|
|
||||||
(range . ,(lsp-range (- (sym-line sym) 1) 0
|
|
||||||
(sym-line sym) 0)))))
|
|
||||||
(else
|
|
||||||
(reply id (or (clangd-definition-at
|
|
||||||
(analysis-includes analysis)
|
|
||||||
(document-flags (doc-path doc))
|
|
||||||
(car ident))
|
|
||||||
'null))))))))))))
|
|
||||||
|
|
||||||
(define (on-completion id params)
|
|
||||||
(let* ((uri (params-uri params))
|
|
||||||
(analysis (ensure-doc! uri))
|
|
||||||
(doc (get-doc uri)))
|
|
||||||
(if (not (and analysis doc))
|
|
||||||
(reply id #())
|
|
||||||
(call-with-values (lambda () (position-of params))
|
|
||||||
(lambda (line column)
|
|
||||||
(let* ((line-text (nth-line (doc-text doc) line))
|
|
||||||
(column (max 0 (min column (string-length line-text))))
|
|
||||||
(bounds (identifier-bounds line-text column))
|
|
||||||
(start (if bounds (car bounds) column))
|
|
||||||
(end (if bounds (cdr bounds) column))
|
|
||||||
(typed (substring line-text start column))
|
|
||||||
(sex (filter-map
|
|
||||||
(lambda (sym)
|
|
||||||
(and (string-prefix? typed (symbol->string (sym-name sym)))
|
|
||||||
(sex-completion sym line start end)))
|
|
||||||
(analysis-completions analysis typed (+ line 1))))
|
|
||||||
(c (if (string=? typed "")
|
|
||||||
(list)
|
|
||||||
(clangd-completions (analysis-includes analysis)
|
|
||||||
(document-flags (doc-path doc))
|
|
||||||
typed line start end)))
|
|
||||||
(seen (map (lambda (item) (cdr (assoc 'label item))) sex)))
|
|
||||||
(reply id
|
|
||||||
(list->vector
|
|
||||||
(append sex
|
|
||||||
(filter (lambda (item)
|
|
||||||
(not (member (cdr (assoc 'label item)) seen)))
|
|
||||||
c))))))))))
|
|
||||||
|
|
||||||
(define (on-symbols id params)
|
|
||||||
(let ((analysis (ensure-doc! (params-uri params))))
|
|
||||||
(reply id
|
|
||||||
(if (not analysis)
|
|
||||||
#()
|
|
||||||
(list->vector
|
|
||||||
(map (lambda (sym)
|
|
||||||
`((name . ,(symbol->string (sym-name sym)))
|
|
||||||
(kind . ,(symbol-kind (sym-kind sym)))
|
|
||||||
(range . ,(lsp-range (- (sym-line sym) 1) 0
|
|
||||||
(sym-end sym) 0))
|
|
||||||
(selectionRange . ,(lsp-range (- (sym-line sym) 1) 0
|
|
||||||
(sym-line sym) 0))))
|
|
||||||
(analysis-document-symbols analysis)))))))
|
|
||||||
|
|
||||||
(define (on-expand id params)
|
|
||||||
(let* ((analysis (ensure-doc! (params-uri params)))
|
|
||||||
(start (jref params 'startLine))
|
|
||||||
(end (jref params 'endLine))
|
|
||||||
(text (and analysis
|
|
||||||
(analysis-expand analysis
|
|
||||||
(or start 1)
|
|
||||||
(if (or (not end) (eq? end 'null)) #f end)))))
|
|
||||||
(if text
|
|
||||||
(reply id `((language . "c") (text . ,text)))
|
|
||||||
(reply-error id -32602 "nothing to expand"))))
|
|
||||||
|
|
||||||
(define (dispatch msg)
|
|
||||||
(let ((method (msg-method msg))
|
|
||||||
(id (msg-id msg))
|
|
||||||
(params (jref msg 'params)))
|
|
||||||
(cond
|
|
||||||
((not method) #f)
|
|
||||||
((string=? method "initialize") (on-initialize id))
|
|
||||||
((string=? method "initialized") #f)
|
|
||||||
((string=? method "shutdown") (reply id 'null))
|
|
||||||
((string=? method "exit") (exit 0))
|
|
||||||
((string=? method "textDocument/didOpen") (on-open params))
|
|
||||||
((string=? method "textDocument/didChange") (on-change params))
|
|
||||||
((string=? method "textDocument/didSave") (on-save params))
|
|
||||||
((string=? method "textDocument/didClose") (on-close params))
|
|
||||||
((string=? method "textDocument/hover") (on-hover id params))
|
|
||||||
((string=? method "textDocument/definition") (on-definition id params))
|
|
||||||
((string=? method "textDocument/completion") (on-completion id params))
|
|
||||||
((string=? method "textDocument/documentSymbol") (on-symbols id params))
|
|
||||||
((string=? method "sex/expand") (on-expand id params))
|
|
||||||
(id (reply id 'null))
|
|
||||||
(else #f))))
|
|
||||||
|
|
||||||
(define (handle-message msg)
|
|
||||||
(handle-exceptions exn
|
|
||||||
(let ((id (msg-id msg)))
|
|
||||||
(when id
|
|
||||||
(reply-error id -32603
|
|
||||||
(or ((condition-property-accessor 'exn 'message #f) exn)
|
|
||||||
"internal error"))))
|
|
||||||
(dispatch msg)))
|
|
||||||
|
|
||||||
(define (serve)
|
|
||||||
(let loop ()
|
|
||||||
(cond
|
|
||||||
((port-ready? (current-input-port) (if (any-dirty?) 0.15 30))
|
|
||||||
(let ((msg (read-message (current-input-port))))
|
|
||||||
(when msg
|
|
||||||
(handle-message msg)
|
|
||||||
(loop))))
|
|
||||||
((any-dirty?)
|
|
||||||
(analyze-dirty!)
|
|
||||||
(loop))
|
|
||||||
(else (loop)))))
|
|
||||||
|
|
||||||
(parse-args (command-line-arguments))
|
|
||||||
;;; A full buffer waits for 1024 bytes or EOF before read-line returns,
|
|
||||||
;;; so a short LSP message on an open pipe would sit there unread.
|
|
||||||
(set-buffering-mode! (current-input-port) #:none)
|
|
||||||
(set-buffering-mode! (current-output-port) #:none)
|
|
||||||
(serve)
|
|
||||||
9
sex-macros.module.scm
Normal file
9
sex-macros.module.scm
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
(module sex-macros
|
||||||
|
(register-macro
|
||||||
|
cat
|
||||||
|
comment
|
||||||
|
get-macro
|
||||||
|
macro?
|
||||||
|
apply-macro
|
||||||
|
defmacro)
|
||||||
|
"sex-macros.scm")
|
||||||
@@ -2,22 +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!
|
|
||||||
reset-macros!)
|
|
||||||
|
|
||||||
(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))
|
||||||
@@ -31,15 +17,7 @@
|
|||||||
(define (comment . _)
|
(define (comment . _)
|
||||||
(void))
|
(void))
|
||||||
|
|
||||||
;;; Every name given a macro, so a later unit can take them all off.
|
|
||||||
(define +macro-names+ (list))
|
|
||||||
|
|
||||||
(define (note-macro-name! name)
|
|
||||||
(unless (memq name +macro-names+)
|
|
||||||
(set! +macro-names+ (cons name +macro-names+))))
|
|
||||||
|
|
||||||
(define (register-macro name arglist body)
|
(define (register-macro name arglist body)
|
||||||
(note-macro-name! name)
|
|
||||||
(put! name 'sex-macro
|
(put! name 'sex-macro
|
||||||
`(lambda ,arglist
|
`(lambda ,arglist
|
||||||
;; A macro body is ordinary Scheme, evaluated at compile
|
;; A macro body is ordinary Scheme, evaluated at compile
|
||||||
@@ -47,15 +25,9 @@
|
|||||||
;; the type database
|
;; the type database
|
||||||
(import scheme
|
(import scheme
|
||||||
(scheme base)
|
(scheme base)
|
||||||
;; a type is a list, so a macro reading one wants
|
|
||||||
;; `(third type)' rather than `(caddr type)'
|
|
||||||
(only srfi-1 first second third fourth fifth last)
|
|
||||||
(only sex-macros cat comment)
|
(only sex-macros cat comment)
|
||||||
(only types get-type-info get-tag-info get-fields
|
(only types get-type-info get-fields get-underlying-type
|
||||||
get-underlying-type type-match type-pattern-matches?
|
type-match map-fields))
|
||||||
map-fields
|
|
||||||
get-name-type get-return-type type-of
|
|
||||||
get-method))
|
|
||||||
,@body)))
|
,@body)))
|
||||||
|
|
||||||
(define (get-macro name)
|
(define (get-macro name)
|
||||||
@@ -66,52 +38,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
|
|
||||||
(begin (note-macro-name! name)
|
|
||||||
(put! name 'sex-macro definition))
|
|
||||||
(remprop! name 'sex-macro)))
|
|
||||||
|
|
||||||
(define (reset-macros!)
|
|
||||||
(for-each (lambda (name) (remprop! name 'sex-macro)) +macro-names+)
|
|
||||||
(set! +macro-names+ (list)))
|
|
||||||
|
|
||||||
(define (defmacro form)
|
(define (defmacro form)
|
||||||
(let ((arglist (car form))
|
(let ((arglist (car form))
|
||||||
|
|||||||
122
sex-mode.el
122
sex-mode.el
@@ -1,44 +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' edits. `sex-lsp' talks to the language server. Quelpa
|
|
||||||
;; installs both files. The hook is `eglot-ensure' or `lsp-deferred'.
|
|
||||||
;; Leave out :custom, :hook, and :config for the editing mode alone.
|
|
||||||
;;
|
|
||||||
;; (use-package sex-mode
|
|
||||||
;; :ensure nil
|
|
||||||
;; :quelpa
|
|
||||||
;; (sex-mode :fetcher git
|
|
||||||
;; :url "https://git.kotobank.ch/alex-eg/sex.git"
|
|
||||||
;; :files ("sex-mode.el" "sex-lsp.el")
|
|
||||||
;; :upgrade t)
|
|
||||||
;; :custom (sex-c-backend 'clangd)
|
|
||||||
;; :hook (sex-mode . lsp-deferred)
|
|
||||||
;; :config (require 'sex-lsp))
|
|
||||||
;;
|
|
||||||
;; 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 ()
|
||||||
@@ -47,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)))
|
||||||
@@ -57,72 +21,52 @@ 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"
|
||||||
"ops"
|
"fn"
|
||||||
"record"
|
"pub"
|
||||||
"struct"
|
"struct"
|
||||||
"sum"
|
"var"
|
||||||
"typedef"
|
"union")
|
||||||
"union"
|
'word)
|
||||||
"var")
|
"\\>"
|
||||||
'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"
|
|
||||||
"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))
|
||||||
@@ -137,10 +81,6 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
|
|||||||
(put 'fn 'lisp-indent-function 'defun)
|
(put 'fn 'lisp-indent-function 'defun)
|
||||||
(put 'pub 'lisp-indent-function 'defun)
|
(put 'pub 'lisp-indent-function 'defun)
|
||||||
(put 'defmacro 'lisp-indent-function 'defun)
|
(put 'defmacro 'lisp-indent-function 'defun)
|
||||||
(put 'record 'lisp-indent-function 'defun)
|
|
||||||
(put 'sum 'lisp-indent-function 'defun)
|
|
||||||
(put 'ops 'lisp-indent-function 'defun)
|
|
||||||
(put 'match 'lisp-indent-function 1)
|
|
||||||
(put 'struct 'lisp-indent-function 'defun)
|
(put 'struct 'lisp-indent-function 'defun)
|
||||||
(put 'union 'lisp-indent-function 'defun)
|
(put 'union 'lisp-indent-function 'defun)
|
||||||
(put 'var 'lisp-indent-function 0)
|
(put 'var 'lisp-indent-function 0)
|
||||||
@@ -161,8 +101,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
|
|
||||||
|
|||||||
5
sex-modules.module.scm
Normal file
5
sex-modules.module.scm
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
(module sex-modules
|
||||||
|
(get-modules-public-forms
|
||||||
|
load-persistent-module-paths
|
||||||
|
read-public-interface)
|
||||||
|
"sex-modules.scm")
|
||||||
534
sex-modules.scm
534
sex-modules.scm
@@ -1,101 +1,46 @@
|
|||||||
(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)
|
||||||
matchable
|
fmt
|
||||||
reader
|
reader
|
||||||
sex-macros
|
|
||||||
srfi-1
|
srfi-1
|
||||||
types
|
|
||||||
utils)
|
utils)
|
||||||
|
|
||||||
(export
|
|
||||||
get-modules-public-forms
|
|
||||||
mark-imported!
|
|
||||||
load-persistent-module-paths
|
|
||||||
check-public-interface
|
|
||||||
module-dependencies
|
|
||||||
read-public-interface
|
|
||||||
reset-modules!)
|
|
||||||
|
|
||||||
(define +persistent-module-paths+ (list))
|
(define +persistent-module-paths+ (list))
|
||||||
|
|
||||||
;;; for guarding against multiple imports (sort of mandatory #pragma
|
(define (get-modules-public-forms module-list)
|
||||||
;;; once)
|
;; Module list is a list of symbols
|
||||||
(define +imported-modules+ (list))
|
|
||||||
|
|
||||||
;;; The unit is one of its own imports from the start: two modules that
|
|
||||||
;;; import each other with pub hand it its own interface back otherwise,
|
|
||||||
;;; and its types are defined twice
|
|
||||||
(define (mark-imported! path)
|
|
||||||
(set! +imported-modules+ (cons (normalize-pathname path) +imported-modules+)))
|
|
||||||
|
|
||||||
;;; Drop what the previous unit imported, read, and exported. The search
|
|
||||||
;;; path stays: it is the process's, not the unit's.
|
|
||||||
(define (reset-modules!)
|
|
||||||
(set! +imported-modules+ (list))
|
|
||||||
(set! +modules-read+ (list))
|
|
||||||
(set! +modules-expanded+ (list))
|
|
||||||
(set! +module-exports+ (list)))
|
|
||||||
|
|
||||||
(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)))
|
(read-public-interface module-path)))
|
||||||
(if (member (normalize-pathname module-path) +imported-modules+)
|
|
||||||
(list)
|
|
||||||
(begin
|
|
||||||
(set! +imported-modules+ (cons (normalize-pathname module-path)
|
|
||||||
+imported-modules+))
|
|
||||||
(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
|
+persistent-module-paths+))
|
||||||
;;; 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)))
|
(define (locate-module name)
|
||||||
(cons directory
|
;; Module locations: relative to file being compiled, or in what was
|
||||||
(append +persistent-module-paths+ (standard-library-paths))))
|
;; in SEX_MODULE_PATH env var at the start of the process (see
|
||||||
|
|
||||||
;;; Where the modules shipped with the compiler live. Asked of the
|
|
||||||
;;; binary rather than baked in when it is built: in a work tree sexc
|
|
||||||
;;; sits beside lib/, and installed it sits in bindir with the modules
|
|
||||||
;;; under ../share/sex. Last in the search order, so a module of one's
|
|
||||||
;;; own wins over one of ours by the same name
|
|
||||||
(define (standard-library-paths)
|
|
||||||
(let ((binary (executable-pathname)))
|
|
||||||
(if binary
|
|
||||||
(let ((bin (pathname-directory binary)))
|
|
||||||
(list (make-pathname bin "lib")
|
|
||||||
(make-pathname (list (pathname-directory bin) "share") "sex")))
|
|
||||||
(list))))
|
|
||||||
|
|
||||||
(define (locate-module name directory)
|
|
||||||
;; Module locations: relative to DIRECTORY, or in what was 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
|
||||||
@@ -110,427 +55,36 @@
|
|||||||
(file-readable? module-path)
|
(file-readable? module-path)
|
||||||
module-path))))
|
module-path))))
|
||||||
|
|
||||||
;;; Every module file read for this unit, with its forms, last read
|
|
||||||
;;; first: what its output depends on, besides the unit itself. A module
|
|
||||||
;;; that an import chain and the interface check both reach is read once
|
|
||||||
(define +modules-read+ (list))
|
|
||||||
|
|
||||||
(define (module-dependencies) (reverse (map car +modules-read+)))
|
|
||||||
|
|
||||||
(define (read-module path)
|
|
||||||
(cond ((assoc path +modules-read+) => cdr)
|
|
||||||
(else (let ((forms (read-from-file path)))
|
|
||||||
(set! +modules-read+ (cons (cons path forms) +modules-read+))
|
|
||||||
forms))))
|
|
||||||
|
|
||||||
(define (read-public-interface module-path)
|
(define (read-public-interface module-path)
|
||||||
;; pub fns are reduced to prototypes, other pub forms are just pasted.
|
;; pub fns are reduced to prototypes, other pub forms are just pasted
|
||||||
;; Declaration order is kept: a module that declares a type and then a
|
(let ((raw-forms (read-from-file module-path)))
|
||||||
;; pub fn taking it has to paste them that way round, or the prototype
|
(fold
|
||||||
;; names a type C has not seen. The declarations of the types its
|
process-public-interface-form
|
||||||
;; importers see only behind a pointer go first.
|
(list)
|
||||||
(let ((forms (module-forms (read-module module-path))))
|
raw-forms)))
|
||||||
(append (check-public-interface forms)
|
|
||||||
(interface-forms 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)
|
|
||||||
(let ((helpers (helper-macros 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
|
|
||||||
;;;
|
|
||||||
;;; They are given the pub forms and nothing else, so a pub form that
|
|
||||||
;;; names a type not among them compiled here and failed there:
|
|
||||||
;;; (pub record shape ((cells (* cell)))) with `cell' private told the
|
|
||||||
;;; importer `unknown type name cell'. A record behind a pointer needs
|
|
||||||
;;; only declaring, and its declaration goes out with the pub forms.
|
|
||||||
;;; Held by value it needs its body; and a typedef or an enum has no
|
|
||||||
;;; declaration short of its definition. Those are errors here, where
|
|
||||||
;;; they were written. A name Sex has no declaration for is one only C
|
|
||||||
;;; knows, and is left to C.
|
|
||||||
|
|
||||||
;;; The bodyless declarations FORMS' importers need, in the order the
|
|
||||||
;;; pub forms ask for them. An error when a pub form needs more than a
|
|
||||||
;;; declaration of a type they cannot see.
|
|
||||||
(define (check-public-interface forms)
|
|
||||||
(let ((visible (visible-types forms))
|
|
||||||
(hidden (hidden-types forms)))
|
|
||||||
(reverse
|
|
||||||
(fold
|
|
||||||
(lambda (form acc)
|
|
||||||
(check-written-out form)
|
|
||||||
(fold (lambda (use acc) (check-type-use form use visible hidden acc))
|
|
||||||
acc
|
|
||||||
(append-map (lambda (type) (type-uses type #f))
|
|
||||||
(interface-types form))))
|
|
||||||
(list)
|
|
||||||
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?)
|
|
||||||
(define (check-type-use form use visible hidden acc)
|
|
||||||
(let* ((name (car use))
|
|
||||||
(seen (assq name visible))
|
|
||||||
(kept (assq name hidden))
|
|
||||||
(remedy (if (and kept (fourth kept)) "import its module with pub" "make it pub")))
|
|
||||||
(cond
|
|
||||||
((and seen (third seen)) acc) ; pub with its body
|
|
||||||
((and seen (cdr use)) acc) ; a pub handle, held by one
|
|
||||||
(seen
|
|
||||||
(sex-error form "only a handle of this type is pub, so hold it through a pointer"
|
|
||||||
name))
|
|
||||||
((not kept) acc)
|
|
||||||
((not (memq (second kept) '(record struct union sum)))
|
|
||||||
(sex-error form (string-append "importers cannot see this "
|
|
||||||
(symbol->string (second kept))
|
|
||||||
", and C declares one only by defining it; "
|
|
||||||
remedy)
|
|
||||||
name))
|
|
||||||
((not (cdr use))
|
|
||||||
(sex-error form (string-append "importers cannot see this type, held by value; "
|
|
||||||
remedy ", or hold it through a pointer")
|
|
||||||
name))
|
|
||||||
((any (lambda (f) (eq? name (cadr f))) acc) acc)
|
|
||||||
(else
|
|
||||||
(cons (copy-form-source!
|
|
||||||
form
|
|
||||||
(list (if (memq (second kept) '(record sum)) 'record (second kept))
|
|
||||||
name))
|
|
||||||
acc)))))
|
|
||||||
|
|
||||||
;;; The type forms a pub form shows its importers
|
|
||||||
;;;
|
|
||||||
;;; (pub fn f ((c (* cell)) (n int)) shape) -> ((* cell) int shape)
|
|
||||||
(define (interface-types form)
|
|
||||||
(match form
|
|
||||||
(('pub 'fn . _)
|
|
||||||
(match (strip-header-comments form 5)
|
|
||||||
(('pub 'fn name (args ...) ret . _) (signature-types args ret))
|
|
||||||
(_ (list))))
|
|
||||||
(('pub 'var . _)
|
|
||||||
(match (strip-header-comments form 4)
|
|
||||||
(('pub 'var name type . _) (list type))
|
|
||||||
(_ (list))))
|
|
||||||
(('pub 'typedef name target) (list target))
|
|
||||||
(('pub 'define name . body) body)
|
|
||||||
(('pub (or 'record 'struct 'union) name . rest)
|
|
||||||
(field-types (find list? (remove comment-form? rest))))
|
|
||||||
((or ('pub 'sum name (variants ...))
|
|
||||||
('pub 'sum name (? string?) (variants ...)))
|
|
||||||
(append-map (lambda (v)
|
|
||||||
(if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list)))
|
|
||||||
(remove comment-form? variants)))
|
|
||||||
(('ops type . methods)
|
|
||||||
(append-map interface-types (filter pub-form? methods)))
|
|
||||||
(_ (list))))
|
|
||||||
|
|
||||||
(define (field-types fields)
|
|
||||||
(if (list? fields) (map second (normalize-fields fields)) (list)))
|
|
||||||
|
|
||||||
(define (signature-types args ret)
|
|
||||||
(cons ret (arglist-types (remove comment-form? args))))
|
|
||||||
|
|
||||||
;;; Each name TYPE mentions, and whether it is behind a pointer:
|
|
||||||
;;;
|
|
||||||
;;; (* const cell) -> ((const . #t) (cell . #t))
|
|
||||||
;;; [cell 4] -> ((cell . #f))
|
|
||||||
;;; (fn ((cell)) int) -> ((cell . #f) (int . #f))
|
|
||||||
;;;
|
|
||||||
;;; A function type takes and returns by value whatever it is held
|
|
||||||
;;; through: C wants the body to define or call one of its functions.
|
|
||||||
(define (type-uses type behind?)
|
|
||||||
(cond
|
|
||||||
((symbol? type) (list (cons type behind?)))
|
|
||||||
((not (pair? type)) (list))
|
|
||||||
(else
|
|
||||||
(case (car type)
|
|
||||||
((*) (append-map (lambda (t) (type-uses t #t)) (cdr type)))
|
|
||||||
((¤) (let ((element (array-element-type type)))
|
|
||||||
(append (if element (type-uses element behind?) (list))
|
|
||||||
(if (array-bound? type) (bound-uses (array-bound type)) (list)))))
|
|
||||||
((fn)
|
|
||||||
(if (and (pair? (cdr type)) (list? (second type)))
|
|
||||||
(append-map (lambda (t) (type-uses t #f))
|
|
||||||
(signature-types (second type) (last type)))
|
|
||||||
(list)))
|
|
||||||
((struct union enum)
|
|
||||||
(if (and (pair? (cdr type)) (symbol? (second type)))
|
|
||||||
(list (cons (second type) behind?))
|
|
||||||
(list)))
|
|
||||||
(else (append-map (lambda (t) (type-uses t behind?)) type))))))
|
|
||||||
|
|
||||||
;;; [int (* 2 N)] needs N, as a value: there is no declaring it
|
|
||||||
(define (bound-uses bound)
|
|
||||||
(cond ((symbol? bound) (list (cons bound #f)))
|
|
||||||
((pair? bound) (append-map bound-uses (cdr bound)))
|
|
||||||
(else (list))))
|
|
||||||
|
|
||||||
;;; The types and constants FORMS declare, as (name kind body?):
|
|
||||||
;;;
|
|
||||||
;;; (pub record tally) -> (tally record #f)
|
|
||||||
;;; (sum colour ((none ()))) -> (colour sum #t)
|
|
||||||
;;; (define (sq x) (* x x)) -> (sq define #t)
|
|
||||||
(define (declared-types forms)
|
|
||||||
(filter-map
|
|
||||||
(lambda (form)
|
|
||||||
(and (pair? form)
|
|
||||||
(let* ((core (strip-pub form))
|
|
||||||
(name (and (pair? core) (pair? (cdr core))
|
|
||||||
(if (and (eq? (car core) 'define)
|
|
||||||
(pair? (second core)))
|
|
||||||
(car (second core))
|
|
||||||
(second core)))))
|
|
||||||
(and (memq (car core)
|
|
||||||
'(record struct union enum sum typedef define))
|
|
||||||
(symbol? name)
|
|
||||||
(list name
|
|
||||||
(car core)
|
|
||||||
(or (memq (car core) '(typedef define spec))
|
|
||||||
(any list? (remove comment-form? (cddr core)))))))))
|
|
||||||
forms))
|
|
||||||
|
|
||||||
(define (pub-form? form) (and (pair? form) (eq? (car form) 'pub)))
|
|
||||||
|
|
||||||
;;; Pub here or through a pub import. A type declared pub both bodyless
|
|
||||||
;;; and whole is whole: its whole entries come first, for `assq'
|
|
||||||
(define (visible-types forms)
|
|
||||||
(let ((all (append (declared-types (filter pub-form? forms))
|
|
||||||
(append-map exported-types (imported-modules forms #t)))))
|
|
||||||
(append (filter third all) (remove third all))))
|
|
||||||
|
|
||||||
;;; Declared here without pub, or brought by an import without it, as
|
|
||||||
;;; (name kind body? imported?)
|
|
||||||
(define (hidden-types forms)
|
|
||||||
(append (map (lambda (entry) (append entry (list #f)))
|
|
||||||
(declared-types (remove pub-form? forms)))
|
|
||||||
(map (lambda (entry) (append entry (list #t)))
|
|
||||||
(append-map exported-types (imported-modules forms #f)))))
|
|
||||||
|
|
||||||
;;; The files of the modules FORMS import, with pub or without
|
|
||||||
(define (imported-modules forms pub?)
|
|
||||||
(append-map (lambda (form)
|
|
||||||
(match form
|
|
||||||
(('pub 'import . modules) (if pub? (located form modules) (list)))
|
|
||||||
(('import . modules) (if pub? (list) (located form modules)))
|
|
||||||
(_ (list))))
|
|
||||||
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.
|
|
||||||
;;; Two modules may import each other, so each is read once
|
|
||||||
(define (exported-types path)
|
|
||||||
(let next ((paths (list path)) (seen (list)) (acc (list)))
|
|
||||||
(cond ((null? paths) (concatenate (reverse acc)))
|
|
||||||
((member (car paths) seen) (next (cdr paths) seen acc))
|
|
||||||
(else
|
|
||||||
(let ((exports (module-exports (car paths))))
|
|
||||||
(next (append (cdr paths) (cdr exports))
|
|
||||||
(cons (car paths) seen)
|
|
||||||
(cons (car exports) acc)))))))
|
|
||||||
|
|
||||||
;;; The types the module at PATH declares to its importers, and the
|
|
||||||
;;; modules its interface imports; worked out once, though the check of
|
|
||||||
;;; every module above it on a pub import chain walks there
|
|
||||||
(define +module-exports+ (list))
|
|
||||||
|
|
||||||
(define (module-exports path)
|
|
||||||
(cond ((assoc path +module-exports+) => cdr)
|
|
||||||
(else (let* ((forms (interface-forms (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)
|
|
||||||
;; (pub fn name args ret . body) -> prototype, keeping a docstring so
|
|
||||||
;; the importer can emit it above the declaration
|
|
||||||
(let ((form (strip-header-comments raw-form 5)))
|
|
||||||
(match form
|
|
||||||
(('pub 'fn name args ret)
|
|
||||||
form)
|
|
||||||
(('pub 'fn name args ret ('comment . _) . rest)
|
|
||||||
(public-fn-interface `(pub fn ,name ,args ,ret ,@rest)))
|
|
||||||
(('pub 'fn name args ret (? string? doc) . _)
|
|
||||||
`(pub fn ,name ,args ,ret ,doc))
|
|
||||||
(('pub 'fn name args ret . _)
|
|
||||||
`(pub fn ,name ,args ,ret)))))
|
|
||||||
|
|
||||||
;;; An ops block is not pub itself -- its methods are. The block leaves
|
|
||||||
;;; as a block, its pub methods reduced to prototypes, so the importer
|
|
||||||
;;; runs its own `process-ops' over it: prototypes alone would say that
|
|
||||||
;;; vec2ːlength exists without saying that vec2 has a `length', and
|
|
||||||
;;; (. v length) needs the second thing.
|
|
||||||
(define (ops-public-interface form)
|
|
||||||
(let ((type (and (pair? (cdr form)) (cadr form)))
|
|
||||||
(methods (filter (lambda (m)
|
|
||||||
(and (pair? m) (eq? (car m) 'pub)
|
|
||||||
(pair? (cdr m)) (eq? (cadr m) 'fn)))
|
|
||||||
(cddr form))))
|
|
||||||
(and (symbol? type)
|
|
||||||
(pair? methods)
|
|
||||||
(copy-form-source! form
|
|
||||||
`(ops ,type ,@(map public-fn-interface methods))))))
|
|
||||||
|
|
||||||
;;; 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
|
(case (car form)
|
||||||
;; Reduced to a prototype, still `pub', so the importer declares it
|
((pub)
|
||||||
;; with external linkage
|
(case (cadr form)
|
||||||
(('pub 'fn . _)
|
;; A function is reduced to a prototype and keeps its `pub', so
|
||||||
(cons (copy-form-source! form (public-fn-interface form)) acc))
|
;; the importing unit declares it with external linkage
|
||||||
(('pub 'var . _)
|
((fn)
|
||||||
(match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
|
(cons (copy-form-source! form (take form 5)) acc))
|
||||||
(cons (copy-form-source! form `(extern var ,name ,type)) acc)))
|
;; A variable becomes an `extern' declaration
|
||||||
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
|
((var)
|
||||||
(cons (copy-form-source! form (cdr form)) acc))
|
(cons (copy-form-source! form (cons 'extern (take (cdr form) 3))) acc))
|
||||||
(('ops . _)
|
((define defmacro import include struct typedef union)
|
||||||
(let ((exported (ops-public-interface form)))
|
(cons (copy-form-source! form (cdr form)) acc))
|
||||||
(if exported (cons exported acc) acc)))
|
(else (sex-error form "pub must be followed by a definition" form))))
|
||||||
(('pub . _)
|
(else acc)))
|
||||||
(sex-error form "pub must be followed by a definition" form))
|
|
||||||
(_ acc)))
|
|
||||||
|
|
||||||
(define (load-persistent-module-paths)
|
(define (load-persistent-module-paths)
|
||||||
(let ((sex-module-path-env-var
|
(let ((sex-module-path-env-var
|
||||||
(get-env-var "SEX_MODULE_PATH")))
|
(get-env-var "SEX_MODULE_PATH")))
|
||||||
(when sex-module-path-env-var
|
(when sex-module-path-env-var
|
||||||
(set! +persistent-module-paths+
|
(set! +persistent-module-paths+
|
||||||
(map to-absolute-pathname
|
(map (lambda (p)
|
||||||
|
(make-absolute-pathname p #f #f))
|
||||||
(string-split sex-module-path-env-var ":"))))))
|
(string-split sex-module-path-env-var ":"))))))
|
||||||
|
|||||||
426
sex-query.scm
426
sex-query.scm
@@ -1,426 +0,0 @@
|
|||||||
;;; Queries over one Sex unit: diagnostics, the symbol table, and a
|
|
||||||
;;; slice of the C that unit compiles to. `sexc --check` and the
|
|
||||||
;;; language server both call this. It is not a second compiler.
|
|
||||||
;;;
|
|
||||||
;;; Specs, realizations, and closures are not in the language, and
|
|
||||||
;;; nothing here records them.
|
|
||||||
|
|
||||||
(import
|
|
||||||
scheme
|
|
||||||
(chicken base)
|
|
||||||
(chicken condition)
|
|
||||||
(chicken io)
|
|
||||||
(chicken irregex)
|
|
||||||
(chicken module)
|
|
||||||
(chicken port)
|
|
||||||
(chicken pretty-print)
|
|
||||||
(chicken string)
|
|
||||||
fmt-c-writer
|
|
||||||
matchable
|
|
||||||
reader
|
|
||||||
semen
|
|
||||||
sex-macros
|
|
||||||
sex-modules
|
|
||||||
srfi-1
|
|
||||||
srfi-13
|
|
||||||
types
|
|
||||||
utils)
|
|
||||||
|
|
||||||
(export
|
|
||||||
compiler-prelude
|
|
||||||
analyze-text
|
|
||||||
analyze-file
|
|
||||||
analyze-port
|
|
||||||
analysis-read?
|
|
||||||
analysis-path
|
|
||||||
analysis-diagnostics
|
|
||||||
analysis-symbols
|
|
||||||
analysis-includes
|
|
||||||
analysis-forms
|
|
||||||
analysis-lookup
|
|
||||||
analysis-completions
|
|
||||||
analysis-document-symbols
|
|
||||||
analysis-expand
|
|
||||||
symbol-summary
|
|
||||||
symbol-hover
|
|
||||||
sym-kind
|
|
||||||
sym-name
|
|
||||||
sym-file
|
|
||||||
sym-line
|
|
||||||
sym-end
|
|
||||||
sym-signature
|
|
||||||
sym-doc
|
|
||||||
sym-scope-start
|
|
||||||
sym-scope-end
|
|
||||||
diag-severity
|
|
||||||
diag-file
|
|
||||||
diag-line
|
|
||||||
diag-end
|
|
||||||
diag-message
|
|
||||||
diag-args
|
|
||||||
write-diagnostics
|
|
||||||
write-symbols
|
|
||||||
parse-expand-lines
|
|
||||||
sex-name->c
|
|
||||||
c-name->sex
|
|
||||||
probe-text)
|
|
||||||
|
|
||||||
;;; The same prelude `sexc` compiles in front of every unit. Kept here
|
|
||||||
;;; so a query and a build cannot drift apart.
|
|
||||||
(define (compiler-prelude)
|
|
||||||
'((include inttypes.h)
|
|
||||||
(include stdbool.h)
|
|
||||||
(include stddef.h)
|
|
||||||
(typedef u8 uint8-t)
|
|
||||||
(typedef i8 int8-t)
|
|
||||||
(typedef u16 uint16-t)
|
|
||||||
(typedef i16 int16-t)
|
|
||||||
(typedef u32 uint32-t)
|
|
||||||
(typedef i32 int32-t)
|
|
||||||
(typedef u64 uint64-t)
|
|
||||||
(typedef i64 int64-t)))
|
|
||||||
|
|
||||||
(define (reset-compiler-state!)
|
|
||||||
(reset-form-sources!)
|
|
||||||
(reset-name-tables!)
|
|
||||||
(reset-macros!)
|
|
||||||
(reset-modules!))
|
|
||||||
|
|
||||||
;;; read? is #f only when the reader itself failed. Semantic errors are
|
|
||||||
;;; diagnostics and the unit is otherwise analyzed.
|
|
||||||
;;;
|
|
||||||
;;; symbols: (kind name file line end signature doc scope-start scope-end)
|
|
||||||
;;; scope-start is #f for a name visible through the whole unit.
|
|
||||||
;;; diagnostics: (severity file line end message args)
|
|
||||||
(define (make-analysis read? path diagnostics symbols includes forms)
|
|
||||||
(vector read? path diagnostics symbols includes forms))
|
|
||||||
|
|
||||||
(define (analysis-read? a) (vector-ref a 0))
|
|
||||||
(define (analysis-path a) (vector-ref a 1))
|
|
||||||
(define (analysis-diagnostics a) (vector-ref a 2))
|
|
||||||
(define (analysis-symbols a) (vector-ref a 3))
|
|
||||||
(define (analysis-includes a) (vector-ref a 4))
|
|
||||||
(define (analysis-forms a) (vector-ref a 5))
|
|
||||||
|
|
||||||
(define (sym-kind s) (list-ref s 0))
|
|
||||||
(define (sym-name s) (list-ref s 1))
|
|
||||||
(define (sym-file s) (list-ref s 2))
|
|
||||||
(define (sym-line s) (list-ref s 3))
|
|
||||||
(define (sym-end s) (list-ref s 4))
|
|
||||||
(define (sym-signature s) (list-ref s 5))
|
|
||||||
(define (sym-doc s) (list-ref s 6))
|
|
||||||
(define (sym-scope-start s) (list-ref s 7))
|
|
||||||
(define (sym-scope-end s) (list-ref s 8))
|
|
||||||
|
|
||||||
(define (diag-severity d) (list-ref d 0))
|
|
||||||
(define (diag-file d) (list-ref d 1))
|
|
||||||
(define (diag-line d) (list-ref d 2))
|
|
||||||
(define (diag-end d) (list-ref d 3))
|
|
||||||
(define (diag-message d) (list-ref d 4))
|
|
||||||
(define (diag-args d) (list-ref d 5))
|
|
||||||
|
|
||||||
;;; "file:line: text" is how the reader reports a bad buffer. Pull the
|
|
||||||
;;; line back out so the diagnostic points at it.
|
|
||||||
(define location-prefix (irregex "^(.+):([0-9]+): (.*)$"))
|
|
||||||
|
|
||||||
(define (note-read-error! exn)
|
|
||||||
(let ((message ((condition-property-accessor 'exn 'message #f) exn))
|
|
||||||
(args ((condition-property-accessor 'exn 'arguments (list)) exn)))
|
|
||||||
(let ((m (and message (irregex-match location-prefix message))))
|
|
||||||
(if m
|
|
||||||
(let ((line (string->number (irregex-match-substring m 2))))
|
|
||||||
(record-diagnostic-at! 'error
|
|
||||||
(irregex-match-substring m 1)
|
|
||||||
line line
|
|
||||||
(irregex-match-substring m 3)
|
|
||||||
args))
|
|
||||||
(record-exception! #f exn)))))
|
|
||||||
|
|
||||||
(define (include-names form)
|
|
||||||
(match form
|
|
||||||
(('include . names) names)
|
|
||||||
(('pub 'include . names) names)
|
|
||||||
(_ (list))))
|
|
||||||
|
|
||||||
(define (gather-includes raw processed)
|
|
||||||
(delete-duplicates
|
|
||||||
(append (if (pair? raw) (append-map include-names raw) (list))
|
|
||||||
(if (pair? processed) (append-map include-names processed) (list)))
|
|
||||||
equal?))
|
|
||||||
|
|
||||||
(define (mark-unit! path)
|
|
||||||
(when (and (string? path)
|
|
||||||
(not (equal? path "stdin"))
|
|
||||||
(not (equal? path "<unknown>")))
|
|
||||||
(mark-imported! (to-absolute-pathname path))))
|
|
||||||
|
|
||||||
(define (process-unit raw path)
|
|
||||||
(mark-unit! path)
|
|
||||||
(handle-exceptions exn
|
|
||||||
(record-exception! #f exn)
|
|
||||||
(check-public-interface raw))
|
|
||||||
(handle-exceptions exn
|
|
||||||
(begin (record-exception! #f exn) #f)
|
|
||||||
(semen-process (append (compiler-prelude) raw))))
|
|
||||||
|
|
||||||
;;; Newest-first, and a prototype recorded before its body loses to the
|
|
||||||
;;; body, which is where the docstring is.
|
|
||||||
(define (unique-symbols syms)
|
|
||||||
(let loop ((syms syms) (seen (list)) (acc (list)))
|
|
||||||
(if (null? syms)
|
|
||||||
(reverse acc)
|
|
||||||
(let ((key (list (sym-kind (car syms)) (sym-name (car syms))
|
|
||||||
(sym-file (car syms)) (sym-line (car syms)))))
|
|
||||||
(if (member key seen)
|
|
||||||
(loop (cdr syms) seen acc)
|
|
||||||
(loop (cdr syms) (cons key seen) (cons (car syms) acc)))))))
|
|
||||||
|
|
||||||
(define (finish read? path raw processed diags syms)
|
|
||||||
(make-analysis read? path
|
|
||||||
(reverse (note-box-items diags))
|
|
||||||
(unique-symbols (note-box-items syms))
|
|
||||||
(gather-includes raw processed)
|
|
||||||
processed))
|
|
||||||
|
|
||||||
(define (analyze-text text path)
|
|
||||||
(reset-compiler-state!)
|
|
||||||
(let ((diags (make-note-box))
|
|
||||||
(syms (make-note-box)))
|
|
||||||
(parameterize ((sex-diagnostics diags)
|
|
||||||
(sex-symbols syms)
|
|
||||||
(current-source-file path))
|
|
||||||
(let ((raw (handle-exceptions exn
|
|
||||||
(begin (note-read-error! exn) #f)
|
|
||||||
(read-sex-string text path))))
|
|
||||||
(if raw
|
|
||||||
(finish #t path raw (process-unit raw path) diags syms)
|
|
||||||
(finish #f path #f #f diags syms))))))
|
|
||||||
|
|
||||||
(define (analyze-port port path)
|
|
||||||
(analyze-text (read-string #f port) path))
|
|
||||||
|
|
||||||
(define (analyze-file path)
|
|
||||||
(let ((abs (to-absolute-pathname path)))
|
|
||||||
(reset-compiler-state!)
|
|
||||||
(let ((diags (make-note-box))
|
|
||||||
(syms (make-note-box)))
|
|
||||||
(parameterize ((sex-diagnostics diags)
|
|
||||||
(sex-symbols syms)
|
|
||||||
(current-source-file abs))
|
|
||||||
(let ((raw (handle-exceptions exn
|
|
||||||
(begin (note-read-error! exn) #f)
|
|
||||||
(read-from-file path))))
|
|
||||||
(if raw
|
|
||||||
(finish #t abs raw (process-unit raw abs) diags syms)
|
|
||||||
(finish #f abs #f #f diags syms)))))))
|
|
||||||
|
|
||||||
(define (kind-rank kind)
|
|
||||||
(case kind
|
|
||||||
((fn) 0) ((sum) 1) ((struct) 2) ((union) 3) ((enum) 4)
|
|
||||||
((typedef) 5) ((const) 6) ((var) 7)
|
|
||||||
(else 9)))
|
|
||||||
|
|
||||||
(define (symbol-width sym)
|
|
||||||
(if (sym-scope-start sym)
|
|
||||||
(- (sym-scope-end sym) (sym-scope-start sym))
|
|
||||||
1000000000))
|
|
||||||
|
|
||||||
;;; A tighter block beats a wider one. At the same span the later
|
|
||||||
;;; declaration wins, and a struct beats the typedef of the same name.
|
|
||||||
(define (symbol-better? a b)
|
|
||||||
(let ((wa (symbol-width a))
|
|
||||||
(wb (symbol-width b)))
|
|
||||||
(cond ((< wa wb) #t)
|
|
||||||
((> wa wb) #f)
|
|
||||||
((> (sym-line a) (sym-line b)) #t)
|
|
||||||
((< (sym-line a) (sym-line b)) #f)
|
|
||||||
(else (< (kind-rank (sym-kind a)) (kind-rank (sym-kind b)))))))
|
|
||||||
|
|
||||||
(define (symbol-visible? sym line)
|
|
||||||
(let ((start (sym-scope-start sym)))
|
|
||||||
(or (not start)
|
|
||||||
(and (>= line (sym-line sym))
|
|
||||||
(<= line (sym-scope-end sym))))))
|
|
||||||
|
|
||||||
(define (analysis-lookup analysis name line)
|
|
||||||
(let loop ((syms (analysis-symbols analysis)) (best #f))
|
|
||||||
(if (null? syms)
|
|
||||||
best
|
|
||||||
(let ((s (car syms)))
|
|
||||||
(loop (cdr syms)
|
|
||||||
(if (and (eq? (sym-name s) name)
|
|
||||||
(symbol-visible? s line)
|
|
||||||
(or (not best) (symbol-better? s best)))
|
|
||||||
s
|
|
||||||
best))))))
|
|
||||||
|
|
||||||
(define (analysis-completions analysis prefix line)
|
|
||||||
(let loop ((syms (analysis-symbols analysis)) (seen (list)) (acc (list)))
|
|
||||||
(if (null? syms)
|
|
||||||
(reverse acc)
|
|
||||||
(let ((name (sym-name (car syms))))
|
|
||||||
(if (or (memq name seen)
|
|
||||||
(not (string-prefix? prefix (symbol->string name))))
|
|
||||||
(loop (cdr syms) (if (memq name seen) seen (cons name seen)) acc)
|
|
||||||
(let ((hit (analysis-lookup analysis name line)))
|
|
||||||
(loop (cdr syms) (cons name seen)
|
|
||||||
(if hit (cons hit acc) acc))))))))
|
|
||||||
|
|
||||||
(define (analysis-document-symbols analysis)
|
|
||||||
(filter (lambda (s) (equal? (sym-file s) (analysis-path analysis)))
|
|
||||||
(analysis-symbols analysis)))
|
|
||||||
|
|
||||||
(define (sexp->string form)
|
|
||||||
(with-output-to-string (lambda () (write form))))
|
|
||||||
|
|
||||||
(define (symbol-summary sym)
|
|
||||||
(let ((sig (sym-signature sym)))
|
|
||||||
(sexp->string
|
|
||||||
(case (sym-kind sym)
|
|
||||||
((fn) sig)
|
|
||||||
((var const) `(var ,(sym-name sym) ,sig))
|
|
||||||
((typedef) `(typedef ,(sym-name sym) ,sig))
|
|
||||||
(else `(,(sym-kind sym) ,(sym-name sym)))))))
|
|
||||||
|
|
||||||
(define (symbol-hover sym)
|
|
||||||
(let ((doc (sym-doc sym)))
|
|
||||||
(if doc
|
|
||||||
(string-append (symbol-summary sym) "\n" doc)
|
|
||||||
(symbol-summary sym))))
|
|
||||||
|
|
||||||
;;; #line N "file" starts a chunk. A chunk is kept when N lies in the
|
|
||||||
;;; inclusive range. Text before the first directive -- the prelude --
|
|
||||||
;;; belongs to no Sex line and is left out of a slice.
|
|
||||||
(define line-directive (irregex "^#line ([0-9]+) "))
|
|
||||||
|
|
||||||
(define (split-lines text)
|
|
||||||
(let loop ((i 0) (start 0) (acc (list)))
|
|
||||||
(cond ((>= i (string-length text))
|
|
||||||
(reverse (cons (substring text start i) acc)))
|
|
||||||
((char=? (string-ref text i) #\newline)
|
|
||||||
(loop (+ i 1) (+ i 1) (cons (substring text start i) acc)))
|
|
||||||
((char=? (string-ref text i) #\return)
|
|
||||||
(let ((next (if (and (< (+ i 1) (string-length text))
|
|
||||||
(char=? (string-ref text (+ i 1)) #\newline))
|
|
||||||
(+ i 2)
|
|
||||||
(+ i 1))))
|
|
||||||
(loop next next (cons (substring text start i) acc))))
|
|
||||||
(else (loop (+ i 1) start acc)))))
|
|
||||||
|
|
||||||
(define (keep-chunk? sex-line start end)
|
|
||||||
(and sex-line start end (<= start sex-line end)))
|
|
||||||
|
|
||||||
(define (slice-c-text text start end)
|
|
||||||
(let loop ((lines (split-lines text))
|
|
||||||
(sex-line #f)
|
|
||||||
(chunk (list))
|
|
||||||
(acc (list)))
|
|
||||||
(define (flush line chunk acc)
|
|
||||||
(if (keep-chunk? line start end) (append chunk acc) acc))
|
|
||||||
(if (null? lines)
|
|
||||||
(let ((kept (reverse (flush sex-line chunk acc))))
|
|
||||||
(if (null? kept) "" (string-append (string-intersperse kept "\n") "\n")))
|
|
||||||
(let ((m (irregex-search line-directive (car lines))))
|
|
||||||
(if m
|
|
||||||
(loop (cdr lines)
|
|
||||||
(string->number (irregex-match-substring m 1))
|
|
||||||
(list (car lines))
|
|
||||||
(flush sex-line chunk acc))
|
|
||||||
(loop (cdr lines) sex-line (cons (car lines) chunk) acc))))))
|
|
||||||
|
|
||||||
;;; END #f is the whole buffer, directives and all. Otherwise the C
|
|
||||||
;;; whose Sex line falls in START..END.
|
|
||||||
(define (analysis-expand analysis start end)
|
|
||||||
(let ((forms (analysis-forms analysis)))
|
|
||||||
(and forms
|
|
||||||
(parameterize ((sex-line-directives 'statement))
|
|
||||||
(let ((text (with-output-to-string (lambda () (emit-c forms)))))
|
|
||||||
(if end (slice-c-text text start end) text))))))
|
|
||||||
|
|
||||||
(define (diagnostic->sexp d)
|
|
||||||
(append (list (diag-severity d) (diag-file d) (diag-line d) (diag-end d)
|
|
||||||
(diag-message d))
|
|
||||||
(diag-args d)))
|
|
||||||
|
|
||||||
(define (symbol->sexp s)
|
|
||||||
(list (sym-kind s) (sym-name s) (sym-file s) (sym-line s) (sym-end s)
|
|
||||||
(sym-signature s) (sym-doc s) (sym-scope-start s) (sym-scope-end s)))
|
|
||||||
|
|
||||||
(define (write-diagnostics analysis port)
|
|
||||||
(pretty-print `(diagnostics ,@(map diagnostic->sexp (analysis-diagnostics analysis)))
|
|
||||||
port))
|
|
||||||
|
|
||||||
(define (write-symbols analysis port)
|
|
||||||
(pretty-print `(symbols ,@(map symbol->sexp (analysis-symbols analysis)))
|
|
||||||
port))
|
|
||||||
|
|
||||||
;;; "START:END", or START with the end left off, which is the whole
|
|
||||||
;;; buffer. ":" is the whole buffer too.
|
|
||||||
(define (parse-expand-lines spec)
|
|
||||||
(let ((colon (substring-index ":" spec)))
|
|
||||||
(cond
|
|
||||||
((not colon)
|
|
||||||
(let ((n (string->number spec)))
|
|
||||||
(or (and n (cons n #f))
|
|
||||||
(error "--expand-lines wants START or START:END, got" spec))))
|
|
||||||
(else
|
|
||||||
(let ((start-text (substring spec 0 colon))
|
|
||||||
(end-text (substring spec (+ colon 1))))
|
|
||||||
(cond
|
|
||||||
((and (string=? start-text "") (string=? end-text ""))
|
|
||||||
(cons #f #f))
|
|
||||||
((string=? end-text "")
|
|
||||||
(let ((n (string->number start-text)))
|
|
||||||
(if n
|
|
||||||
(cons n #f)
|
|
||||||
(error "--expand-lines wants START or START:END, got" spec))))
|
|
||||||
(else
|
|
||||||
(let ((start (string->number start-text))
|
|
||||||
(end (string->number end-text)))
|
|
||||||
(if (and start end)
|
|
||||||
(cons start end)
|
|
||||||
(error "--expand-lines wants START or START:END, got" spec))))))))))
|
|
||||||
|
|
||||||
;;; Hyphens are underscores in C, except the arrow, which is one token.
|
|
||||||
(define (sex-name->c name)
|
|
||||||
(let ((s (if (symbol? name) (symbol->string name) name)))
|
|
||||||
(let loop ((i 0) (chars (list)))
|
|
||||||
(if (>= i (string-length s))
|
|
||||||
(list->string (reverse chars))
|
|
||||||
(let ((c (string-ref s i)))
|
|
||||||
(if (and (char=? c #\-)
|
|
||||||
(not (and (< (+ i 1) (string-length s))
|
|
||||||
(char=? (string-ref s (+ i 1)) #\>))))
|
|
||||||
(loop (+ i 1) (cons #\_ chars))
|
|
||||||
(loop (+ i 1) (cons c chars))))))))
|
|
||||||
|
|
||||||
(define (c-name->sex name)
|
|
||||||
(string->symbol
|
|
||||||
(string-translate (if (symbol? name) (symbol->string name) name) "_" "-")))
|
|
||||||
|
|
||||||
(define prelude-headers '(stddef.h stdbool.h inttypes.h))
|
|
||||||
|
|
||||||
(define (include-spelling name)
|
|
||||||
(if (string? name)
|
|
||||||
(with-output-to-string (lambda () (write name)))
|
|
||||||
(string-append "<" (symbol->string name) ">")))
|
|
||||||
|
|
||||||
;;; A C translation unit of just the headers, then PREFIX in C spelling,
|
|
||||||
;;; which is where clangd is asked to complete or hover.
|
|
||||||
(define (probe-text includes prefix)
|
|
||||||
(with-output-to-string
|
|
||||||
(lambda ()
|
|
||||||
(for-each (lambda (name)
|
|
||||||
(display "#include ")
|
|
||||||
(display (include-spelling name))
|
|
||||||
(newline))
|
|
||||||
(delete-duplicates (append prelude-headers includes) equal?))
|
|
||||||
;; A bare name is not a hoverable token. A call is, and completion
|
|
||||||
;; still lands on the name, which is written before the argument.
|
|
||||||
(display "void sex_probe (void) {")
|
|
||||||
(newline)
|
|
||||||
(display (sex-name->c (or prefix "")))
|
|
||||||
(display "(0);")
|
|
||||||
(newline)
|
|
||||||
(display "}")
|
|
||||||
(newline))))
|
|
||||||
1
sexc.module.scm
Normal file
1
sexc.module.scm
Normal file
@@ -0,0 +1 @@
|
|||||||
|
(module sexc (main) "sexc.scm")
|
||||||
298
sexc.scm
298
sexc.scm
@@ -2,30 +2,22 @@
|
|||||||
(scheme base) ; call/cc
|
(scheme base) ; call/cc
|
||||||
brev-separate
|
brev-separate
|
||||||
(chicken base)
|
(chicken base)
|
||||||
(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)
|
||||||
(chicken process-context)
|
(chicken process-context)
|
||||||
(chicken port)
|
(chicken port)
|
||||||
(chicken string) ; string-split
|
|
||||||
fmt
|
fmt
|
||||||
fmt-c-writer
|
fmt-c-writer
|
||||||
getopt-long
|
getopt-long
|
||||||
sex-macros
|
sex-macros
|
||||||
sex-modules
|
sex-modules
|
||||||
sex-query
|
|
||||||
reader
|
reader
|
||||||
semen
|
semen
|
||||||
srfi-1 ; list routines
|
srfi-1 ; list routines
|
||||||
utils)
|
utils)
|
||||||
|
|
||||||
(export
|
|
||||||
main)
|
|
||||||
|
|
||||||
;;; Main function facilities
|
;;; Main function facilities
|
||||||
|
|
||||||
(define opts-grammar
|
(define opts-grammar
|
||||||
@@ -38,17 +30,6 @@
|
|||||||
(required #f)
|
(required #f)
|
||||||
(value #f)
|
(value #f)
|
||||||
(single-char #\c))
|
(single-char #\c))
|
||||||
(features ,(fmt #f "Comma-separated feature names, added to the host's own" nl
|
|
||||||
(pad padding) "for #+ and #- feature expressions. May be given" nl
|
|
||||||
(pad padding) "more than once")
|
|
||||||
(required #f)
|
|
||||||
(value #t)
|
|
||||||
(single-char #\f))
|
|
||||||
(no-platform-features
|
|
||||||
,(fmt #f "Leave out the host's own features. With --features," nl
|
|
||||||
(pad padding) "this reads a file the way another platform would")
|
|
||||||
(required #f)
|
|
||||||
(value #f))
|
|
||||||
(emit-c "Emit C code"
|
(emit-c "Emit C code"
|
||||||
(required #f)
|
(required #f)
|
||||||
(value #f)
|
(value #f)
|
||||||
@@ -65,35 +46,16 @@
|
|||||||
(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 -E or -m options are provided, defaults to stdout")
|
||||||
(pad padding) "which `-' names too")
|
|
||||||
(required #f)
|
(required #f)
|
||||||
(value #t)
|
(value #t)
|
||||||
(single-char #\o))
|
(single-char #\o))
|
||||||
(depfile
|
|
||||||
,(fmt #f "Write a make rule for the output to FILE: it depends on" nl
|
|
||||||
(pad padding) "the source and on every module read for it. Needs -o")
|
|
||||||
(required #f)
|
|
||||||
(value #t))
|
|
||||||
(line-directives
|
(line-directives
|
||||||
,(fmt #f "How much #line information to emit: statement (default)," nl
|
,(fmt #f "How much #line information to emit: statement (default)," nl
|
||||||
(pad padding) "toplevel, or none. `statement' is what makes a debugger" nl
|
(pad padding) "toplevel, or none. `statement' is what makes a debugger" nl
|
||||||
(pad padding) "land on the right source line; `none' is for reading -C" nl
|
(pad padding) "land on the right source line; `none' is for reading -C" nl
|
||||||
(pad padding) "output by eye")
|
(pad padding) "output by eye")
|
||||||
(required #f)
|
(required #f)
|
||||||
(value #t))
|
|
||||||
(check ,(fmt #f "Print semantic diagnostics as an s-expression and" nl
|
|
||||||
(pad padding) "do not compile. Exit status is non-zero only" nl
|
|
||||||
(pad padding) "when the file cannot be read")
|
|
||||||
(required #f)
|
|
||||||
(value #f))
|
|
||||||
(symbols "Print the symbol table as an s-expression and do not compile"
|
|
||||||
(required #f)
|
|
||||||
(value #f))
|
|
||||||
(expand-lines
|
|
||||||
,(fmt #f "Print the C for Sex lines START:END. START with no end," nl
|
|
||||||
(pad padding) "or `:`, is the whole buffer. Does not compile")
|
|
||||||
(required #f)
|
|
||||||
(value #t)))))
|
(value #t)))))
|
||||||
|
|
||||||
(define (print-help)
|
(define (print-help)
|
||||||
@@ -125,23 +87,6 @@
|
|||||||
(list)
|
(list)
|
||||||
(cdr tail))))
|
(cdr tail))))
|
||||||
|
|
||||||
;;; getopt-long reads a lone `-' as an option, so `-o -' died there as
|
|
||||||
;;; one missing its value. `--output=-' is the spelling it takes
|
|
||||||
(define (spell-stdout-output argv)
|
|
||||||
(let loop ((as argv) (acc (list)))
|
|
||||||
(cond ((null? as) (reverse acc))
|
|
||||||
((and (member (car as) '("-o" "--output"))
|
|
||||||
(pair? (cdr as))
|
|
||||||
(string=? (cadr as) "-"))
|
|
||||||
(loop (cddr as) (cons "--output=-" acc)))
|
|
||||||
(else (loop (cdr as) (cons (car as) acc))))))
|
|
||||||
|
|
||||||
;;; ...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)))
|
||||||
|
|
||||||
@@ -152,48 +97,17 @@
|
|||||||
((equal? v "none") 'none)
|
((equal? v "none") 'none)
|
||||||
(else (error "--line-directives must be statement, toplevel or none, got" v)))))
|
(else (error "--line-directives must be statement, toplevel or none, got" v)))))
|
||||||
|
|
||||||
|
(define (get-input-file args)
|
||||||
|
(let ((rest-args (get-rest-args args)))
|
||||||
;;; --features may be given more than once, and each may name several.
|
(if (null? rest-args)
|
||||||
;;; Collect all of them
|
'stdin
|
||||||
(define (cli-features args)
|
(car rest-args))))
|
||||||
(append-map (lambda (entry)
|
|
||||||
(map string->symbol (string-split (cdr entry) ",")))
|
|
||||||
(filter (lambda (entry) (eq? (car entry) 'features)) args)))
|
|
||||||
|
|
||||||
(define (get-input-file args dash?)
|
|
||||||
(let ((inputs (append (if dash? (list "-") (list)) (get-rest-args args))))
|
|
||||||
(cond ((null? inputs) 'stdin)
|
|
||||||
;; any after the first were never read, and nothing said so
|
|
||||||
((pair? (cdr inputs))
|
|
||||||
(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)
|
|
||||||
(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 check symbols expand-lines)))
|
|
||||||
|
|
||||||
(define (write-to-file-or-stdout output what)
|
(define (write-to-file-or-stdout output what)
|
||||||
(if (stdout-output? output)
|
(if (eq? output 'default)
|
||||||
(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
|
||||||
@@ -202,179 +116,73 @@
|
|||||||
(map pp sex-forms)
|
(map pp sex-forms)
|
||||||
(emit-c sex-forms)))))
|
(emit-c sex-forms)))))
|
||||||
|
|
||||||
;;; app.o: app.sex /m/greet.sex, and an empty rule per module, so that
|
|
||||||
;;; make takes a module deleted since as out of date rather than as a
|
|
||||||
;;; file it has no rule to make
|
|
||||||
(define (dependency-rule target source modules)
|
|
||||||
(let ((spell (lambda (path) (string-translate* path '((" " . "\\ "))))))
|
|
||||||
(apply string-append
|
|
||||||
(spell target) ":"
|
|
||||||
(append (map (lambda (path) (string-append " " (spell path)))
|
|
||||||
(if source (cons source modules) modules))
|
|
||||||
(list "\n")
|
|
||||||
(map (lambda (path) (string-append "\n" (spell path) ":\n"))
|
|
||||||
modules)))))
|
|
||||||
|
|
||||||
(define (write-dependencies depfile output input)
|
|
||||||
(when (stdout-output? output)
|
|
||||||
(error "--depfile needs -o, to name what depends on the modules"))
|
|
||||||
(with-output-to-file depfile
|
|
||||||
(lambda ()
|
|
||||||
(display (dependency-rule output
|
|
||||||
(and (not (eq? input 'stdin)) input)
|
|
||||||
(module-dependencies))))))
|
|
||||||
|
|
||||||
(define (compile-to-file sex-forms output args cc-args)
|
(define (compile-to-file sex-forms output args cc-args)
|
||||||
"Hand the generated C to the C compiler. Returns the compiler's exit
|
(let ((compiler (or (get-arg args 'c-compiler #f)
|
||||||
status, which is ours to pass on."
|
(get-env-var "SEX_CC")
|
||||||
;; named with its own options, as make's CC is: "ccache cc", "cc -O2"
|
"cc"))
|
||||||
(let ((compiler (let ((words (string-split (or (get-arg args 'c-compiler #f)
|
|
||||||
(get-env-var "SEX_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)))
|
||||||
;; The generated C goes to a temporary .c file rather than the
|
;; The generated C goes to a temporary .c file rather than the
|
||||||
;; compiler's stdin. It is removed however we leave -- emit-c
|
;; compiler's stdin
|
||||||
;; can throw, and used to leave the file behind when it did
|
(let ((c-file (create-temporary-file "c")))
|
||||||
(c-file (create-temporary-file "c")))
|
|
||||||
;; An unhandled error ends the process without unwinding, so the
|
|
||||||
;; cleanup cannot be left to dynamic-wind
|
|
||||||
(handle-exceptions 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 status
|
||||||
(delete-file* c-file)
|
(delete-file* c-file)
|
||||||
(if normal-exit? status 1)))))))
|
(apply values status)))))))
|
||||||
|
|
||||||
;;; The unit's own forms are checked for what its importers will need,
|
(define (semantic-process-forms raw-forms input-source)
|
||||||
;;; the prelude's not: every unit has those
|
(if (eq? input-source 'stdin)
|
||||||
(define (semantic-process-forms unit-forms input-source)
|
(semen-process raw-forms)
|
||||||
(when (string? input-source)
|
(with-directory input-source
|
||||||
(mark-imported! (to-absolute-pathname input-source)))
|
(semen-process raw-forms))))
|
||||||
(let ((process (lambda ()
|
|
||||||
(check-public-interface unit-forms)
|
|
||||||
(semen-process (append (compiler-prelude) unit-forms)))))
|
|
||||||
(if (eq? input-source 'stdin)
|
|
||||||
(process)
|
|
||||||
(with-directory input-source (process)))))
|
|
||||||
|
|
||||||
;;; Query output. C from --expand-lines owns stdout; diagnostics and the
|
(define prelude
|
||||||
;;; symbol table go beside it on stderr so a slice stays valid text.
|
'((include inttypes.h)
|
||||||
;;; On their own they are the stdout of the command.
|
|
||||||
(define (report-query analysis args output)
|
(typedef u8 uint8-t)
|
||||||
(let* ((expanding? (get-arg args 'expand-lines #f))
|
(typedef i8 int8-t)
|
||||||
(want-check? (get-arg args 'check #f))
|
(typedef u16 uint16-t)
|
||||||
(want-symbols? (get-arg args 'symbols #f))
|
(typedef i16 int16-t)
|
||||||
(range (and expanding? (parse-expand-lines expanding?))))
|
(typedef u32 uint32-t)
|
||||||
;; A reader failure is the one non-zero status. Say what it was,
|
(typedef i32 int32-t)
|
||||||
;; on stdout for --check and on stderr when stdout is C.
|
(typedef u64 uint64-t)
|
||||||
(unless (analysis-read? analysis)
|
(typedef i64 int64-t)))
|
||||||
(let ((where (if (or expanding? (not want-check?))
|
|
||||||
(current-error-port)
|
|
||||||
#f)))
|
|
||||||
(if where
|
|
||||||
(write-diagnostics analysis where)
|
|
||||||
(write-to-file-or-stdout
|
|
||||||
output
|
|
||||||
(lambda () (write-diagnostics analysis (current-output-port))))))
|
|
||||||
(exit 70))
|
|
||||||
(when (or want-check? want-symbols?)
|
|
||||||
(let ((port (if expanding? (current-error-port) #f)))
|
|
||||||
(define (write-reports)
|
|
||||||
(when want-check? (write-diagnostics analysis (current-output-port)))
|
|
||||||
(when want-symbols? (write-symbols analysis (current-output-port))))
|
|
||||||
(if port
|
|
||||||
(with-output-to-port port write-reports)
|
|
||||||
(write-to-file-or-stdout output write-reports))))
|
|
||||||
(when expanding?
|
|
||||||
(let ((text (analysis-expand analysis (car range) (cdr range))))
|
|
||||||
(unless text (exit 70))
|
|
||||||
(write-to-file-or-stdout output (lambda () (display text)))))))
|
|
||||||
|
|
||||||
;;; 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 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, --check, --symbols, --expand-lines 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
|
|
||||||
;; in place before the first form is read
|
|
||||||
(current-features
|
|
||||||
(append (if (get-arg args 'no-platform-features #f)
|
|
||||||
(list)
|
|
||||||
(platform-features))
|
|
||||||
(cli-features args)))
|
|
||||||
|
|
||||||
;; before the interface too, which asks the modules it imports
|
|
||||||
;; what types they export
|
|
||||||
(load-persistent-module-paths)
|
|
||||||
|
|
||||||
(when (or (get-arg args 'check #f)
|
|
||||||
(get-arg args 'symbols #f)
|
|
||||||
(get-arg args 'expand-lines #f))
|
|
||||||
(report-query (if (eq? input 'stdin)
|
|
||||||
(analyze-port (current-input-port) "stdin")
|
|
||||||
(analyze-file input))
|
|
||||||
args output)
|
|
||||||
(return #f))
|
|
||||||
|
|
||||||
(when (get-arg args 'public-interface #f)
|
(when (get-arg args 'public-interface #f)
|
||||||
(assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument")
|
(assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument")
|
||||||
|
|
||||||
(write-to-file-or-stdout
|
(write-to-file-or-stdout
|
||||||
output
|
output
|
||||||
(fn
|
(fn
|
||||||
(map pp (read-public-interface input))))
|
(map pp (reverse
|
||||||
|
(read-public-interface input)))))
|
||||||
(return #f))
|
(return #f))
|
||||||
|
(load-persistent-module-paths)
|
||||||
|
|
||||||
;; The file name in a #line directive now comes from the form's
|
;; The file name in a #line directive now comes from the form's
|
||||||
;; own recorded location, so imported modules report themselves
|
;; own recorded location, so imported modules report themselves
|
||||||
@@ -384,15 +192,11 @@ status, which is ours to pass on."
|
|||||||
(not (get-arg args 'line-directives #f)))
|
(not (get-arg args 'line-directives #f)))
|
||||||
(sex-line-directives 'none))
|
(sex-line-directives 'none))
|
||||||
|
|
||||||
(let ((sex-forms (semantic-process-forms (read-raw-forms input) input)))
|
(let* ((raw-forms (append prelude (read-raw-forms input)))
|
||||||
(let ((depfile (get-arg args 'depfile #f)))
|
(sex-forms (semantic-process-forms raw-forms input)))
|
||||||
(when depfile
|
|
||||||
(write-dependencies depfile output input)))
|
|
||||||
(if (or (get-arg args 'macro-expand #f)
|
(if (or (get-arg args 'macro-expand #f)
|
||||||
(get-arg args 'emit-c #f))
|
(get-arg args 'emit-c #f))
|
||||||
;; Emit processed and macro-expanded sex code, or emit C code
|
;; Emit processed and macro-expanded sex code, or emit C code
|
||||||
(emit-c-or-sex sex-forms output args)
|
(emit-c-or-sex sex-forms output args)
|
||||||
;; Compile file! The C compiler's status is ours too
|
;; Compile file!
|
||||||
(let ((status (compile-to-file sex-forms output args cc-args)))
|
(compile-to-file sex-forms output args cc-args)))))))
|
||||||
(unless (zero? status)
|
|
||||||
(exit status)))))))))
|
|
||||||
|
|||||||
48
tests/Makefile
Normal file
48
tests/Makefile
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
CHICKEN_C = csc
|
||||||
|
|
||||||
|
CSC_FLAGS += -K prefix -static
|
||||||
|
MODULE_FLAGS = -emit-all-import-libraries -module-registration -c
|
||||||
|
|
||||||
|
MODULES = utils types sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc
|
||||||
|
SEX_OBJ = $(MODULES:%=%.o)
|
||||||
|
|
||||||
|
TESTS = basic semen reader fmt-c-writer utils line-directives codegen args types
|
||||||
|
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
|
||||||
|
|
||||||
|
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 utils.o
|
||||||
|
$(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,utils
|
||||||
|
|
||||||
|
semen.o: semen.module.scm ../semen.scm 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,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 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,utils
|
||||||
|
|
||||||
|
sexc.o: sexc.module.scm 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,types,utils
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -f $(SEX_OBJ)
|
||||||
|
rm -f *.import.scm
|
||||||
|
rm -f *.link
|
||||||
|
rm -f sex-tests
|
||||||
55
tests/args.scm
Normal file
55
tests/args.scm
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
;;; 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 '())))
|
||||||
51
tests/basic.scm
Normal file
51
tests/basic.scm
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
(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 '--->>>))
|
||||||
|
|
||||||
|
;; 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))
|
||||||
|
|
||||||
|
;; c89 stuff
|
||||||
|
(test 'int (atom-to-fmt-c 'bool))
|
||||||
|
(test 1 (atom-to-fmt-c 'true))
|
||||||
|
(test 0 (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 "))))
|
||||||
1121
tests/codegen.scm
1121
tests/codegen.scm
File diff suppressed because it is too large
Load Diff
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# Stands in for the C compiler: writes the arguments it was given, one
|
|
||||||
# to a line, to $CC_ARGUMENTS
|
|
||||||
printf '%s\n' "$@" > "$CC_ARGUMENTS"
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
;;; What sexc makes of its command line.
|
|
||||||
;;;
|
|
||||||
;;; Everything after the first `--' is the C compiler's, word for word;
|
|
||||||
;;; `-o -' is stdout; --depfile writes a make rule. Each shows only in
|
|
||||||
;;; what a sexc process hands on, so each is checked on one. `cc' here
|
|
||||||
;;; stands in for the compiler and writes down the arguments it got.
|
|
||||||
;;;
|
|
||||||
;;; make check-command-line
|
|
||||||
|
|
||||||
(import scheme
|
|
||||||
(chicken base)
|
|
||||||
(chicken file)
|
|
||||||
(chicken io)
|
|
||||||
(chicken pathname)
|
|
||||||
(chicken process)
|
|
||||||
(chicken process-context)
|
|
||||||
(chicken string)
|
|
||||||
srfi-1
|
|
||||||
test)
|
|
||||||
|
|
||||||
(define sexc (or (get-environment-variable "SEXC") "../../sexc"))
|
|
||||||
|
|
||||||
(define scratch (create-temporary-directory))
|
|
||||||
(define (built name) (make-pathname scratch name))
|
|
||||||
|
|
||||||
(define cc-arguments-file (built "cc-arguments"))
|
|
||||||
(set-environment-variable! "CC_ARGUMENTS" cc-arguments-file)
|
|
||||||
(define cc-option (string-append "--c-compiler=" (make-pathname (current-directory) "cc")))
|
|
||||||
|
|
||||||
;;; The lines sexc prints when run with ARGS and INPUT on its stdin, or
|
|
||||||
;;; #f when it fails
|
|
||||||
(define (output-with-input input . args)
|
|
||||||
(let ((proc (process sexc args)))
|
|
||||||
(display input (process-input-port proc))
|
|
||||||
(close-output-port (process-input-port proc))
|
|
||||||
(let ((lines (read-lines (process-output-port proc))))
|
|
||||||
(process-wait proc)
|
|
||||||
(and (process-returned-normally? proc)
|
|
||||||
(zero? (process-exit-status proc))
|
|
||||||
lines))))
|
|
||||||
|
|
||||||
(define (output-of . args)
|
|
||||||
(apply output-with-input "" args))
|
|
||||||
|
|
||||||
(define (cc-arguments)
|
|
||||||
(call-with-input-file cc-arguments-file read-lines))
|
|
||||||
|
|
||||||
;;; ("-o" "a" "/tmp/x.c" "-lm") -> ("-lm")
|
|
||||||
(define (past-c-file arguments)
|
|
||||||
(cdr (find-tail (lambda (a) (equal? (pathname-extension a) "c")) arguments)))
|
|
||||||
|
|
||||||
;;; What the compiler got past sexc's own -o and .c file, when sexc
|
|
||||||
;;; compiles with ARGS
|
|
||||||
(define (cc-tail . args)
|
|
||||||
(and (apply output-of cc-option args)
|
|
||||||
(past-c-file (cc-arguments))))
|
|
||||||
|
|
||||||
(define hello (string-intersperse (call-with-input-file "hello.sex" read-lines) "\n"))
|
|
||||||
|
|
||||||
(test-group "--"
|
|
||||||
;; `OpenGL' has no dash, and was once dropped for it, leaving
|
|
||||||
;; -framework to swallow whatever came next
|
|
||||||
(test "what follows reaches the compiler as written"
|
|
||||||
'("-framework" "OpenGL" "-Wall")
|
|
||||||
(cc-tail "hello.sex" "-o" (built "a") "--" "-framework" "OpenGL" "-Wall"))
|
|
||||||
(test "what precedes stays with sexc"
|
|
||||||
(list "-o" (built "a"))
|
|
||||||
(begin (cc-tail "hello.sex" "-o" (built "a") "--" "-lm")
|
|
||||||
(take (cc-arguments) 2)))
|
|
||||||
(test "without one the compiler gets nothing more"
|
|
||||||
'()
|
|
||||||
(cc-tail "hello.sex" "-o" (built "a")))
|
|
||||||
(test "nor after a trailing one"
|
|
||||||
'()
|
|
||||||
(cc-tail "hello.sex" "-o" (built "a") "--"))
|
|
||||||
;; ld takes a `--' of its own
|
|
||||||
(test "only the first one separates"
|
|
||||||
'("-Wl,--as-needed" "--" "-lm")
|
|
||||||
(cc-tail "hello.sex" "-o" (built "a") "--" "-Wl,--as-needed" "--" "-lm"))
|
|
||||||
(test "a file after it is the compiler's, and the source is stdin"
|
|
||||||
'("extra.o")
|
|
||||||
(and (output-with-input hello cc-option "-o" (built "a") "--" "extra.o")
|
|
||||||
(past-c-file (cc-arguments)))))
|
|
||||||
|
|
||||||
;;; getopt-long reads a lone `-' as an option, and refused `-o -'
|
|
||||||
(test-group "-o -"
|
|
||||||
(test-assert "writes the C to stdout"
|
|
||||||
(member "int main (void) {" (or (output-of "hello.sex" "-C" "-o" "-") '())))
|
|
||||||
(test-assert "and so does --output -"
|
|
||||||
(member "int main (void) {" (or (output-of "hello.sex" "-C" "--output" "-") '()))))
|
|
||||||
|
|
||||||
;;; The rules for the modules a unit imports are checked in tests/modules
|
|
||||||
(test-group "--depfile"
|
|
||||||
(copy-file "hello.sex" (built "a b.sex"))
|
|
||||||
(test "a space is escaped, the way make reads it"
|
|
||||||
(list (string-append (built "a\\ b.c") ": " (built "a\\ b.sex")))
|
|
||||||
(and (output-of (built "a b.sex") "-C" "-o" (built "a b.c")
|
|
||||||
(string-append "--depfile=" (built "a b.d")))
|
|
||||||
(call-with-input-file (built "a b.d") read-lines)))
|
|
||||||
(test "stdin is no file to depend on"
|
|
||||||
(list (string-append (built "hello.c") ":"))
|
|
||||||
(and (output-with-input hello "-C" "-o" (built "hello.c")
|
|
||||||
(string-append "--depfile=" (built "hello.d")))
|
|
||||||
(call-with-input-file (built "hello.d") read-lines))))
|
|
||||||
|
|
||||||
(delete-directory scratch #t)
|
|
||||||
|
|
||||||
(test-exit)
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
(pub fn main () int
|
|
||||||
(return 0))
|
|
||||||
@@ -1,505 +0,0 @@
|
|||||||
;;; record, ops, sum and match, through the whole pipeline.
|
|
||||||
;;;
|
|
||||||
;;; The diagnostics are the point of these forms -- a match that
|
|
||||||
;;; leaves a variant out is the thing C cannot say -- so most of what
|
|
||||||
;;; is checked here is what the compiler refuses, and that it refuses
|
|
||||||
;;; it with the name of whatever is wrong.
|
|
||||||
;;;
|
|
||||||
;;; `in-fn' comes from codegen.scm, which run.scm includes first.
|
|
||||||
|
|
||||||
(import sex-modules)
|
|
||||||
|
|
||||||
(define (interface-of source)
|
|
||||||
"The declarations SOURCE, compiled as a module, hands its importers
|
|
||||||
ahead of its pub forms."
|
|
||||||
(check-public-interface (read-source source)))
|
|
||||||
|
|
||||||
(define (interface-reports? source fragment)
|
|
||||||
(fails-with? (lambda () (interface-of source)) fragment))
|
|
||||||
|
|
||||||
(define (ops-src . body)
|
|
||||||
(string-append
|
|
||||||
"(record vec2 ((x float) (y float)))"
|
|
||||||
"(ops vec2"
|
|
||||||
" (pub fn length ((self (* const vec2))) float (return 1.0))"
|
|
||||||
" (fn sum-of ((self vec2)) float (return (. self x)))"
|
|
||||||
" (fn scale ((self (* vec2))) void (= (. self x) 2.0)))"
|
|
||||||
"(fn mk () vec2 (return #(vec2 : 1.0 2.0)))"
|
|
||||||
"(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) "
|
|
||||||
(apply string-append body) ")"))
|
|
||||||
|
|
||||||
(define forward-src
|
|
||||||
(string-append
|
|
||||||
"(record pb ((n int)))"
|
|
||||||
"(ops pb"
|
|
||||||
" (fn twice ((self (* pb))) int (return (* 2 (.len self))))"
|
|
||||||
" (pub fn len ((self (* pb))) int (return (. self n))))"))
|
|
||||||
|
|
||||||
(define (sum-src . body)
|
|
||||||
(string-append
|
|
||||||
"(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))"
|
|
||||||
"(fn mk () shape (return (shape/circle 1.0)))"
|
|
||||||
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
|
|
||||||
(apply string-append body) ")"))
|
|
||||||
|
|
||||||
(test-group "encapsulation"
|
|
||||||
|
|
||||||
;; A record is a struct plus a typedef of its own name, so the bare
|
|
||||||
;; name stands where (struct name) had to.
|
|
||||||
(test-group "record"
|
|
||||||
(test-assert "emits the struct"
|
|
||||||
(emits? "(record point ((x int) (y int)))" "struct point {"))
|
|
||||||
(test-assert "and a typedef of the same name"
|
|
||||||
(emits? "(record point ((x int) (y int)))" "typedef struct point point;"))
|
|
||||||
(test-assert "so the bare name is a type"
|
|
||||||
(emits? "(record point ((x int)))(fn f () void (var p point))" "point p;"))
|
|
||||||
(test-assert "and so is a pointer to it"
|
|
||||||
(emits? "(record point ((x int)))(fn f () void (var p (* const point)))"
|
|
||||||
"const point * p"))
|
|
||||||
(test-assert "struct keeps C's meaning"
|
|
||||||
(not (emits? "(struct raw ((x int)))" "typedef")))
|
|
||||||
(test-assert "a record needs a name"
|
|
||||||
(reports? "(record ((x int)))" "record needs a name"))
|
|
||||||
;; An opaque handle: the declaration is public, the fields are not
|
|
||||||
(test-assert "declared, then defined, is still defined"
|
|
||||||
(emits? "(pub record h)(record h ((x int)))" "struct h {")))
|
|
||||||
|
|
||||||
;; An ops block is mangled functions plus a registry entry. `pub'
|
|
||||||
;; inside it means what it means outside.
|
|
||||||
(test-group "ops"
|
|
||||||
(test-assert "a method is the type and the name, mangled"
|
|
||||||
(emits? (ops-src "") "float vec2ːlength"))
|
|
||||||
(test-assert "a pub method has external linkage"
|
|
||||||
(not (emits? (ops-src "") "static float vec2ːlength")))
|
|
||||||
(test-assert "a private one does not"
|
|
||||||
(emits? (ops-src "") "static float vec2ːsum_of"))
|
|
||||||
(test-assert "the slash is not a division"
|
|
||||||
(emits? "(fn f () int (return (/ 10 2)))" "10 / 2"))
|
|
||||||
(test-assert "ops needs a type name"
|
|
||||||
(reports? "(ops (fn g ((s int)) void))" "ops needs a type name"))
|
|
||||||
(test-assert "and takes only fn forms"
|
|
||||||
(reports? "(record v ((x int)))(ops v (var n int 1))" "ops takes fn forms"))
|
|
||||||
(test-assert "a method is defined once"
|
|
||||||
(reports? (string-append "(record v ((x int)))"
|
|
||||||
"(ops v (fn g ((s v)) int (return 1))"
|
|
||||||
" (fn g ((s v)) int (return 2)))")
|
|
||||||
"method is already defined on"))
|
|
||||||
(test-assert "pub goes on the methods, not the block"
|
|
||||||
(reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))
|
|
||||||
;; Every method is known before any body is walked, and C is told of
|
|
||||||
;; one before a body above it calls it -- and only then
|
|
||||||
(test-assert "a method can call one written below it"
|
|
||||||
(emits? forward-src "return 2 * pbːlen(self)"))
|
|
||||||
(test-assert "which is declared ahead of the call"
|
|
||||||
(emits? forward-src "int pbːlen (pb * self);"))
|
|
||||||
(test-assert "and nothing else is"
|
|
||||||
(not (emits? (ops-src "") "vec2ːsum_of (vec2 self);"))))
|
|
||||||
|
|
||||||
;; The method sits in the head, so the shape of a form can be read
|
|
||||||
;; without knowing the receiver's type.
|
|
||||||
(test-group "method calls"
|
|
||||||
(test-assert "a value meeting a pointer self is addressed"
|
|
||||||
(emits? (ops-src "(.length v)") "vec2ːlength(&v)"))
|
|
||||||
(test-assert "a pointer meeting a pointer self is passed along"
|
|
||||||
(emits? (ops-src "(.length p)") "vec2ːlength(p)"))
|
|
||||||
(test-assert "a pointer meeting a value self is dereferenced"
|
|
||||||
(emits? (ops-src "(.sum-of p)") "vec2ːsum_of(*p)"))
|
|
||||||
(test-assert "a value meeting a value self is passed along"
|
|
||||||
(emits? (ops-src "(.sum-of v)") "vec2ːsum_of(v)"))
|
|
||||||
(test-assert "a field is still a field"
|
|
||||||
(emits? (ops-src "(var q float (. v x))") "v.x"))
|
|
||||||
;; the whole reason the method moved into the head
|
|
||||||
(test-assert "a field and a method of one name coexist"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(ops w (fn x ((self (* const w))) int (return 2)))"
|
|
||||||
"(fn f () void (var a w #(w : 1)) (var b int (. a x))"
|
|
||||||
" (var c int (.x a)))")
|
|
||||||
"wːx(&a)"))
|
|
||||||
(test-assert "and the field reading is untouched"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(ops w (fn x ((self (* const w))) int (return 2)))"
|
|
||||||
"(fn f () void (var a w #(w : 1)) (var b int (. a x)))")
|
|
||||||
"int b = a.x"))
|
|
||||||
(test-assert "a method that is not there is named"
|
|
||||||
(reports? (ops-src "(.nope v)") "no such method on"))
|
|
||||||
(test-assert "and so is a receiver with no type to dispatch on"
|
|
||||||
(reports? "(fn f () void (var n int 1) (.get n))" "no such method on"))
|
|
||||||
(test-assert "a self spread over the parameter is a pointer self too"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(ops w (fn get ((self * const w)) int (return (. self x))))"
|
|
||||||
"(fn f () int (var a w #(w : 1)) (var p (* const w) (& a))"
|
|
||||||
" (return (+ (.get a) (.get p))))")
|
|
||||||
"wːget(&a) + wːget(p)"))
|
|
||||||
(test-assert "a const receiver is not handed to a method that may change it"
|
|
||||||
(reports? (ops-src "(var c (* const vec2) p) (.scale c)")
|
|
||||||
"this one is const"))
|
|
||||||
(test-assert "one that cannot change it takes it"
|
|
||||||
(emits? (ops-src "(var c (* const vec2) p) (var n float (.length c))")
|
|
||||||
"vec2ːlength(c)"))
|
|
||||||
(test-assert "a macro receiver is typed by what it expands to"
|
|
||||||
(emits? (string-append "(defmacro (the a) a)"
|
|
||||||
(ops-src "(var n float (.length (the v)))"))
|
|
||||||
"vec2ːlength(&v)"))
|
|
||||||
(test-assert "and so is the start of a path"
|
|
||||||
(emits? (string-append "(defmacro (the a) a)"
|
|
||||||
(ops-src "(var q float (. (the p) x))"))
|
|
||||||
"p->x"))
|
|
||||||
(test-assert "a typedef of the type has its methods"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(typedef alias w)"
|
|
||||||
"(ops w (fn get ((self (* const w))) int (return (. self x))))"
|
|
||||||
"(fn f () int (var a alias #(alias : 1)) (return (.get a)))")
|
|
||||||
"wːget(&a)"))
|
|
||||||
(test-assert "and a method written on the typedef is the type's"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(typedef alias w)"
|
|
||||||
"(ops alias (fn get ((self (* const alias))) int (return 1)))"
|
|
||||||
"(fn f () int (var a w #(w : 1)) (return (.get a)))")
|
|
||||||
"aliasːget(&a)"))
|
|
||||||
(test-assert "a typedef of a scalar keeps its own"
|
|
||||||
(reports? (string-append
|
|
||||||
"(typedef meters float)"
|
|
||||||
"(ops meters (fn half ((self meters)) meters (return self)))"
|
|
||||||
"(fn f () void (var x float 1.0) (.half x))")
|
|
||||||
"no such method on"))
|
|
||||||
(test-assert "which a typedef of it shares"
|
|
||||||
(emits? (string-append
|
|
||||||
"(typedef meters float)"
|
|
||||||
"(typedef km meters)"
|
|
||||||
"(ops meters (fn half ((self meters)) meters (return self)))"
|
|
||||||
"(fn f () void (var x km 1.0) (var y km (.half x)))")
|
|
||||||
"metersːhalf(x)"))
|
|
||||||
(test-assert "a method call inside a literal is still a call"
|
|
||||||
(emits? (ops-src "(var w vec2 #(vec2 : (.length v) 1.0))")
|
|
||||||
"(vec2){vec2ːlength(&v), 1.0}"))
|
|
||||||
(test-assert "however deep"
|
|
||||||
(emits? (ops-src "(var ws [vec2 1] #(#(vec2 : (.length p) 1.0)))")
|
|
||||||
"{(vec2){vec2ːlength(p), 1.0}}"))
|
|
||||||
(test-assert "an address cannot be taken of a call"
|
|
||||||
(reports? (ops-src "(.length (mk))") "receiver is not an lvalue"))
|
|
||||||
;; the inner call has to be typed to find the outer one's receiver
|
|
||||||
(test-assert "a method call can be another's receiver"
|
|
||||||
(emits? (string-append
|
|
||||||
"(record w ((x int)))"
|
|
||||||
"(ops w (fn twice ((a w)) w (return a))"
|
|
||||||
" (fn get ((a w)) int (return (. a x))))"
|
|
||||||
"(fn f () int (var a w #(w : 1)) (return (.get (.twice a))))")
|
|
||||||
"wːget(wːtwice(a))")))
|
|
||||||
|
|
||||||
;; A sum is the tag enum, a payload struct per variant that carries
|
|
||||||
;; fields, the record holding both, and a constructor each.
|
|
||||||
(test-group "sum"
|
|
||||||
(test-assert "the tag enum is named after the sum"
|
|
||||||
(emits? (sum-src "") "enum shapeǂ {"))
|
|
||||||
(test-assert "and its constants after the sum and the variant"
|
|
||||||
(emits? (sum-src "") "shapeǂcircle"))
|
|
||||||
(test-assert "a variant may be called tag"
|
|
||||||
(emits? "(sum t ((tag ((x int))) (none ())))" "struct tːtag {"))
|
|
||||||
(test-assert "a variant with fields gets a payload struct"
|
|
||||||
(emits? (sum-src "") "struct shapeːcircle {"))
|
|
||||||
(test-assert "the sum is typedef'd"
|
|
||||||
(emits? (sum-src "") "typedef struct shape shape;"))
|
|
||||||
;; a typedef here would land in the namespace the constructor holds
|
|
||||||
(test-assert "a payload struct is not"
|
|
||||||
(not (emits? (sum-src "") "typedef struct shapeːcircle")))
|
|
||||||
(test-assert "the typedef comes before the payloads, for a recursive sum"
|
|
||||||
(emits? "(sum expr ((lit ((v float))) (neg ((e (* const expr))))))"
|
|
||||||
"typedef struct expr expr;"))
|
|
||||||
(test-assert "a constructor is written in place"
|
|
||||||
(emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
|
|
||||||
"(struct tːa){1}"))
|
|
||||||
(test-assert "and is no function"
|
|
||||||
(not (emits? "(pub sum t ((a ((x int)))))(fn f () t (return (t/a 1)))"
|
|
||||||
"t tːa (")))
|
|
||||||
(test-assert "so it is a constant at file scope"
|
|
||||||
(emits? "(sum t ((a ((x int)))))(var g t (t/a 1))"
|
|
||||||
"static t g = {.tag = tǂa, .u = {.a = {1}}};"))
|
|
||||||
(test-assert "as is any literal a global starts from"
|
|
||||||
(emits? "(record point ((x int) (y int)))(var g point #(point : 1 2))"
|
|
||||||
"static point g = {1, 2};"))
|
|
||||||
(test-assert "and an lvalue a method can take the address of"
|
|
||||||
(emits? (string-append
|
|
||||||
"(sum t ((a ((x int)))))"
|
|
||||||
"(ops t (fn get ((self (* const t))) int (return 1)))"
|
|
||||||
"(fn f () int (return (.get (t/a 1))))")
|
|
||||||
"tːget(&(t){"))
|
|
||||||
(test-assert "a constructor takes as many arguments as its variant has fields"
|
|
||||||
(reports? "(sum t ((a ((x int)))))(fn f () t (return (t/a 1 2)))"
|
|
||||||
"variant takes this many fields"))
|
|
||||||
(test-assert "and is not a function value"
|
|
||||||
(reports? "(sum t ((a ((x int)))))(fn f () void (var g (fn ((x int)) t) t/a))"
|
|
||||||
"a constructor is not a function"))
|
|
||||||
(test-assert "an array field takes a brace literal as it is"
|
|
||||||
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2))))"
|
|
||||||
"(struct tːa){{1, 2}}"))
|
|
||||||
(test-assert "and an array by its elements"
|
|
||||||
(emits? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 2] #(1 2)) (return (t/a v)))"
|
|
||||||
"(struct tːa){{v[0], v[1]}}"))
|
|
||||||
(test-assert "which have to be countable"
|
|
||||||
(reports? "(fn n () int (return 2))(sum t ((a ((xs [int (n)])))))"
|
|
||||||
"array field needs a length"))
|
|
||||||
(test-assert "and as many as the field holds"
|
|
||||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var v [int 3] #(1 2 3)) (return (t/a v)))"
|
|
||||||
"array is not as long as its field"))
|
|
||||||
(test-assert "and so must a literal"
|
|
||||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1 2 3))))"
|
|
||||||
"array is not as long as its field"))
|
|
||||||
(test-assert "not filling it with zeros either"
|
|
||||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (return (t/a #(1))))"
|
|
||||||
"array is not as long as its field"))
|
|
||||||
(test-assert "an array field takes an array"
|
|
||||||
(reports? "(sum t ((a ((xs [int 2])))))(fn f () t (var p (* int) 0) (return (t/a p)))"
|
|
||||||
"an array field takes an array"))
|
|
||||||
(test-assert "read from a path, not from a call"
|
|
||||||
(reports? (string-append "(sum t ((a ((xs [int 2])))))(fn g () int (return 0))"
|
|
||||||
"(fn f () t (var m [t 2]) (return (t/a (. [m (g)] u a xs))))")
|
|
||||||
"bind it to a var first"))
|
|
||||||
(test-assert "an array binder is a copy of each element"
|
|
||||||
(emits? (string-append "(sum t ((a ((xs [int 2])))))"
|
|
||||||
"(fn f ((s t)) int (match s ((a (xs)) (return [xs 0]))))")
|
|
||||||
"int xs[2] = {s.u.a.xs[0], s.u.a.xs[1]}"))
|
|
||||||
(test-assert "a sum cannot hold itself"
|
|
||||||
(reports? "(sum box ((inner ((x box)))))" "a sum holds itself through a pointer"))
|
|
||||||
(test-assert "nor an array of itself"
|
|
||||||
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
|
|
||||||
(test-assert "though it can point at itself"
|
|
||||||
(emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
|
|
||||||
(test-assert "a function fills a function-pointer field"
|
|
||||||
(emits? (string-append
|
|
||||||
"(fn g ((n int)) int (return n))"
|
|
||||||
"(sum t ((a ((k (fn ((int)) int))))))"
|
|
||||||
"(fn f () t (return (t/a g)))")
|
|
||||||
"(struct tːa){g}"))
|
|
||||||
(test-assert "a tag-only sum has no union at all"
|
|
||||||
(not (emits? "(sum light ((red ()) (green ())))" "union")))
|
|
||||||
(test-assert "a sum is declared once"
|
|
||||||
(reports? "(sum t ((a ())))(sum t ((b ())))" "sum is already defined"))
|
|
||||||
(test-assert "and needs variants"
|
|
||||||
(reports? "(sum t)" "sum needs a name and a list of variants"))
|
|
||||||
(test-assert "a variant is a name and a field list"
|
|
||||||
(reports? "(sum t (a))" "a variant is"))
|
|
||||||
(test-assert "and is declared once"
|
|
||||||
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
|
|
||||||
|
|
||||||
;; match is an if over the tag whose arms bind the payload. What
|
|
||||||
;; it refuses is why it exists.
|
|
||||||
(test-group "match"
|
|
||||||
(test-assert "it tests the tag"
|
|
||||||
(emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))"
|
|
||||||
" ((empty ()) (= out 0.0)))")
|
|
||||||
"if (s.tag == shapeǂcircle)"))
|
|
||||||
(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"
|
|
||||||
(emits? (sum-src "(match s ((circle (r)) (= out r)) ((rect (w h)) (= out w))"
|
|
||||||
" ((empty ()) (= out 0.0)))")
|
|
||||||
"float r = s.u.circle.r"))
|
|
||||||
(test-assert "_ binds nothing"
|
|
||||||
(not (emits? (sum-src "(match s ((circle (r)) (= out r))"
|
|
||||||
" ((rect (w _)) (= out w))"
|
|
||||||
" ((empty ()) (= out 0.0)))")
|
|
||||||
").h")))
|
|
||||||
(test-assert "a scrutinee that is not a path is read once"
|
|
||||||
(emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))")
|
|
||||||
"shape λm0 = mk()"))
|
|
||||||
(test-assert "a path scrutinee is not copied"
|
|
||||||
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
|
|
||||||
"λm0")))
|
|
||||||
(test-assert "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"
|
|
||||||
(emits? (string-append "(defmacro (the a) a)"
|
|
||||||
(sum-src "(match (the s) ((circle (r)) (= out r))"
|
|
||||||
" (else (= out 0.0)))"))
|
|
||||||
"shape λm0 = s"))
|
|
||||||
(test-assert "a typedef of a sum is matched as the sum"
|
|
||||||
(emits? (string-append
|
|
||||||
"(sum shape ((circle ((r int))) (empty ())))"
|
|
||||||
"(typedef alias shape)"
|
|
||||||
"(fn f () int (var s alias (shape/circle 1))"
|
|
||||||
" (match s ((circle (r)) (return r)) ((empty ()) (return 0))))")
|
|
||||||
"s.tag == shapeǂcircle"))
|
|
||||||
(test-assert "else is the last branch, wherever it is written"
|
|
||||||
(let ((c (silently
|
|
||||||
(lambda ()
|
|
||||||
(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"
|
|
||||||
(emits? (sum-src "(match s ((circle (r)) (= out r)) ;; gone\n (else (= out 2.0)))")
|
|
||||||
"out = 2.0"))
|
|
||||||
|
|
||||||
(test-assert "a variant left out is an error"
|
|
||||||
(reports? (sum-src "(match s ((circle (r)) (= out r)))")
|
|
||||||
"match leaves a variant out"))
|
|
||||||
(test-assert "and the missing ones are named"
|
|
||||||
(reports? (sum-src "(match s ((circle (r)) (= out r)))") "rect"))
|
|
||||||
(test-assert "else excuses the rest"
|
|
||||||
(emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
|
|
||||||
"s.tag == shapeǂcircle"))
|
|
||||||
(test-assert "a variant the sum does not have is an error"
|
|
||||||
(reports? (sum-src "(match s ((circle (r)) (= out r)) ((square (w)) (= out w))"
|
|
||||||
" ((rect (w h)) (= out w)) ((empty ()) (= out 0.0)))")
|
|
||||||
"not a variant of"))
|
|
||||||
(test-assert "so is the wrong number of binders"
|
|
||||||
(reports? (sum-src "(match s ((circle (r q)) (= out r)) (else (= out 0.0)))")
|
|
||||||
"variant takes this many fields"))
|
|
||||||
(test-assert "so is the same arm twice"
|
|
||||||
(reports? (sum-src "(match s ((circle (r)) (= out r)) ((circle (q)) (= out q))"
|
|
||||||
" (else (= out 0.0)))")
|
|
||||||
"arm is written twice"))
|
|
||||||
(test-assert "so is a second else"
|
|
||||||
(reports? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0))"
|
|
||||||
" (else (= out 1.0)))")
|
|
||||||
"more than one else"))
|
|
||||||
(test-assert "so is an arm that is not one"
|
|
||||||
(reports? (sum-src "(match s foo)") "an arm is"))
|
|
||||||
(test-assert "match has no value"
|
|
||||||
(reports? (sum-src "(var n float (match s ((circle (r)) r) (else 0.0)))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "not even as an argument"
|
|
||||||
(reports? (sum-src "(= out (match s ((circle (r)) r) (else 0.0)))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "nor as an if's test"
|
|
||||||
(reports? (sum-src "(if (match s ((circle (r)) 1) (else 0)) (= out 1.0))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "nor as a while's"
|
|
||||||
(reports? (sum-src "(while (match s ((circle (r)) 1) (else 0)) (= out 1.0))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "nor in a for's header"
|
|
||||||
(reports? (sum-src "(for (var i int 0) (match s ((circle (r)) 1) (else 0)) (++ i)"
|
|
||||||
" (= out 1.0))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "nor as a case label"
|
|
||||||
(reports? (sum-src "(switch 1 (case (match s ((circle (r)) 1) (else 0)) (= out 1.0)))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "nor as a case/fallthrough's"
|
|
||||||
(reports? (sum-src "(switch 1 (case/fallthrough (match s ((circle (r)) 1) (else 0))"
|
|
||||||
" (= out 1.0)))")
|
|
||||||
"match is a statement"))
|
|
||||||
(test-assert "but an if's branches are statements, the else among them"
|
|
||||||
(emits? (sum-src "(if (== out 0.0) (match s ((circle (r)) (= out r)) (else (= out 1.0)))"
|
|
||||||
" (match s ((circle (r)) (= out 2.0)) (else (= out 3.0))))")
|
|
||||||
"out = 3.0;"))
|
|
||||||
(test-assert "but a case body is a statement"
|
|
||||||
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
|
|
||||||
" (else (= out 0.0)))))")
|
|
||||||
"s.tag == shapeǂcircle"))
|
|
||||||
(test-assert "and so is a lambda's, wherever the lambda stands"
|
|
||||||
(emits? (sum-src "(var c (fn ((shape)) int) (lambda ((v shape)) int"
|
|
||||||
" (match v ((circle (r)) (return 1)) (else (return 0)))))")
|
|
||||||
"v.tag == shapeǂcircle"))
|
|
||||||
;; 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"
|
|
||||||
(reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))"
|
|
||||||
"match wants a sum")))
|
|
||||||
|
|
||||||
;; An importer is given the pub forms and nothing else, so a type one
|
|
||||||
;; of them names has to be among them, or C is told no more of it
|
|
||||||
;; than a declaration can say
|
|
||||||
(test-group "what importers can see"
|
|
||||||
(test "a private record behind a pointer is declared for them"
|
|
||||||
'((record cell))
|
|
||||||
(interface-of "(record cell ((v int))) (pub record shape ((c (* cell))))"))
|
|
||||||
(test "once"
|
|
||||||
'((record cell))
|
|
||||||
(interface-of "(record cell ((v int))) (pub fn f ((a (* cell)) (b (* cell))) void)"))
|
|
||||||
(test "a struct as a struct"
|
|
||||||
'((struct cell))
|
|
||||||
(interface-of "(struct cell ((v int))) (pub fn f ((a (* struct cell))) void)"))
|
|
||||||
(test "a pub one needs nothing"
|
|
||||||
'()
|
|
||||||
(interface-of "(pub record cell ((v int))) (pub record shape ((c cell)))"))
|
|
||||||
(test "nor one only C knows"
|
|
||||||
'()
|
|
||||||
(interface-of "(pub fn f ((p (* FILE)) (n size-t)) void)"))
|
|
||||||
(test "nor a private fn's"
|
|
||||||
'()
|
|
||||||
(interface-of "(record cell ((v int))) (fn f ((c cell)) void)"))
|
|
||||||
;; 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"
|
|
||||||
(interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))"
|
|
||||||
"held by value"))
|
|
||||||
(test-assert "naming the line"
|
|
||||||
(interface-reports? "(record cell ((v int)))\n(pub record shape ((c cell)))"
|
|
||||||
"codegen.sex:2:"))
|
|
||||||
(test-assert "in an array too"
|
|
||||||
(interface-reports? "(record cell ((v int))) (pub record shape ((cs [cell 4])))"
|
|
||||||
"held by value"))
|
|
||||||
(test-assert "returned"
|
|
||||||
(interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value"))
|
|
||||||
(test-assert "or taken by a function a pub one takes"
|
|
||||||
(interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn ((c cell)) void))) void)"
|
|
||||||
"held by value"))
|
|
||||||
(test-assert "or returned by one"
|
|
||||||
(interface-reports? "(record cell ((v int))) (pub fn take ((cb (fn () cell))) void)"
|
|
||||||
"held by value"))
|
|
||||||
(test "but a pointer there is still a pointer"
|
|
||||||
'((record cell))
|
|
||||||
(interface-of "(record cell ((v int))) (pub fn take ((cb (fn ((c (* cell))) void))) void)"))
|
|
||||||
(test-assert "or taken by a pub method"
|
|
||||||
(interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))"
|
|
||||||
"held by value"))
|
|
||||||
(test-assert "a typedef has no declaration to give, pointer or not"
|
|
||||||
(interface-reports? "(typedef small int) (pub fn f ((p (* small))) void)"
|
|
||||||
"this typedef, and C declares one only by defining it"))
|
|
||||||
(test-assert "nor has an enum"
|
|
||||||
(interface-reports? "(enum mood (up down)) (pub var m (* enum mood))"
|
|
||||||
"this enum, and C declares"))
|
|
||||||
(test-assert "a pub handle is held through a pointer"
|
|
||||||
(interface-reports? "(pub record h) (record h ((n int))) (pub fn f ((x h)) void)"
|
|
||||||
"only a handle"))
|
|
||||||
(test "which is all it takes"
|
|
||||||
'()
|
|
||||||
(interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)"))
|
|
||||||
;; A constant has no declaration either, and an array bound or a
|
|
||||||
;; pub define's body hands its name to importers all the same
|
|
||||||
(test-assert "a constant sizing a pub record's array"
|
|
||||||
(interface-reports? "(define N 4) (pub record r ((xs [int N])))"
|
|
||||||
"this define, and C declares one only by defining it"))
|
|
||||||
(test-assert "or used by a pub define"
|
|
||||||
(interface-reports? "(define N 4) (pub define M (* 2 N))" "this define"))
|
|
||||||
(test "is fine when pub"
|
|
||||||
'()
|
|
||||||
(interface-of "(pub define N 4) (pub record r ((xs [int N])))"))
|
|
||||||
(test "as is a literal bound"
|
|
||||||
'()
|
|
||||||
(interface-of "(pub record r ((xs [int 4])))"))))
|
|
||||||
@@ -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)
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
;;; Compiles cleanly, so the only way the build can fail is the bogus
|
|
||||||
;;; flag handed to cc -- which is the point.
|
|
||||||
(pub fn main () int
|
|
||||||
(return 0))
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
;;; Rejected by the writer, so emit-c throws: there is a temporary .c
|
|
||||||
;;; by then, and it must not survive.
|
|
||||||
(fn f () void
|
|
||||||
(var p (* (* char))))
|
|
||||||
3
tests/fmt-c-writer.module.scm
Normal file
3
tests/fmt-c-writer.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module fmt-c-writer
|
||||||
|
*
|
||||||
|
"../fmt-c-writer.scm")
|
||||||
@@ -1,132 +1,159 @@
|
|||||||
;;; 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))))
|
||||||
|
|
||||||
|
;;; Fn defs
|
||||||
|
(test
|
||||||
|
'(%fun void puk ((int) (%array float 8)))
|
||||||
|
(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 int ((int) (%array int))) min)))
|
||||||
|
(walk-struct '(struct mega-kebab
|
||||||
|
((a int)
|
||||||
|
(dob (struct ((year int)
|
||||||
|
(month int)
|
||||||
|
(day int))))
|
||||||
|
(min (fn ((int) (¤ int)) bool)))))))
|
||||||
|
|||||||
145
tests/infer.scm
145
tests/infer.scm
@@ -1,145 +0,0 @@
|
|||||||
;;; Type inference, layer 0.
|
|
||||||
;;;
|
|
||||||
;;; Names registered in the type database are prefixed, since the
|
|
||||||
;;; database is one table shared by every suite in the linked binary.
|
|
||||||
|
|
||||||
(import infer types)
|
|
||||||
|
|
||||||
;;; Parse and print a surface type again. Everything in this suite goes
|
|
||||||
;;; through this pair, which is deliberate: they are the only thing the
|
|
||||||
;;; rest of the compiler will ever see of the IR.
|
|
||||||
(define (round-trip surface)
|
|
||||||
(unparse-type (parse-type surface)))
|
|
||||||
|
|
||||||
(test-group "infer"
|
|
||||||
|
|
||||||
(test-group "round-trip"
|
|
||||||
;; Every spelling below appears in example/ or tests/, or is one
|
|
||||||
;; the C writer documents in walk-type. `type-match' compares types
|
|
||||||
;; with equal?, so a near miss here is not a cosmetic bug -- it is
|
|
||||||
;; a reflection macro silently falling into its else branch.
|
|
||||||
(for-each
|
|
||||||
(lambda (surface)
|
|
||||||
(test (conc "round-trips: " surface) surface (round-trip surface)))
|
|
||||||
'(int
|
|
||||||
void
|
|
||||||
char
|
|
||||||
float
|
|
||||||
double
|
|
||||||
size-t
|
|
||||||
GLfloat
|
|
||||||
(unsigned int)
|
|
||||||
(long long)
|
|
||||||
(const int)
|
|
||||||
(const char)
|
|
||||||
(* char)
|
|
||||||
(* void)
|
|
||||||
(* const char)
|
|
||||||
(* * char)
|
|
||||||
(* const * const char)
|
|
||||||
(const * const char)
|
|
||||||
(* FILE)
|
|
||||||
(* SDL-Window)
|
|
||||||
(struct point)
|
|
||||||
(struct list-int)
|
|
||||||
(union value)
|
|
||||||
(enum mood)
|
|
||||||
(const struct list-int)
|
|
||||||
(* struct list-int)
|
|
||||||
(* const struct point)
|
|
||||||
(¤ int 16)
|
|
||||||
(¤ char 512)
|
|
||||||
(¤ GLfloat 15)
|
|
||||||
(¤ float)
|
|
||||||
(¤ * const char)
|
|
||||||
(¤ * const struct res 32)
|
|
||||||
(¤ (¤ const char))
|
|
||||||
(fn () void)
|
|
||||||
(fn ((int)) int)
|
|
||||||
(fn ((int) (int)) int)
|
|
||||||
(fn ((* const char)) size-t)
|
|
||||||
(fn ((* const char) (...)) int)
|
|
||||||
(fn ((¤ float 4)) void)))
|
|
||||||
|
|
||||||
;; Grouping parens are not part of the type, so these come back
|
|
||||||
;; canonicalised rather than verbatim -- which is the whole reason
|
|
||||||
;; unparse-type exists rather than "keep what was written".
|
|
||||||
(test "a grouped element is the same array" '(¤ int 16) (round-trip '(¤ (int) 16)))
|
|
||||||
(test "a grouped base is the same pointer" '(* const char)
|
|
||||||
(round-trip '(* (const char))))
|
|
||||||
(test "a grouped aggregate keeps its qualifier" '(const struct point)
|
|
||||||
(round-trip '(const (struct point))))
|
|
||||||
|
|
||||||
;; A typedef is transparent to unification and opaque to printing:
|
|
||||||
;; the generated declaration has to say what the programmer said.
|
|
||||||
(add-typedef 'i-handle '(typedef i-handle int))
|
|
||||||
(test "a typedef prints as itself" 'i-handle (round-trip 'i-handle))
|
|
||||||
(test "and qualified, as itself" '(const i-handle) (round-trip '(const i-handle)))
|
|
||||||
(test "and under a pointer" '(* i-handle) (round-trip '(* i-handle))))
|
|
||||||
|
|
||||||
(test-group "wildcards"
|
|
||||||
(test "a bare _ is a variable" '_ (round-trip '_))
|
|
||||||
(test "and composes under a pointer" '(* _) (round-trip '(* _)))
|
|
||||||
(test "and inside an array" '(¤ _ 4) (round-trip '(¤ _ 4)))
|
|
||||||
(test "and in a signature" '(fn ((_)) _) (round-trip '(fn ((_)) _)))
|
|
||||||
|
|
||||||
;; Each _ is its own variable: solving one must not solve the rest.
|
|
||||||
(let ((t (parse-type '(fn ((_)) _))))
|
|
||||||
(unify t (parse-type '(fn ((int)) _)) #f)
|
|
||||||
(test "one hole at a time" '(fn ((int)) _) (unparse-type t))))
|
|
||||||
|
|
||||||
(test-group "decay"
|
|
||||||
;; decay: the conversion C performs at a call site, an operand of
|
|
||||||
;; `+', or the left half of a subscript.
|
|
||||||
(test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16)))))
|
|
||||||
(test "a function decays to a pointer to itself" '(* (fn ((int)) int))
|
|
||||||
(unparse-type (decay (parse-type '(fn ((int)) int)))))
|
|
||||||
(test "anything else is left alone" 'int (unparse-type (decay (parse-type 'int)))))
|
|
||||||
|
|
||||||
(test-group "unification"
|
|
||||||
(test-assert "a type unifies with itself"
|
|
||||||
(unify (parse-type 'int) (parse-type 'int) #f))
|
|
||||||
(test-error "and not with another one"
|
|
||||||
(unify (parse-type 'int) (parse-type 'char) #f))
|
|
||||||
|
|
||||||
(let ((a (parse-type '_)))
|
|
||||||
(unify a (parse-type '(* const char)) #f)
|
|
||||||
(test "a variable takes the shape it is unified with"
|
|
||||||
'(* const char) (unparse-type a)))
|
|
||||||
|
|
||||||
;; The point of the exercise: `(var p (* _) (& x))' with x : int.
|
|
||||||
(let ((p (parse-type '(* _))))
|
|
||||||
(unify p (parse-type '(* int)) #f)
|
|
||||||
(test "a partial type is completed by one step" '(* int) (unparse-type p)))
|
|
||||||
|
|
||||||
(let ((a (parse-type '_))
|
|
||||||
(b (parse-type '_)))
|
|
||||||
(unify a b #f)
|
|
||||||
(unify b (parse-type 'double) #f)
|
|
||||||
(test "two variables joined then solved" 'double (unparse-type a)))
|
|
||||||
|
|
||||||
(test-error "structure has to match"
|
|
||||||
(unify (parse-type '(* int)) (parse-type '(* char)) #f))
|
|
||||||
(test-error "and arity"
|
|
||||||
(unify (parse-type '(fn ((int)) int))
|
|
||||||
(parse-type '(fn ((int) (int)) int)) #f))
|
|
||||||
(test-error "and aggregates are told apart by name"
|
|
||||||
(unify (parse-type '(struct point)) (parse-type '(struct box)) #f))
|
|
||||||
(test-error "and by kind"
|
|
||||||
(unify (parse-type '(struct point)) (parse-type '(union point)) #f))
|
|
||||||
|
|
||||||
;; An unwritten array length constrains nothing, the way it does
|
|
||||||
;; not in C either.
|
|
||||||
(test-assert "an unsized array unifies with a sized one"
|
|
||||||
(unify (parse-type '(¤ int)) (parse-type '(¤ int 16)) #f))
|
|
||||||
(test-error "but two written lengths must agree"
|
|
||||||
(unify (parse-type '(¤ int 4)) (parse-type '(¤ int 16)) #f))
|
|
||||||
|
|
||||||
;; A typedef unifies as whatever it stands for.
|
|
||||||
(add-typedef 'i-count '(typedef i-count int))
|
|
||||||
(test-assert "a typedef unifies with its target"
|
|
||||||
(unify (parse-type 'i-count) (parse-type 'int) #f))
|
|
||||||
(let ((a (parse-type '_)))
|
|
||||||
(unify a (parse-type 'i-count) #f)
|
|
||||||
(test "and keeps its name when it is the one printed"
|
|
||||||
'i-count (unparse-type a)))))
|
|
||||||
@@ -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
|
||||||
@@ -85,10 +86,7 @@
|
|||||||
" (: done)" ; 52
|
" (: done)" ; 52
|
||||||
" (var svar u64 (sizeof (struct pt)))" ; 53
|
" (var svar u64 (sizeof (struct pt)))" ; 53
|
||||||
" (var cvar int (cast mvar int))" ; 54
|
" (var cvar int (cast mvar int))" ; 54
|
||||||
" (putchar (if (< mvar 123)" ; 55 a conditional as an
|
" (return 122))" ; 55
|
||||||
" (putchar 124)" ; 56 argument: an expression,
|
|
||||||
" 125))" ; 57 so no anchor inside it
|
|
||||||
" (return 122))" ; 58
|
|
||||||
))
|
))
|
||||||
|
|
||||||
(define fixture (string-intersperse fixture-lines "\n"))
|
(define fixture (string-intersperse fixture-lines "\n"))
|
||||||
@@ -96,10 +94,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 is (file . line), 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))))))
|
||||||
|
|
||||||
@@ -227,30 +231,12 @@ after that is one more. Lines before the first directive get #f."
|
|||||||
;; Expressions that are their own statement
|
;; Expressions that are their own statement
|
||||||
(test-group "expressions"
|
(test-group "expressions"
|
||||||
(maps/tokens "sizeof" "(var svar" "sizeof")
|
(maps/tokens "sizeof" "(var svar" "sizeof")
|
||||||
(maps/tokens "cast" "(var cvar" "(int)mvar")
|
(maps/tokens "cast" "(var cvar" "(int)mvar"))
|
||||||
;; an `if' arm is a statement only where the `if' is one: a
|
|
||||||
;; directive between `?' and `:' does not compile
|
|
||||||
(maps "conditional argument" "123")
|
|
||||||
;; a bare 123 may be a digit run of the fixture's path, in every #line
|
|
||||||
(test-assert "holds no directive"
|
|
||||||
(let ((start (string-contains c-out "mvar < 123")))
|
|
||||||
(not (string-contains (substring c-out start (string-contains c-out ": 125" start))
|
|
||||||
"#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"))))))))
|
|
||||||
|
|||||||
132
tests/lsp.scm
132
tests/lsp.scm
@@ -1,132 +0,0 @@
|
|||||||
;;; The language server speaks LSP. ./sex-lsp is forked onto pipes,
|
|
||||||
;;; because a `process' port has no descriptor to wait on.
|
|
||||||
|
|
||||||
(import scheme
|
|
||||||
(scheme base)
|
|
||||||
(chicken file posix)
|
|
||||||
(chicken port)
|
|
||||||
(chicken process)
|
|
||||||
srfi-13
|
|
||||||
test)
|
|
||||||
|
|
||||||
(define (string->bytes text)
|
|
||||||
(let* ((n (string-length text))
|
|
||||||
(out (make-bytevector n)))
|
|
||||||
(do ((i 0 (+ i 1)))
|
|
||||||
((= i n) out)
|
|
||||||
(bytevector-u8-set! out i (char->integer (string-ref text i))))))
|
|
||||||
|
|
||||||
(define (copied-bytes buf count)
|
|
||||||
(let ((out (make-string count)))
|
|
||||||
(do ((i 0 (+ i 1)))
|
|
||||||
((= i count) out)
|
|
||||||
(string-set! out i (integer->char (bytevector-u8-ref buf i))))))
|
|
||||||
|
|
||||||
(define (fd-write-all fd text)
|
|
||||||
(unless (string=? text "")
|
|
||||||
(let ((n (file-write fd (string->bytes text))))
|
|
||||||
(when (< n (string-length text))
|
|
||||||
(fd-write-all fd (substring text n))))))
|
|
||||||
|
|
||||||
(define (fd-chunk fd n)
|
|
||||||
(let ((got (file-read fd n)))
|
|
||||||
(let ((buf (car got))
|
|
||||||
(count (cadr got)))
|
|
||||||
(and (positive? count) (copied-bytes buf count)))))
|
|
||||||
|
|
||||||
(define (fd-ready? fd)
|
|
||||||
(call-with-values
|
|
||||||
(lambda () (file-select (list fd) '() 4))
|
|
||||||
(lambda (readable writable) (pair? readable))))
|
|
||||||
|
|
||||||
(define (read-some fd n)
|
|
||||||
(let loop ((acc "") (left n))
|
|
||||||
(if (zero? left)
|
|
||||||
acc
|
|
||||||
(let ((chunk (fd-chunk fd left)))
|
|
||||||
(and chunk (loop (string-append acc chunk)
|
|
||||||
(- left (string-length chunk))))))))
|
|
||||||
|
|
||||||
(define (lsp-read fd)
|
|
||||||
(and (fd-ready? fd)
|
|
||||||
(let loop ((line "") (len #f))
|
|
||||||
(let ((b (fd-chunk fd 1)))
|
|
||||||
(and b
|
|
||||||
(if (char=? (string-ref b 0) #\newline)
|
|
||||||
(let ((line (if (and (positive? (string-length line))
|
|
||||||
(char=? (string-ref line
|
|
||||||
(- (string-length line) 1))
|
|
||||||
#\return))
|
|
||||||
(substring line 0 (- (string-length line) 1))
|
|
||||||
line)))
|
|
||||||
(cond
|
|
||||||
((string=? line "") (and len (read-some fd len)))
|
|
||||||
((and (>= (string-length line) 15)
|
|
||||||
(string-ci=? (substring line 0 15) "content-length:"))
|
|
||||||
(loop "" (string->number (string-trim (substring line 15)))))
|
|
||||||
(else (loop "" len))))
|
|
||||||
(loop (string-append line b) len)))))))
|
|
||||||
|
|
||||||
(define (lsp-send fd method id params-json)
|
|
||||||
(let ((body (string-append "{\"jsonrpc\":\"2.0\""
|
|
||||||
(if id (string-append ",\"id\":" (number->string id)) "")
|
|
||||||
",\"method\":\"" method "\",\"params\":" params-json "}")))
|
|
||||||
(fd-write-all fd (string-append "Content-Length: "
|
|
||||||
(number->string (string-length body))
|
|
||||||
"\r\n\r\n" body))))
|
|
||||||
|
|
||||||
(define (spawn-sex-lsp)
|
|
||||||
(call-with-values
|
|
||||||
create-pipe
|
|
||||||
(lambda (from-r from-w)
|
|
||||||
(call-with-values
|
|
||||||
create-pipe
|
|
||||||
(lambda (to-r to-w)
|
|
||||||
(let ((proc (process-fork)))
|
|
||||||
(if (not proc)
|
|
||||||
(begin
|
|
||||||
(duplicate-fileno to-r 0)
|
|
||||||
(duplicate-fileno from-w 1)
|
|
||||||
(process-execute "./sex-lsp" '())
|
|
||||||
(exit 127))
|
|
||||||
(begin
|
|
||||||
(file-close to-r)
|
|
||||||
(file-close from-w)
|
|
||||||
(values proc to-w from-r)))))))))
|
|
||||||
|
|
||||||
(when (file-exists? "./sex-lsp")
|
|
||||||
(test-group "sex-lsp"
|
|
||||||
(call-with-values
|
|
||||||
spawn-sex-lsp
|
|
||||||
(lambda (proc to-lsp from-lsp)
|
|
||||||
(lsp-send to-lsp "initialize" 1 "{\"capabilities\":{}}")
|
|
||||||
(let ((init (lsp-read from-lsp)))
|
|
||||||
(test-assert "initialize offers hover"
|
|
||||||
(and init (string-contains init "hoverProvider"))))
|
|
||||||
(lsp-send to-lsp "initialized" #f "{}")
|
|
||||||
(lsp-send to-lsp "textDocument/didOpen" #f
|
|
||||||
(string-append
|
|
||||||
"{\"textDocument\":{\"uri\":\"file:///tmp/lsp-bar.sex\",\"languageId\":\"sex\",\"version\":1,\"text\":"
|
|
||||||
(with-output-to-string
|
|
||||||
(lambda ()
|
|
||||||
(write "(pub fn bar ((a int)) void\n \"Add once.\"\n (return))\n(nope)\n")))
|
|
||||||
"}}"))
|
|
||||||
(let ((note (lsp-read from-lsp)))
|
|
||||||
(test-assert "the bad form is diagnosed"
|
|
||||||
(and note (string-contains note "unknown top level form"))))
|
|
||||||
(lsp-send to-lsp "textDocument/hover" 2
|
|
||||||
"{\"textDocument\":{\"uri\":\"file:///tmp/lsp-bar.sex\"},\"position\":{\"line\":0,\"character\":10}}")
|
|
||||||
(let ((hover (lsp-read from-lsp)))
|
|
||||||
(test-assert "hover is the prototype and the docstring"
|
|
||||||
(and hover
|
|
||||||
(string-contains hover "fn bar")
|
|
||||||
(string-contains hover "Add once."))))
|
|
||||||
(lsp-send to-lsp "sex/expand" 3
|
|
||||||
"{\"textDocument\":{\"uri\":\"file:///tmp/lsp-bar.sex\"},\"startLine\":1,\"endLine\":3}")
|
|
||||||
(let ((expanded (lsp-read from-lsp)))
|
|
||||||
(test-assert "sex/expand returns the function's C"
|
|
||||||
(and expanded (string-contains expanded "bar"))))
|
|
||||||
(lsp-send to-lsp "shutdown" 4 "null")
|
|
||||||
(lsp-read from-lsp)
|
|
||||||
(lsp-send to-lsp "exit" #f "null")
|
|
||||||
(process-wait proc)))))
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the
|
|
||||||
;;; start, from the directory sexc was started in.
|
|
||||||
|
|
||||||
(import (chicken file)
|
|
||||||
(chicken pathname)
|
|
||||||
(chicken process-context)
|
|
||||||
semen
|
|
||||||
sex-modules)
|
|
||||||
|
|
||||||
(define (write-module dir name)
|
|
||||||
(create-directory dir #t)
|
|
||||||
(with-output-to-file (make-pathname dir name "sex")
|
|
||||||
(lambda () (display "(pub fn found () int)"))))
|
|
||||||
|
|
||||||
(test-group "module path"
|
|
||||||
;; make-absolute-pathname took `src' for a directory under the root,
|
|
||||||
;; and an import searched /src/
|
|
||||||
(let ((start (current-directory))
|
|
||||||
(scratch (create-temporary-directory)))
|
|
||||||
(write-module (make-pathname scratch "src") "mp-relative")
|
|
||||||
(write-module (make-pathname scratch "lib") "mp-absolute")
|
|
||||||
(change-directory scratch)
|
|
||||||
(set-environment-variable! "SEX_MODULE_PATH"
|
|
||||||
(string-append "src:" (make-pathname scratch "lib")))
|
|
||||||
(load-persistent-module-paths)
|
|
||||||
(change-directory start)
|
|
||||||
|
|
||||||
(test "a relative entry is from the working directory"
|
|
||||||
'((pub fn found () int))
|
|
||||||
(semen-process '((import mp-relative))))
|
|
||||||
(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)))
|
|
||||||
28
tests/modules/Makefile
Normal file
28
tests/modules/Makefile
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
SEXC ?= ../../sexc
|
||||||
|
|
||||||
|
EXPECTED = hello, world\nhello, sex\n2 greetings
|
||||||
|
|
||||||
|
check:
|
||||||
|
@$(SEXC) greet.sex -c -o greet.o
|
||||||
|
@$(SEXC) greet-app.sex -o greet-app -- greet.o
|
||||||
|
@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 greet-app
|
||||||
|
|
||||||
|
.PHONY: check clean
|
||||||
@@ -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)
|
|
||||||
@@ -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))
|
|
||||||
@@ -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)))
|
|
||||||
@@ -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)))
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)))
|
|
||||||
@@ -7,9 +7,6 @@
|
|||||||
;;; as a prototype and `greet-count' as an extern. Both keep external
|
;;; as a prototype and `greet-count' as an extern. Both keep external
|
||||||
;;; linkage, so they refer to the one definition in greet.o rather than
|
;;; linkage, so they refer to the one definition in greet.o rather than
|
||||||
;;; to private copies.
|
;;; to private copies.
|
||||||
;;;
|
|
||||||
;;; Also check that import populates type-database, by means of
|
|
||||||
;;; describe-fields macro, which should work on imported type.
|
|
||||||
|
|
||||||
(include stdio.h)
|
(include stdio.h)
|
||||||
|
|
||||||
@@ -19,32 +16,4 @@
|
|||||||
(greet "world")
|
(greet "world")
|
||||||
(greet "sex")
|
(greet "sex")
|
||||||
(printf "%d greetings\n" greet-count)
|
(printf "%d greetings\n" greet-count)
|
||||||
(describe-fields greeting)
|
|
||||||
(printf "\n")
|
|
||||||
;; ...and through the imported typedef for it
|
|
||||||
(describe-fields greeting-t)
|
|
||||||
(printf "\n")
|
|
||||||
(var m (enum mood) grumpy)
|
|
||||||
(printf "mood %d\n" m)
|
|
||||||
|
|
||||||
;; the bare record name, then the method both ways round
|
|
||||||
(var v vec2 #(vec2 : 3 4))
|
|
||||||
(printf "vec2 %d %d\n" (.manhattan v) (vec2/manhattan (& v)))
|
|
||||||
|
|
||||||
;; only the handle crossed: (. t n) here is an incomplete type
|
|
||||||
(var t (* tally) (tally/make))
|
|
||||||
(.bump t)
|
|
||||||
(.bump t)
|
|
||||||
(printf "tally %d\n" (.count t))
|
|
||||||
(.drop t)
|
|
||||||
|
|
||||||
;; neither cell nor ledger is visible here, only declared
|
|
||||||
(var b board (make-board))
|
|
||||||
(printf "board %d\n" (board-total (& b)))
|
|
||||||
(printf "ledger %d\n" (ledger-total (greet-ledger)))
|
|
||||||
|
|
||||||
(var c colour (colour/rgb 1 2 3))
|
|
||||||
(match c
|
|
||||||
((rgb (r g b)) (printf "colour %d%d%d\n" r g b))
|
|
||||||
((none ()) (printf "colour none\n")))
|
|
||||||
(return 0))
|
(return 0))
|
||||||
|
|||||||
@@ -5,98 +5,14 @@
|
|||||||
;;; the compiled object still has to be handed to the C compiler. See
|
;;; the compiled object still has to be handed to the C compiler. See
|
||||||
;;; greet-app.sex.
|
;;; greet-app.sex.
|
||||||
|
|
||||||
(pub include stdio.h)
|
(include stdio.h)
|
||||||
(include stdlib.h)
|
|
||||||
|
|
||||||
(import ledger)
|
(pub var greet-count int 0)
|
||||||
|
|
||||||
(pub var greet-count ;; a comment in the header of a public form is
|
(pub fn greet ((name (* const char))) void
|
||||||
;; not part of it: what the importer is given has
|
|
||||||
;; to be `extern int greet-count', not a form
|
|
||||||
;; counted off by one
|
|
||||||
int 0)
|
|
||||||
|
|
||||||
(pub struct greeting
|
|
||||||
"A greeting to print."
|
|
||||||
((text (* const char)) (times int)))
|
|
||||||
|
|
||||||
(pub enum mood (cheerful grumpy))
|
|
||||||
|
|
||||||
(pub typedef greeting-t (struct greeting))
|
|
||||||
|
|
||||||
;;; Compile-time reflection across the module boundary: both the macro
|
|
||||||
;;; and the struct it asks about are exported, and the importing unit
|
|
||||||
;;; has to know the struct's fields to expand this.
|
|
||||||
(pub defmacro (describe-fields type)
|
|
||||||
`(do ,@(map-fields type
|
|
||||||
(lambda (name field-type)
|
|
||||||
`(printf "%s " ,(symbol->string name))))))
|
|
||||||
|
|
||||||
(var greetings ledger #(ledger : 0))
|
|
||||||
|
|
||||||
(pub fn greet ;; ...and here the prototype would lose its return type
|
|
||||||
((name (* const char))) void
|
|
||||||
"Print a greeting for NAME."
|
|
||||||
(++ greet-count)
|
(++ greet-count)
|
||||||
(ledger-add (& greetings) 1)
|
|
||||||
(printf "hello, %s\n" name))
|
(printf "hello, %s\n" name))
|
||||||
|
|
||||||
;;; Types the importer cannot see, crossing behind a pointer. `cell' is
|
|
||||||
;;; private and `ledger' was imported without `pub', and the importer
|
|
||||||
;;; is handed a declaration of each and nothing else.
|
|
||||||
(record cell ((v int)))
|
|
||||||
|
|
||||||
(var the-cell cell #(cell : 40))
|
|
||||||
|
|
||||||
(pub record board ((first (* cell)) (size int)))
|
|
||||||
|
|
||||||
(pub fn make-board () board
|
|
||||||
(return #(board : (& the-cell) 2)))
|
|
||||||
|
|
||||||
(pub fn board-total ((b (* const board))) int
|
|
||||||
(return (+ (. b first v) (. b size))))
|
|
||||||
|
|
||||||
(pub fn greet-ledger () (* ledger)
|
|
||||||
(return (& greetings)))
|
|
||||||
|
|
||||||
(pub fn ledger-total ((l (* const ledger))) int
|
|
||||||
(return (. l total)))
|
|
||||||
|
|
||||||
;;; A record and an ops block crossing the boundary. The record has to
|
|
||||||
;;; arrive as the struct *and* its typedef, or the bare name does not
|
|
||||||
;;; work there; the ops block has to arrive as a block rather than as
|
|
||||||
;;; loose prototypes, or the importer learns that vec2ːmanhattan exists
|
|
||||||
;;; without learning that vec2 has a `manhattan' -- and (. v manhattan)
|
|
||||||
;;; needs the second thing.
|
|
||||||
(pub record vec2 ((x int) (y int)))
|
|
||||||
|
|
||||||
(ops vec2
|
|
||||||
(pub fn manhattan ((self (* const vec2))) int
|
|
||||||
(return (+ (. self x) (. self y)))))
|
|
||||||
|
|
||||||
;;; An opaque record: the handle is public and the fields are not, so
|
|
||||||
;;; the importer holds a (* tally) and reaches it only through methods.
|
|
||||||
(pub record tally)
|
|
||||||
|
|
||||||
(record tally ((n int)))
|
|
||||||
|
|
||||||
(ops tally
|
|
||||||
(pub fn make () (* tally)
|
|
||||||
(var t (* tally) (malloc (sizeof tally)))
|
|
||||||
(= (. t n) 0)
|
|
||||||
(return t))
|
|
||||||
(pub fn bump ((self (* tally))) void
|
|
||||||
(++ (. self n)))
|
|
||||||
(pub fn count ((self (* const tally))) int
|
|
||||||
(return (. self n)))
|
|
||||||
(pub fn drop ((self (* tally))) void
|
|
||||||
(free self)))
|
|
||||||
|
|
||||||
;;; A pub sum is pasted whole, so the importer builds its own copy of
|
|
||||||
;;; the declarations; a constructor is written in place where it is
|
|
||||||
;;; called, so there is no function for two units to both define.
|
|
||||||
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
|
|
||||||
|
|
||||||
;;; 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"))
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
;;; A module greet.sex imports without `pub'. greet-app.sex never
|
|
||||||
;;; imports it, yet holds a (* ledger) that greet hands out: what greet
|
|
||||||
;;; exports has to declare the type for it.
|
|
||||||
|
|
||||||
(pub record ledger ((total int)))
|
|
||||||
|
|
||||||
(pub fn ledger-add ((l (* ledger)) (n int)) void
|
|
||||||
(+= (. l total) n))
|
|
||||||
@@ -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))
|
|
||||||
@@ -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))
|
|
||||||
@@ -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))))
|
|
||||||
@@ -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))
|
|
||||||
@@ -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)))
|
|
||||||
@@ -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))
|
|
||||||
177
tests/query.scm
177
tests/query.scm
@@ -1,177 +0,0 @@
|
|||||||
;;; Symbol table, diagnostics that survive a bad form, and C sliced
|
|
||||||
;;; back to the Sex lines it came from.
|
|
||||||
|
|
||||||
(import scheme
|
|
||||||
(scheme base) ; open-input-string
|
|
||||||
(chicken file)
|
|
||||||
(chicken io)
|
|
||||||
(chicken pathname)
|
|
||||||
(chicken port)
|
|
||||||
(chicken process)
|
|
||||||
(chicken string)
|
|
||||||
srfi-1
|
|
||||||
srfi-13
|
|
||||||
test
|
|
||||||
sex-query)
|
|
||||||
|
|
||||||
(define (quietly thunk)
|
|
||||||
(with-error-output-to-string (lambda () (thunk))))
|
|
||||||
|
|
||||||
(define (analyze source)
|
|
||||||
(analyze-text source "query.sex"))
|
|
||||||
|
|
||||||
(define (lookup source name line)
|
|
||||||
(analysis-lookup (analyze source) name line))
|
|
||||||
|
|
||||||
(define (has-char? sym ch)
|
|
||||||
(let ((s (symbol->string (sym-name sym))))
|
|
||||||
(let loop ((i 0))
|
|
||||||
(and (< i (string-length s))
|
|
||||||
(or (char=? (string-ref s i) ch)
|
|
||||||
(loop (+ i 1)))))))
|
|
||||||
|
|
||||||
(test-group "symbols"
|
|
||||||
(let ((a (analyze "(pub fn bar ((a int)) void\n \"Add once.\"\n (return))\n")))
|
|
||||||
(test-assert "a readable unit" (analysis-read? a))
|
|
||||||
(let ((bar (analysis-lookup a 'bar 1)))
|
|
||||||
(test 'fn (sym-kind bar))
|
|
||||||
(test 1 (sym-line bar))
|
|
||||||
(test 3 (sym-end bar))
|
|
||||||
(test '(fn bar ((a int)) void) (sym-signature bar))
|
|
||||||
(test "Add once." (sym-doc bar))
|
|
||||||
(test-assert "the prototype and the docstring"
|
|
||||||
(and (string-contains (symbol-hover bar) "(fn bar ((a int)) void)")
|
|
||||||
(string-contains (symbol-hover bar) "Add once."))))
|
|
||||||
(let ((param (analysis-lookup a 'a 2)))
|
|
||||||
(test 'var (sym-kind param))
|
|
||||||
(test 'int (sym-signature param))
|
|
||||||
(test 1 (sym-scope-start param))))
|
|
||||||
(test-assert "the prelude's names are not the unit's"
|
|
||||||
(not (analysis-lookup (analyze "(fn f () void (return))") 'u8 1)))
|
|
||||||
(let ((a (analyze "(struct point \"A point.\" ((x int) (y int)))\n(typedef point-t (struct point))\n(enum mood (cheerful grumpy))\n")))
|
|
||||||
(test 'struct (sym-kind (analysis-lookup a 'point 1)))
|
|
||||||
(test "A point." (sym-doc (analysis-lookup a 'point 1)))
|
|
||||||
(test 'typedef (sym-kind (analysis-lookup a 'point-t 2)))
|
|
||||||
(test 'const (sym-kind (analysis-lookup a 'cheerful 3)))
|
|
||||||
(test '(enum mood) (sym-signature (analysis-lookup a 'grumpy 3))))
|
|
||||||
(test-assert "a spec method is not a name"
|
|
||||||
(not (analysis-lookup
|
|
||||||
(analyze "(spec (show T)\n (fn show ((self (* const T))) void))\n")
|
|
||||||
'show 1)))
|
|
||||||
(test-assert "a closure's minted helper is not a name"
|
|
||||||
(not (any (lambda (s) (has-char? s #\ƛ))
|
|
||||||
(analysis-symbols
|
|
||||||
(analyze "(fn make-adder ((n int)) (closure ((int)) int)\n (return (closure ((b int)) int (n)\n (return (+ n b)))))\n"))))))
|
|
||||||
|
|
||||||
(test-group "lookup"
|
|
||||||
(let ((src "(fn outer ((a int)) int\n (return a)\n (do\n (var a char 1)\n (return a)))\n"))
|
|
||||||
(test 'int (sym-signature (lookup src 'a 2)))
|
|
||||||
(test 'char (sym-signature (lookup src 'a 5)))
|
|
||||||
(test 'fn (sym-kind (lookup src 'outer 5)))))
|
|
||||||
|
|
||||||
(define *recovered* #f)
|
|
||||||
|
|
||||||
(test-group "diagnostics"
|
|
||||||
(let ((err (with-error-output-to-string
|
|
||||||
(lambda ()
|
|
||||||
(set! *recovered* (analyze "(fn good () int\n (return 1))\n(nope)\n(fn also () int\n (return 2))\n"))))))
|
|
||||||
(test "" err)
|
|
||||||
(test-assert "the good function is still there"
|
|
||||||
(analysis-lookup *recovered* 'good 1))
|
|
||||||
(test-assert "and so is the one after the bad form"
|
|
||||||
(analysis-lookup *recovered* 'also 4))
|
|
||||||
(test-assert "the bad form is an error"
|
|
||||||
(any (lambda (d)
|
|
||||||
(and (eq? (diag-severity d) 'error)
|
|
||||||
(string-contains (diag-message d) "unknown top level form")))
|
|
||||||
(analysis-diagnostics *recovered*))))
|
|
||||||
(let ((a (analyze "(fn f () void (var t (* struct tm) 0) (= (. t a b) 1))")))
|
|
||||||
(test-assert "a warning is a diagnostic, and the function remains"
|
|
||||||
(and (analysis-lookup a 'f 1)
|
|
||||||
(any (lambda (d)
|
|
||||||
(and (eq? (diag-severity d) 'warning)
|
|
||||||
(string-contains (diag-message d) "cannot type this")))
|
|
||||||
(analysis-diagnostics a))))))
|
|
||||||
|
|
||||||
(test-group "expand"
|
|
||||||
(let ((a (analyze "(fn alpha () int\n (return 11111))\n(fn beta () int\n (return 22222))\n")))
|
|
||||||
(let ((alpha (analysis-expand a 1 2)))
|
|
||||||
(test-assert "the form's C" (string-contains alpha "11111"))
|
|
||||||
(test-assert "not the other form" (not (string-contains alpha "22222"))))
|
|
||||||
(let ((whole (analysis-expand a 1 #f)))
|
|
||||||
(test-assert "the whole buffer keeps both"
|
|
||||||
(and (string-contains whole "11111")
|
|
||||||
(string-contains whole "22222")
|
|
||||||
(string-contains whole "#include <stddef.h>"))))))
|
|
||||||
|
|
||||||
(test-group "includes and C names"
|
|
||||||
(let ((a (analyze "(include stdio.h)\n(include \"local.h\")\n")))
|
|
||||||
(test-assert "a header named by a symbol" (member 'stdio.h (analysis-includes a)))
|
|
||||||
(test-assert "and one named by a string" (member "local.h" (analysis-includes a))))
|
|
||||||
(test "SDL_Init" (sex-name->c "SDL-Init"))
|
|
||||||
(test "foo->bar_baz" (sex-name->c "foo->bar-baz"))
|
|
||||||
(test 'SDL-Init (c-name->sex "SDL_Init"))
|
|
||||||
(let ((probe (probe-text '(stdio.h) "SDL-In")))
|
|
||||||
(test-assert "prelude headers" (string-contains probe "#include <stddef.h>"))
|
|
||||||
(test-assert "the unit's header" (string-contains probe "#include <stdio.h>"))
|
|
||||||
(test-assert "the prefix in C spelling" (string-contains probe "SDL_In"))))
|
|
||||||
|
|
||||||
(test-group "import"
|
|
||||||
(let* ((dir (create-temporary-directory))
|
|
||||||
(greet (make-pathname dir "greet.sex"))
|
|
||||||
(app (make-pathname dir "app.sex")))
|
|
||||||
(with-output-to-file greet
|
|
||||||
(lambda ()
|
|
||||||
(display "(pub fn greet ((name int)) int\n \"Hi.\"\n (return name))\n")))
|
|
||||||
(with-output-to-file app
|
|
||||||
(lambda ()
|
|
||||||
(display "(import greet)\n(fn main () int (return (greet 1)))\n")))
|
|
||||||
(let* ((a (analyze-file app))
|
|
||||||
(g (analysis-lookup a 'greet 2)))
|
|
||||||
(test-assert "the import was read" (analysis-read? a))
|
|
||||||
(test 'fn (sym-kind g))
|
|
||||||
(test "Hi." (sym-doc g))
|
|
||||||
(test "greet.sex" (pathname-strip-directory (sym-file g)))
|
|
||||||
(test-assert "document symbols stay in this file"
|
|
||||||
(and (any (lambda (s) (eq? (sym-name s) 'main))
|
|
||||||
(analysis-document-symbols a))
|
|
||||||
(not (any (lambda (s) (eq? (sym-name s) 'greet))
|
|
||||||
(analysis-document-symbols a))))))
|
|
||||||
(delete-directory dir #t)))
|
|
||||||
|
|
||||||
(define (run-sexc . args)
|
|
||||||
(let ((proc (process "./sexc" args)))
|
|
||||||
(let ((out (read-string #f (process-output-port proc))))
|
|
||||||
(close-input-port (process-output-port proc))
|
|
||||||
(call-with-values (lambda () (process-wait proc))
|
|
||||||
(lambda (pid normal? status) status))
|
|
||||||
(cons (process-exit-status proc) out))))
|
|
||||||
|
|
||||||
(define (read-output text)
|
|
||||||
(read (open-input-string text)))
|
|
||||||
|
|
||||||
(test-group "sexc query flags"
|
|
||||||
(let* ((dir (create-temporary-directory))
|
|
||||||
(file (make-pathname dir "q.sex")))
|
|
||||||
(with-output-to-file file
|
|
||||||
(lambda ()
|
|
||||||
(display "(fn alpha () int\n (return 11111))\n(nope)\n")))
|
|
||||||
(let ((checked (run-sexc "--check" file)))
|
|
||||||
(test 0 (car checked))
|
|
||||||
(test-assert "an error sexp"
|
|
||||||
(let ((form (read-output (cdr checked))))
|
|
||||||
(and (eq? (car form) 'diagnostics)
|
|
||||||
(any (lambda (d) (eq? (car d) 'error)) (cdr form))))))
|
|
||||||
(let ((symbols (run-sexc "--symbols" file)))
|
|
||||||
(test 0 (car symbols))
|
|
||||||
(test-assert "alpha survives nope"
|
|
||||||
(let ((form (read-output (cdr symbols))))
|
|
||||||
(and (eq? (car form) 'symbols)
|
|
||||||
(any (lambda (s) (eq? (cadr s) 'alpha)) (cdr form))))))
|
|
||||||
(let ((expanded (run-sexc "--expand-lines=1:2" file)))
|
|
||||||
(test 0 (car expanded))
|
|
||||||
(test-assert "the slice" (string-contains (cdr expanded) "11111")))
|
|
||||||
(let ((broken (make-pathname dir "broken.sex")))
|
|
||||||
(with-output-to-file broken (lambda () (display "(fn")))
|
|
||||||
(test 70 (car (run-sexc "--check" broken))))
|
|
||||||
(delete-directory dir #t)))
|
|
||||||
3
tests/reader.module.scm
Normal file
3
tests/reader.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module reader
|
||||||
|
*
|
||||||
|
"../reader.scm")
|
||||||
177
tests/reader.scm
177
tests/reader.scm
@@ -1,28 +1,6 @@
|
|||||||
(import (chicken condition)
|
(import (chicken port)
|
||||||
(chicken irregex)
|
|
||||||
(chicken port)
|
|
||||||
reader)
|
reader)
|
||||||
|
|
||||||
(define-syntax feature-test
|
|
||||||
(syntax-rules ()
|
|
||||||
((feature-test result features string)
|
|
||||||
(test result
|
|
||||||
(parameterize ((current-features 'features))
|
|
||||||
(with-input-from-string string
|
|
||||||
(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)
|
||||||
@@ -52,106 +30,6 @@
|
|||||||
;; a `.'-prefixed symbol is an ordinary symbol, not dot-access
|
;; a `.'-prefixed symbol is an ordinary symbol, not dot-access
|
||||||
(reader-test '((.field obj)) "(.field obj)")
|
(reader-test '((.field obj)) "(.field obj)")
|
||||||
|
|
||||||
;; a leading `-' on a name is negation, the way it is on a number:
|
|
||||||
;; no name is spelled with one, and -INFINITY otherwise mangled into
|
|
||||||
;; _INFINITY. The operators that start with one are left alone
|
|
||||||
(reader-test '((- INFINITY)) "-INFINITY")
|
|
||||||
(reader-test '((var best double (- INFINITY))) "(var best double -INFINITY)")
|
|
||||||
(reader-test '((- _x)) "-_x")
|
|
||||||
(reader-test '(-1 -1.5) "-1 -1.5")
|
|
||||||
(reader-test '(- -> ->> -- -=) "- -> ->> -- -=")
|
|
||||||
;; ...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
|
|
||||||
;; Scheme does; either is an ordinary integer from here on
|
|
||||||
(reader-test '(224 224 5 5 -16) "0xE0 0Xe0 0b101 0B101 -0x10")
|
|
||||||
(reader-test '(128 128 5 8 -16) "#x80 #X80 #b101 #o10 #x-10")
|
|
||||||
;; ...and only a number: a prefix with nothing after it is a name
|
|
||||||
(reader-test '(0x 0xg) "0x 0xg")
|
|
||||||
|
|
||||||
;; `_' 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")
|
||||||
@@ -160,57 +38,4 @@
|
|||||||
(reader-test '((a b) (comment " t")) "(a b) ; t")
|
(reader-test '((a b) (comment " t")) "(a b) ; t")
|
||||||
;; a `;' inside a string is not a comment
|
;; a `;' inside a string is not a comment
|
||||||
(reader-test '("a;b") "\"a;b\"")
|
(reader-test '("a;b") "\"a;b\"")
|
||||||
|
|
||||||
;; #+ / #- feature expressions. What does not apply is read and
|
|
||||||
;; dropped, so it never reaches the compiler at all
|
|
||||||
(feature-test '((a)) (linux) "#+linux (a)")
|
|
||||||
(feature-test '() (macosx) "#+linux (a)")
|
|
||||||
(feature-test '() (linux) "#-linux (a)")
|
|
||||||
(feature-test '((a)) (macosx) "#-linux (a)")
|
|
||||||
;; the guarded datum can be anything, not only a list
|
|
||||||
(feature-test '(42) (x) "#+x 42")
|
|
||||||
(feature-test '("s") (x) "#+x \"s\"")
|
|
||||||
|
|
||||||
;; and / or / not
|
|
||||||
(feature-test '((a)) (unix linux) "#+(and unix linux) (a)")
|
|
||||||
(feature-test '() (unix) "#+(and unix linux) (a)")
|
|
||||||
(feature-test '((a)) (unix) "#+(or linux unix) (a)")
|
|
||||||
(feature-test '() (bsd) "#+(or linux unix) (a)")
|
|
||||||
(feature-test '((a)) (unix) "#+(and unix (not macosx)) (a)")
|
|
||||||
(feature-test '() (unix macosx) "#+(and unix (not macosx)) (a)")
|
|
||||||
;; (and) is true and (or) is false, as they are in CL
|
|
||||||
(feature-test '((a)) () "#+(and) (a)")
|
|
||||||
(feature-test '() () "#+(or) (a)")
|
|
||||||
|
|
||||||
;; a guard inside a form, including as the last element -- dropping
|
|
||||||
;; continues with the next token, so the closing paren still arrives
|
|
||||||
(feature-test '((f 1 3)) (a) "(f #+a 1 #-a 2 3)")
|
|
||||||
(feature-test '((f 2 3)) (b) "(f #+a 1 #-a 2 3)")
|
|
||||||
(feature-test '((f 1)) (a) "(f #+a 1 #+b 2)")
|
|
||||||
(feature-test '((f)) (b) "(f #+a 1)")
|
|
||||||
;; ...and as the last form in the file
|
|
||||||
(feature-test '((a)) (x) "(a) #+y (b)")
|
|
||||||
|
|
||||||
;; guards nest
|
|
||||||
(feature-test '((a)) (x y) "#+x #+y (a)")
|
|
||||||
(feature-test '((b)) (x) "#+x #+y (a) (b)")
|
|
||||||
;; ...and the inner one may leave nothing behind: the end of the
|
|
||||||
;; file, or the paren closing the list, is what the outer one then
|
|
||||||
;; produces, and neither is an error
|
|
||||||
(feature-test '() (x) "#+x #+y (a)")
|
|
||||||
(feature-test '((f)) (x) "(f #+x #+y 1)")
|
|
||||||
(feature-test '((f 2)) (x) "(f #+x #+y 1 2)")
|
|
||||||
(feature-test '((a)) (x) "(a) #+x #+y (b)")
|
|
||||||
|
|
||||||
;; a comment between a guard and the form it guards describes the
|
|
||||||
;; guard. Taking it for the guarded datum would leave the form itself
|
|
||||||
;; unconditional
|
|
||||||
(feature-test '((a)) (x) "#+x ;; why\n (a)")
|
|
||||||
(feature-test '() (y) "#+x ;; why\n (a)")
|
|
||||||
(feature-test '((b)) (y) "#+x ;; why\n (a) (b)")
|
|
||||||
;; a comment after the guarded form is an ordinary form, and stays
|
|
||||||
(feature-test '((comment "; tail")) (y) "#+x (a) ;; tail")
|
|
||||||
|
|
||||||
;; a feature the program was not given is simply absent
|
|
||||||
(feature-test '() () "#+anything (a)")
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
(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 "args.scm")
|
||||||
(include-relative "module-path.scm")
|
(include "types.scm")
|
||||||
(include-relative "types.scm")
|
|
||||||
(include-relative "infer.scm")
|
|
||||||
(include-relative "query.scm")
|
|
||||||
(include-relative "lsp.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
2
tests/semen.module.scm
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
(module semen *
|
||||||
|
"../semen.scm")
|
||||||
114
tests/semen.scm
114
tests/semen.scm
@@ -1,8 +1,30 @@
|
|||||||
(import semen
|
(import srfi-69
|
||||||
types)
|
semen)
|
||||||
|
|
||||||
|
(define print-str-fn
|
||||||
|
'(fn void print-str ((string s))
|
||||||
|
(printf "%s" s)))
|
||||||
|
|
||||||
|
(define sum-fn
|
||||||
|
'(pub fn float sum ((int a) (int b))
|
||||||
|
(return (cast float (+ a b)))))
|
||||||
|
|
||||||
(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 '((string s)) (sex-fn-arglist print-str-fn))
|
||||||
|
(test '(fn void print-str ((string s))) (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 '((int a) (int b)) (sex-fn-arglist sum-fn))
|
||||||
|
(test '(pub fn float sum ((int a) (int b))) (sex-fn-prototype sum-fn))
|
||||||
|
(test '((return (cast float (+ a b)))) (sex-fn-body sum-fn))
|
||||||
|
|
||||||
(let ((sex-code
|
(let ((sex-code
|
||||||
'((defmacro (sum-var name a b c)
|
'((defmacro (sum-var name a b c)
|
||||||
@@ -12,82 +34,24 @@
|
|||||||
|
|
||||||
(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))
|
||||||
|
|
||||||
(fn foo ((a int) (b int)) void
|
(fn void foo ((int a) (int b))
|
||||||
(return (+ a (x10 b)))))))
|
(return (+ a (x10 b)))))))
|
||||||
|
|
||||||
(test '((fn foo ((a int) (b int)) void
|
(test '((fn void foo ((int a) (int b))
|
||||||
(return (+ a (* 10 b)))))
|
(return (+ a (* 10 b)))))
|
||||||
(semen-process sex-code-macro)))
|
(semen-process sex-code-macro))))
|
||||||
|
|
||||||
;;; Docstrings are lifted out as comment forms sitting before the
|
|
||||||
;;; declaration. A string later in a body is left alone.
|
|
||||||
|
|
||||||
(test '((comment "Greet NAME.")
|
|
||||||
(fn greet ((name (* char))) void
|
|
||||||
(printf "Hello %s!\n" name)))
|
|
||||||
(semen-process
|
|
||||||
'((fn greet ((name (* char))) void
|
|
||||||
"Greet NAME."
|
|
||||||
(printf "Hello %s!\n" name)))))
|
|
||||||
|
|
||||||
(test '((comment "Public entry.")
|
|
||||||
(pub fn main () int
|
|
||||||
(return 0)))
|
|
||||||
(semen-process
|
|
||||||
'((pub fn main () int
|
|
||||||
"Public entry."
|
|
||||||
(return 0)))))
|
|
||||||
|
|
||||||
;; A prototype whose only "body" is a docstring stays a prototype
|
|
||||||
(test '((comment "Forward.")
|
|
||||||
(fn helper ((a int)) int))
|
|
||||||
(semen-process
|
|
||||||
'((fn helper ((a int)) int
|
|
||||||
"Forward."))))
|
|
||||||
|
|
||||||
(test '((fn f () void (g) "not a docstring"))
|
|
||||||
(semen-process
|
|
||||||
'((fn f () void (g) "not a docstring"))))
|
|
||||||
|
|
||||||
;; `;' comments before the string are skipped when looking for it,
|
|
||||||
;; and stay in the body
|
|
||||||
(test '((comment "Kept.")
|
|
||||||
(fn f () void (comment " note") (g)))
|
|
||||||
(semen-process
|
|
||||||
'((fn f () void (comment " note") "Kept." (g)))))
|
|
||||||
|
|
||||||
(test '((comment "A 2D point.")
|
|
||||||
(struct t-doc-pt ((x int) (y int))))
|
|
||||||
(semen-process
|
|
||||||
'((struct t-doc-pt "A 2D point." ((x int) (y int))))))
|
|
||||||
|
|
||||||
(test '((x int) (y int))
|
|
||||||
(get-fields 't-doc-pt))
|
|
||||||
|
|
||||||
(test '((comment "RGB.")
|
|
||||||
(enum t-doc-color (red green blue)))
|
|
||||||
(semen-process
|
|
||||||
'((enum t-doc-color "RGB." (red green blue)))))
|
|
||||||
|
|
||||||
(test '((comment "Either.")
|
|
||||||
(union t-doc-val ((i int) (f float))))
|
|
||||||
(semen-process
|
|
||||||
'((union t-doc-val "Either." ((i int) (f float))))))
|
|
||||||
|
|
||||||
;; Includes
|
|
||||||
(test '((include stdio.h))
|
|
||||||
(semen-process
|
|
||||||
'((include stdio.h))))
|
|
||||||
(test '((include stdio.h)
|
|
||||||
(include stdlib.h))
|
|
||||||
(semen-process
|
|
||||||
'((include stdio.h
|
|
||||||
stdlib.h))))
|
|
||||||
(test '()
|
|
||||||
(semen-process
|
|
||||||
'((include))))
|
|
||||||
)
|
|
||||||
|
|||||||
3
tests/sex-macros.module.scm
Normal file
3
tests/sex-macros.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module sex-macros
|
||||||
|
*
|
||||||
|
"../sex-macros.scm")
|
||||||
3
tests/sex-modules.module.scm
Normal file
3
tests/sex-modules.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module sex-modules
|
||||||
|
*
|
||||||
|
"../sex-modules.scm")
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
(compilation "-- -std=c11 -pedantic-errors")
|
|
||||||
(input)
|
|
||||||
(output "c11: 42 43 6 4 6 12 5 0 -9223372036854775808"
|
|
||||||
"trigraphs: what??! ??= ???( ??/")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; C11 is the floor, and this is the program that holds it there: the
|
|
||||||
;;; C every feature emits has to build under it with no extension, so
|
|
||||||
;;; one that reaches past it -- a GNU statement expression, a C23
|
|
||||||
;;; keyword -- fails here rather than on a user's compiler.
|
|
||||||
;;;
|
|
||||||
;;; A lifted lambda is the one that leans on C11 itself, through
|
|
||||||
;;; `_Static_assert'; the record, the method and the match are here for
|
|
||||||
;;; what they emit, and the globals for initializers that have to be
|
|
||||||
;;; constants.
|
|
||||||
;;;
|
|
||||||
;;; 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)
|
|
||||||
|
|
||||||
(record point ((x int) (y int)))
|
|
||||||
|
|
||||||
(ops point
|
|
||||||
(fn area ((self (* const point))) int
|
|
||||||
(return (* (. self x) (. self y)))))
|
|
||||||
|
|
||||||
(sum shape ((square ((side int))) (dot ())))
|
|
||||||
|
|
||||||
(var corner _ #(point : 2 3))
|
|
||||||
(var 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
|
|
||||||
(var n int 0)
|
|
||||||
(match s
|
|
||||||
((square (side)) (= n (* 4 side)))
|
|
||||||
((dot ()) (= n 0)))
|
|
||||||
(return n))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var p point #(point : 6 7))
|
|
||||||
(var add-k (fn ((int)) int)
|
|
||||||
(lambda ((v int)) int (return (+ v 1))))
|
|
||||||
(printf "c11: %d %d %d %d %d %d %d %d %lld\n"
|
|
||||||
(.area p) (add-k (.area p)) (+ (sides (shape/square 1)) (sides (shape/dot)) 2)
|
|
||||||
(sides unit) (.area corner) (.area [pair 1]) [primes 2] (. origin y) least)
|
|
||||||
(printf "trigraphs: %s\n" "what??! ??= ???( ??/")
|
|
||||||
(return 0))
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "plain 1 2"
|
|
||||||
"literal 3 4"
|
|
||||||
"designated zoe 7"
|
|
||||||
"through a pointer 9"
|
|
||||||
"array 10 20 30"
|
|
||||||
"argument 6"
|
|
||||||
"mixed 1 5"
|
|
||||||
"read through a pointer 1 5"
|
|
||||||
"by index 0 2 0 1")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; `:' inside #(...) ends a type and makes the rest a C99 compound
|
|
||||||
;;; literal. Without one, #(...) is the brace initializer it always was.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
(struct named ((first-name (* const char)) (n int)))
|
|
||||||
|
|
||||||
(fn sum ((p (struct point))) int
|
|
||||||
(return (+ (. p x) (. p y))))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
;; unchanged: a bare initializer has no type of its own
|
|
||||||
(var p (struct point) #(1 2))
|
|
||||||
(printf "plain %d %d\n" (. p x) (. p y))
|
|
||||||
|
|
||||||
(var q (struct point) #(struct point : 3 4))
|
|
||||||
(printf "literal %d %d\n" (. q x) (. q y))
|
|
||||||
|
|
||||||
;; designated, out of declaration order, and kebab-cased
|
|
||||||
(var r (struct named) #(struct named : .n 7 .first-name "zoe"))
|
|
||||||
(printf "designated %s %d\n" (. r first-name) (. r n))
|
|
||||||
|
|
||||||
;; a compound literal is an lvalue, so its address can be taken --
|
|
||||||
;; until the end of the enclosing block, and no longer
|
|
||||||
(var pp (* struct point) (& #(struct point : 9 9)))
|
|
||||||
(printf "through a pointer %d\n" (. pp x))
|
|
||||||
|
|
||||||
;; an array literal decays the way an array does
|
|
||||||
(var a (* int) #([int 3] : 10 20 30))
|
|
||||||
(printf "array %d %d %d\n" [a 0] [a 1] [a 2])
|
|
||||||
|
|
||||||
(printf "argument %d\n" (sum #(struct point : 2 4)))
|
|
||||||
|
|
||||||
;; positional and designated may be mixed, as in C
|
|
||||||
(var m (struct point) #(struct point : 1 .y 5))
|
|
||||||
(printf "mixed %d %d\n" (. m x) (. m y))
|
|
||||||
|
|
||||||
;; what a literal holds is walked like any expression, so a path in
|
|
||||||
;; it reads through a pointer as it does outside one
|
|
||||||
(var pm (* (struct point)) (& m))
|
|
||||||
(var c (struct point) #(struct point : (. pm x) (. pm y)))
|
|
||||||
(printf "read through a pointer %d %d\n" (. c x) (. c y))
|
|
||||||
|
|
||||||
;; 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))
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "-(2 + 3)"
|
|
||||||
"-5")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A recursive sum and an inherent method on it: every layer of
|
|
||||||
;;; encapsulation in one program, built at once.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(sum expr
|
|
||||||
((lit ((v float)))
|
|
||||||
(neg ((e (* const expr))))
|
|
||||||
(add ((l (* const expr)) (r (* const expr))))))
|
|
||||||
|
|
||||||
(ops expr
|
|
||||||
(pub fn eval ((self (* const expr))) float
|
|
||||||
;; v, e, l and r are copies of the fields, not references to them
|
|
||||||
(match (* self)
|
|
||||||
((lit (v)) (return v))
|
|
||||||
((neg (e)) (return (- (.eval e))))
|
|
||||||
((add (l r)) (return (+ (.eval l) (.eval r))))))
|
|
||||||
(pub fn show ((self (* const expr))) void
|
|
||||||
(match (* self)
|
|
||||||
((lit (v)) (printf "%g" v))
|
|
||||||
((neg (e)) (printf "-") (.show e))
|
|
||||||
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")"))))
|
|
||||||
(pub fn show-line ((self (* const expr))) void
|
|
||||||
(.show self)
|
|
||||||
(printf "\n")))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var two expr (expr/lit 2.0))
|
|
||||||
(var three expr (expr/lit 3.0))
|
|
||||||
(var both expr (expr/add (& two) (& three)))
|
|
||||||
(var e expr (expr/neg (& both)))
|
|
||||||
|
|
||||||
(.show-line e) ; -(2 + 3)
|
|
||||||
(printf "%g\n" (.eval e)) ; -5
|
|
||||||
(return 0))
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
(compilation "-f alpha -f beta,gamma --features=delta --no-platform-features")
|
|
||||||
(input)
|
|
||||||
(output "alpha" "beta" "gamma" "delta" "elsewhere")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; The flags naming the features, in every spelling sexc takes. This
|
|
||||||
;;; is not pedantry about the command line: sextest reads the program
|
|
||||||
;;; itself and prints the surviving forms to sexc, so a spelling it
|
|
||||||
;;; does not recognise leaves the guards below resolved against the
|
|
||||||
;;; wrong set -- quietly, since the test then checks the output of a
|
|
||||||
;;; program it did not mean to compile.
|
|
||||||
;;;
|
|
||||||
;;; --no-platform-features is what makes `#-unix' true wherever this is
|
|
||||||
;;; compiled, and it has to be honoured on both sides for that to hold.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
#+alpha (puts "alpha")
|
|
||||||
#+beta (puts "beta")
|
|
||||||
#+gamma (puts "gamma")
|
|
||||||
#+delta (puts "delta")
|
|
||||||
#-unix (puts "elsewhere")
|
|
||||||
#+unix (puts "here")
|
|
||||||
(return 0))
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
(compilation "--features=test-on")
|
|
||||||
(input)
|
|
||||||
(output "selected" "on" "and-not")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; #+ and #- pick what the compiler gets to see. `test-on' is handed
|
|
||||||
;;; to sexc by the (compilation ...) form above, so this program reads
|
|
||||||
;;; the same way on every platform.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
#+test-on (define GREETING "on")
|
|
||||||
#-test-on (define GREETING "off")
|
|
||||||
|
|
||||||
#-test-on (pub fn main () int (puts "the whole function is dropped") (return 1))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
;; ...and inside a form, not only at toplevel
|
|
||||||
(puts #+test-on "selected" #-test-on "rejected")
|
|
||||||
(puts GREETING)
|
|
||||||
#+(and test-on (not test-off)) (puts "and-not")
|
|
||||||
#-test-on (puts "never printed")
|
|
||||||
(return 0))
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "15"
|
|
||||||
"42 0.25"
|
|
||||||
"(5, 7)"
|
|
||||||
"(1, 2)"
|
|
||||||
"3"
|
|
||||||
"(5, 7)"
|
|
||||||
"0 1 4 9 "
|
|
||||||
"4"
|
|
||||||
"42"
|
|
||||||
"<fn of 0: 10>"
|
|
||||||
"32"
|
|
||||||
"2 1"
|
|
||||||
"Hello from Sex!")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; Both halves of inference, from the two sides that read the same
|
|
||||||
;;; answers: `_' in a type means "work it out", and `type-of' hands a
|
|
||||||
;;; macro the type of an expression.
|
|
||||||
;;;
|
|
||||||
;;; This was written as a draft before either existed, to be read
|
|
||||||
;;; before it was built. It is registered now.
|
|
||||||
;;;
|
|
||||||
;;; Two features, one mechanism:
|
|
||||||
;;;
|
|
||||||
;;; `_' in a type means "work it out", and
|
|
||||||
;;; `type-of' hands a macro the type of an expression.
|
|
||||||
;;;
|
|
||||||
;;; Both are the same solved constraint store, read from two sides.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
(include string.h)
|
|
||||||
|
|
||||||
;;; `(include string.h)' is for the C compiler; it tells Sex nothing.
|
|
||||||
;;; A signature has to be written before `_' can be resolved from a
|
|
||||||
;;; call to `strlen' -- without one the call's type is `?', and a `_'
|
|
||||||
;;; that resolves to `?' is an error, not a silent int.
|
|
||||||
(extern fn strlen ((s (* const char))) size-t)
|
|
||||||
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
|
|
||||||
(fn midpoint ((a (* const struct point)) (b (* const struct point))) (struct point)
|
|
||||||
(var m (struct point))
|
|
||||||
;; No `_' here: `m' has no initializer to infer from. Inference fills
|
|
||||||
;; in a type, it does not invent one.
|
|
||||||
(= (. m x) (/ (+ (. a x) (. b x)) 2))
|
|
||||||
(= (. m y) (/ (+ (. a y) (. b y)) 2))
|
|
||||||
(return m))
|
|
||||||
|
|
||||||
;;; A lambda's type is written once, in the signature; `_' reads it
|
|
||||||
;;; from there wherever the function is called.
|
|
||||||
(fn make-adder () (fn ((int)) int)
|
|
||||||
(return (lambda ((b int)) int
|
|
||||||
(return (+ b 10)))))
|
|
||||||
|
|
||||||
;;; A macro that asks what it was handed.
|
|
||||||
;;;
|
|
||||||
;;; `type-of' returns a *surface* type -- the same spelling the type
|
|
||||||
;;; database hands to `map-fields' -- so it composes with the
|
|
||||||
;;; `type-match' that already exists, and dispatch over a user struct
|
|
||||||
;;; costs nothing extra.
|
|
||||||
(defmacro (print x)
|
|
||||||
(type-match (type-of x)
|
|
||||||
(int `(printf "%d\n" ,x))
|
|
||||||
(size-t `(printf "%zu\n" ,x))
|
|
||||||
(double `(printf "%g\n" ,x))
|
|
||||||
((* const char) `(printf "%s\n" ,x))
|
|
||||||
;; NOTE: ,x twice -- a macro that duplicates its argument still has
|
|
||||||
;; to think about evaluating it twice. Inference does not fix that.
|
|
||||||
((struct point) `(printf "(%d, %d)\n" (. ,x x) (. ,x y)))
|
|
||||||
;; a function type is a type like any other, so it dispatches like
|
|
||||||
;; one -- and `_' saves a clause per signature
|
|
||||||
((fn _ int) `(printf "<fn of 0: %d>\n" (,x 0)))
|
|
||||||
(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
|
|
||||||
;;; before. Either spelling works -- `_' is the lazier one, and it is
|
|
||||||
;;; inferred in the expansion's own scope.
|
|
||||||
(defmacro (swap a b)
|
|
||||||
`(do (var tmp _ ,a)
|
|
||||||
(= ,a ,b)
|
|
||||||
(= ,b tmp)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
;; Written out, for contrast with everything below it.
|
|
||||||
(var greeting (* const char) "Hello from Sex!")
|
|
||||||
|
|
||||||
;; size-t, from the signature above -- not int, and not a guess.
|
|
||||||
(var n _ (strlen greeting))
|
|
||||||
(printf "%zu\n" n)
|
|
||||||
|
|
||||||
;; Literals carry a constraint, not a type: the int-ish one defaults
|
|
||||||
;; to int, and the mixed division joins to double the way C does.
|
|
||||||
(var count _ (+ 20 22))
|
|
||||||
(var half _ (/ 1.0 4))
|
|
||||||
(printf "%d %g\n" count half)
|
|
||||||
|
|
||||||
;; An aggregate initializer has no type of its own, so the type flows
|
|
||||||
;; in and has to be written. `(var origin _ #(3 4))' is an error --
|
|
||||||
;; there is nothing to infer from.
|
|
||||||
(var origin (struct point) #(3 4))
|
|
||||||
(var corner (struct point) #(7 10))
|
|
||||||
|
|
||||||
;; A compound literal is the way out of that rule: the `:' is where an
|
|
||||||
;; initializer stops needing a type from its context, so `_' has
|
|
||||||
;; something to read after all.
|
|
||||||
(var centre _ #((struct point) : 5 7))
|
|
||||||
(print centre)
|
|
||||||
|
|
||||||
;; ...and the same designated, which names fields instead of counting
|
|
||||||
;; positions.
|
|
||||||
(var offset _ #((struct point) : .x 1 .y 2))
|
|
||||||
(print offset)
|
|
||||||
|
|
||||||
;; A partial type: "a pointer to something". The something arrives
|
|
||||||
;; from the initializer. This is why the wildcard lives in the type
|
|
||||||
;; grammar rather than beside it -- it composes.
|
|
||||||
(var p (* _) (& origin))
|
|
||||||
|
|
||||||
;; Member access reads the same type database the macros do.
|
|
||||||
(var x _ (. p x))
|
|
||||||
(printf "%d\n" x)
|
|
||||||
|
|
||||||
;; A call into a function Sex has actually parsed: the return type is
|
|
||||||
;; the whole answer, and `print' then dispatches on it.
|
|
||||||
(var mid _ (midpoint (& origin) (& corner)))
|
|
||||||
(print mid)
|
|
||||||
|
|
||||||
;; The loop variable, which is where `_' earns its keep most often.
|
|
||||||
(for (var i _ 0) (< i 4) (++ i)
|
|
||||||
(printf "%d " (* i i)))
|
|
||||||
(printf "\n")
|
|
||||||
|
|
||||||
;; Four of something: the element type is fixed by the initializer,
|
|
||||||
;; the count by the type. Subscripting gives the element type back.
|
|
||||||
(var squares [_ 4] #(0 1 4 9))
|
|
||||||
(print [squares 2])
|
|
||||||
|
|
||||||
;; A function pointer's type comes from the signature that produced
|
|
||||||
;; it, and calling one needs that type and nothing else.
|
|
||||||
(var add-10 _ (make-adder))
|
|
||||||
(print (add-10 32))
|
|
||||||
(print add-10)
|
|
||||||
|
|
||||||
;; ...including where it is returned, with no name in between.
|
|
||||||
(print ((make-adder) 22))
|
|
||||||
|
|
||||||
;; A macro writing a declaration it could not have written before.
|
|
||||||
(var a _ 1)
|
|
||||||
(var b _ 2)
|
|
||||||
(swap a b)
|
|
||||||
(printf "%d %d\n" a b)
|
|
||||||
|
|
||||||
(print greeting)
|
|
||||||
(return 0))
|
|
||||||
|
|
||||||
;;; Open questions this draft raises, to settle before Layer 2 ships:
|
|
||||||
;;;
|
|
||||||
;;; 1. SETTLED. `type-match' took `_' on the pattern side, so
|
|
||||||
;;; `(fn _ int)' above is one clause rather than one per signature,
|
|
||||||
;;; and `(* _)' and `[_ _]' say "any pointer" and "any array". A `_'
|
|
||||||
;;; written last takes the rest, since a type's words are spread and
|
|
||||||
;;; not nested: `(* const char)' is three elements. Nothing
|
|
||||||
;;; destructures -- a macro body is Scheme and a type is a list, so
|
|
||||||
;;; `(caddr (type-of x))' reads an array's length.
|
|
||||||
;;;
|
|
||||||
;;; 2. SETTLED, allowed. `[_ 4]' against `#(0 1 4 9)' unifies each
|
|
||||||
;;; element with the hole, so the element type comes from the
|
|
||||||
;;; literals and the length stays as written -- `[_ 10]' with two
|
|
||||||
;;; initializers is still ten. Elements that disagree are a type
|
|
||||||
;;; mismatch. A bare `_' is still refused: `#(0 1 4 9)' has no type
|
|
||||||
;;; of its own, only elements.
|
|
||||||
;;;
|
|
||||||
;;; 3. POSTPONED to the standard library design. `(extern fn strlen
|
|
||||||
;;; ...)' above duplicates string.h, which is the same bargain every
|
|
||||||
;;; FFI makes, but it is where "no C header parsing" starts costing
|
|
||||||
;;; the user something. A `sex/libc' module of prototypes is the
|
|
||||||
;;; obvious answer and belongs with the rest of the stdlib.
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "Named fn through a pointer: 30"
|
|
||||||
"Lambda through a pointer: 30"
|
|
||||||
"Lambda called in place: 130"
|
|
||||||
"Nested lambdas: 666")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; Lambdas are lifted into toplevel functions by semen, so what this
|
|
||||||
;;; really checks is that the lifted `fn' comes out in the argument
|
|
||||||
;;; order the writer expects -- (fn name arglist ret-type . body).
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(fn sum ((a int) (b int)) int
|
|
||||||
(return (+ a b)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var a int 10)
|
|
||||||
(var b int 20)
|
|
||||||
|
|
||||||
(var sum-fn (fn ((int) (int)) int) sum)
|
|
||||||
(printf "Named fn through a pointer: %d\n" (sum-fn a b))
|
|
||||||
|
|
||||||
(var sum-lambda (fn ((int) (int)) int)
|
|
||||||
(lambda ((a int) (b int)) int
|
|
||||||
(return (+ a b))))
|
|
||||||
(printf "Lambda through a pointer: %d\n" (sum-lambda a b))
|
|
||||||
|
|
||||||
(printf "Lambda called in place: %d\n"
|
|
||||||
((lambda ((a int) (b int)) int
|
|
||||||
(return (+ a b 100)))
|
|
||||||
a b))
|
|
||||||
|
|
||||||
;; A lambda inside a lambda: the inner one is lifted out of a
|
|
||||||
;; function that is itself being lifted
|
|
||||||
(var outer (fn ((int)) int)
|
|
||||||
(lambda ((x int)) int
|
|
||||||
(var inner (fn ((int)) int)
|
|
||||||
(lambda ((y int)) int
|
|
||||||
(return (+ 60 y))))
|
|
||||||
(return (+ 600 (inner x)))))
|
|
||||||
(printf "Nested lambdas: %d\n" (outer 6))
|
|
||||||
|
|
||||||
(return 0))
|
|
||||||
@@ -9,25 +9,25 @@
|
|||||||
(fn-name (cat 'make-list- type)))
|
(fn-name (cat 'make-list- type)))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type)
|
`(,@(if is-public? '(pub) '()) fn ,fn-name () (* ,list-type)
|
||||||
(var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type)))
|
(var list (* ,list-type) (cast (malloc (sizeof ,list-type)) (* ,list-type)))
|
||||||
(= (. list next) NULL)
|
(= (-> list next) NULL)
|
||||||
(return list))))
|
(return list))))
|
||||||
|
|
||||||
(pub defmacro (add-value-list-T type is-public?)
|
(pub defmacro (add-value-list-T type is-public?)
|
||||||
(let ((list-type (list 'struct (cat 'list- type)))
|
(let ((list-type (list 'struct (cat 'list- type)))
|
||||||
(fn-name (cat 'add-value-list- type)))
|
(fn-name (cat 'add-value-list- type)))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void
|
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list * ,list-type) (value ,type)) void
|
||||||
(while (!= (. list next) NULL)
|
(while (!= (-> list next) NULL)
|
||||||
(= list (. list next)))
|
(= list (-> list next)))
|
||||||
(= (. list next) (,(cat 'make-list- type)))
|
(= (-> list next) (,(cat 'make-list- type)))
|
||||||
(= (. list value) value))))
|
(= (-> list value) value))))
|
||||||
|
|
||||||
(pub defmacro (length-list-T type is-public?)
|
(pub defmacro (length-list-T type is-public?)
|
||||||
(let ((fn-name (cat 'length-list- type))
|
(let ((fn-name (cat 'length-list- type))
|
||||||
(list-type (list 'struct (cat 'list- type))))
|
(list-type (list 'struct (cat 'list- type))))
|
||||||
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t
|
`(,@(if is-public? '(pub) '()) fn ,fn-name ((list ,(cons '* list-type))) size-t
|
||||||
(var n size-t 0)
|
(var n size-t 0)
|
||||||
(while (!= (. list next) NULL)
|
(while (!= (-> list next) NULL)
|
||||||
(= list (. list next))
|
(= list (-> list next))
|
||||||
(++ n))
|
(++ n))
|
||||||
(return n))))
|
(return n))))
|
||||||
|
|
||||||
@@ -35,14 +35,14 @@
|
|||||||
`(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type)
|
`(,@(if is-public? '(pub) '()) fn ,(cat 'is-empty-list- type)
|
||||||
((list ,(list '* 'struct (cat 'list- type))))
|
((list ,(list '* 'struct (cat 'list- type))))
|
||||||
bool
|
bool
|
||||||
(return (== (. list next) NULL))))
|
(return (== (-> list next) NULL))))
|
||||||
|
|
||||||
(pub defmacro (list-for-each list-type list-var elt-type elt-var what-do)
|
(pub defmacro (list-for-each list-type list-var elt-type elt-var what-do)
|
||||||
(let ((list-var-2 (cat list-var '-2)))
|
(let ((list-var-2 (cat list-var '-2)))
|
||||||
`(do
|
`(do
|
||||||
(var ,list-var-2 (* ,list-type) ,list-var)
|
(var ,list-var-2 (* ,list-type) ,list-var)
|
||||||
(var ,elt-var ,elt-type (. ,list-var-2 value))
|
(var ,elt-var ,elt-type (-> ,list-var-2 value))
|
||||||
(while (!= (. ,list-var-2 next) NULL)
|
(while (!= (-> ,list-var-2 next) NULL)
|
||||||
,what-do
|
,what-do
|
||||||
(= ,list-var-2 (. ,list-var-2 next))
|
(= ,list-var-2 (-> ,list-var-2 next))
|
||||||
(= ,elt-var (. ,list-var-2 value))))))
|
(= ,elt-var (-> ,list-var-2 value))))))
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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))
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "logical: 1 1 0"
|
|
||||||
"bitwise: 7 2 5"
|
|
||||||
"shifts: 48 0 12"
|
|
||||||
"increment: 7"
|
|
||||||
"decayed: 2 2 there"
|
|
||||||
"unsigned wins either way: 4294967295 4294967295"
|
|
||||||
"toplevel: 1 2.5 hi 12"
|
|
||||||
"a type is not a call: 7"
|
|
||||||
"radix literals: 224 5 128"
|
|
||||||
"a double reaches C whole: 1"
|
|
||||||
"negated literals: 1 2.5")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; The walk types an expression by its head, and the heads it had a
|
|
||||||
;;; rule for were the ones inference was written against. `&&', the
|
|
||||||
;;; bitwise operators, the shifts and `++' were not among them and each
|
|
||||||
;;; stopped with `cannot infer'.
|
|
||||||
;;;
|
|
||||||
;;; The rest of this is the same mistake in three other places: an array
|
|
||||||
;;; is a pointer the moment it is an operand, a rank tie is not decided
|
|
||||||
;;; by which operand was written first, and `_' is not a local's
|
|
||||||
;;; privilege.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(fn area ((w int) (h int)) int
|
|
||||||
(return (* w h)))
|
|
||||||
|
|
||||||
;;; a toplevel `_' reads the same table a local's does, so it can name
|
|
||||||
;;; anything declared above it
|
|
||||||
(var n _ 1)
|
|
||||||
(var d _ 2.5)
|
|
||||||
(var s _ "hi")
|
|
||||||
(var a _ (+ 3 (* 3 3)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var x int 6)
|
|
||||||
(var y int 3)
|
|
||||||
(var ok _ (&& x y))
|
|
||||||
(var orr _ (|| x y))
|
|
||||||
(var neg _ (! x))
|
|
||||||
(printf "logical: %d %d %d\n" ok orr neg)
|
|
||||||
|
|
||||||
(var bor _ (| x y))
|
|
||||||
(var band _ (& x y))
|
|
||||||
(var bxor _ (^ x y))
|
|
||||||
(printf "bitwise: %d %d %d\n" bor band bxor)
|
|
||||||
|
|
||||||
;; a shift is the promoted left operand, not a join: the right one
|
|
||||||
;; says only how far
|
|
||||||
(var c char 12)
|
|
||||||
(var shl _ (<< x y))
|
|
||||||
(var shr _ (>> x y))
|
|
||||||
(var wide _ (>> c 0))
|
|
||||||
(printf "shifts: %d %d %d\n" shl shr wide)
|
|
||||||
|
|
||||||
;; ...and an increment is the operand, unpromoted
|
|
||||||
(var inc _ (++ x))
|
|
||||||
(printf "increment: %d\n" inc)
|
|
||||||
|
|
||||||
;; an array operand decays, so this is a pointer and not an array
|
|
||||||
(var xs [int 4] #(1 2 3 4))
|
|
||||||
(var p _ (+ xs 1))
|
|
||||||
(var q _ (+ 1 xs))
|
|
||||||
(var names [(* const char) 2] #("hi" "there"))
|
|
||||||
(var np _ (+ names 1))
|
|
||||||
(printf "decayed: %d %d %s\n" (* p) (* q) (* np))
|
|
||||||
|
|
||||||
;; at equal rank C takes the unsigned operand, whichever side it is on
|
|
||||||
(var i int -1)
|
|
||||||
(var u (unsigned int) 1)
|
|
||||||
(var u1 _ (+ i u))
|
|
||||||
(var u2 _ (+ u i))
|
|
||||||
(printf "unsigned wins either way: %u %u\n" (- u1 1) (- u2 1))
|
|
||||||
|
|
||||||
(printf "toplevel: %d %g %s %d\n" n d s 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
|
|
||||||
(var f (fn ((int)) int) (lambda ((v int)) int (return (+ v 1))))
|
|
||||||
(var fp (fn ((f int) (g int)) int) area)
|
|
||||||
(printf "a type is not a call: %d\n" (f 6))
|
|
||||||
|
|
||||||
;; a mask reads best in the radix it is a mask in
|
|
||||||
(var lead int 0xE5)
|
|
||||||
(printf "radix literals: %d %d %d\n" (& lead 0xE0) (& lead 0b111) #x80)
|
|
||||||
|
|
||||||
;; ...and a double in all the digits it was written with
|
|
||||||
(var sixth double (/ 1.0 6.0))
|
|
||||||
(printf "a double reaches C whole: %d\n" (== 0.16666666666666666 sixth))
|
|
||||||
|
|
||||||
;; 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))
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
(compilation "-- -lm")
|
|
||||||
(input)
|
|
||||||
(output "5.0 5.0 10.0 14.0 14.0 6.0"
|
|
||||||
"struct receiver: 14"
|
|
||||||
"private: 8.0"
|
|
||||||
"forward call: 28.0")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; An ops block is mangled fns plus a registry entry, so a method is
|
|
||||||
;;; reachable both ways: spelled out as vec2/length, or as (.length v).
|
|
||||||
;;; The method sits in the head, not in a field position, so (. v x) is
|
|
||||||
;;; always the field x and the two cannot be confused -- here vec2 has
|
|
||||||
;;; both a field x and methods, and nothing arbitrates between them.
|
|
||||||
;;;
|
|
||||||
;;; Whether the receiver is addressed, dereferenced or passed along is
|
|
||||||
;;; decided by its type against the method's own, so (.length v) and
|
|
||||||
;;; (.length p) both work. `ops' takes a plain C struct too: it keys on
|
|
||||||
;;; the tag, not on the typedef a record happens to add.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
(include math.h)
|
|
||||||
|
|
||||||
(record vec2 ((x float) (y float)))
|
|
||||||
|
|
||||||
(ops vec2
|
|
||||||
;; a method may call one written below it
|
|
||||||
(fn twice-sum ((self vec2)) float
|
|
||||||
(return (* 2.0 (.sum-of self))))
|
|
||||||
|
|
||||||
(pub fn length ((self (* const vec2))) float
|
|
||||||
"Pointer self, so (.length v) has to take the address."
|
|
||||||
(return (sqrtf (+ (* (. self x) (. self x))
|
|
||||||
(* (. self y) (. self y))))))
|
|
||||||
|
|
||||||
(fn scale ((self (* vec2)) (k float)) void
|
|
||||||
(*= (. self x) k)
|
|
||||||
(*= (. self y) k))
|
|
||||||
|
|
||||||
(fn sum-of ((self vec2)) float
|
|
||||||
;; value self, so (.sum-of p) has to dereference
|
|
||||||
(return (+ (. self x) (. self y)))))
|
|
||||||
|
|
||||||
(struct raw ((a int) (b int)))
|
|
||||||
|
|
||||||
(ops raw
|
|
||||||
(fn total ((self (* const (struct raw)))) int
|
|
||||||
(return (+ (. self a) (. self b)))))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var v vec2 #(vec2 : 3.0 4.0))
|
|
||||||
(var p (* vec2) (& v))
|
|
||||||
|
|
||||||
(printf "%.1f %.1f " (.length v) (vec2/length (& v)))
|
|
||||||
(.scale v 2.0)
|
|
||||||
(printf "%.1f %.1f %.1f %.1f\n"
|
|
||||||
(.length p) (.sum-of v) (.sum-of p) (. v x))
|
|
||||||
|
|
||||||
(var r (struct raw) #(struct raw : 6 8))
|
|
||||||
(printf "struct receiver: %d\n" (.total r))
|
|
||||||
|
|
||||||
(var u vec2 #(vec2 : 8.0 0.0))
|
|
||||||
(printf "private: %.1f\n" (vec2/sum-of u))
|
|
||||||
(printf "forward call: %.1f\n" (.twice-sum v))
|
|
||||||
(return 0))
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "conditional operand: 75"
|
|
||||||
"cast as object of .: 7"
|
|
||||||
"cast of bitwise: 1"
|
|
||||||
"cast of conditional: 44"
|
|
||||||
"define body: 6")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A Sex form is parenthesised by construction, and C is not: whatever
|
|
||||||
;;; the writer leaves bare, C regroups by its own precedence. Each line
|
|
||||||
;;; below came out regrouped, and all but the member access still
|
|
||||||
;;; compiled -- computing 4, 257, 300, and 4 from `2 * 1 + 2'.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(record wanted ((distance int)))
|
|
||||||
|
|
||||||
(define SUM (+ 1 2))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var compared int 4)
|
|
||||||
(printf "conditional operand: %d\n" (/ 300 (if (> compared 0) compared 1)))
|
|
||||||
|
|
||||||
(var w wanted #(wanted : 7))
|
|
||||||
(var pa (* const void) (& w))
|
|
||||||
(printf "cast as object of .: %d\n" (. (cast pa (* const wanted)) distance))
|
|
||||||
|
|
||||||
(var x int 1)
|
|
||||||
(printf "cast of bitwise: %d\n" (cast (| x 256) u8))
|
|
||||||
(printf "cast of conditional: %d\n" (cast (if x 300 1) u8))
|
|
||||||
(printf "define body: %d\n" (* 2 SUM))
|
|
||||||
(return 0))
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "p 3 4 / n 7 zoe / area 12 / sizes 8 8"
|
|
||||||
"chain 1 2")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A record is a struct that also names itself, so the bare name
|
|
||||||
;;; stands wherever (struct name) had to: a var, a pointer, an array
|
|
||||||
;;; element, an arglist, a return type, a sizeof. struct keeps C's
|
|
||||||
;;; meaning, for a type that came from a header or is laid out to
|
|
||||||
;;; match one.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(record point ((x int) (y int)))
|
|
||||||
|
|
||||||
(record named
|
|
||||||
"Fields of more than one kind, and a docstring."
|
|
||||||
((id int) (first-name (* const char))))
|
|
||||||
|
|
||||||
(struct raw ((a int) (b int)))
|
|
||||||
|
|
||||||
;;; 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
|
|
||||||
(+= (. p x) dx)
|
|
||||||
(+= (. p y) dy))
|
|
||||||
|
|
||||||
(fn area ((p point)) int
|
|
||||||
(return (* (. p x) (. p y))))
|
|
||||||
|
|
||||||
(fn origin () point
|
|
||||||
(return #(point : 0 0)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var p point #(point : 1 2))
|
|
||||||
(shift (& p) 2 2)
|
|
||||||
|
|
||||||
(var n named #(named : .id 7 .first-name "zoe"))
|
|
||||||
(var r (struct raw) #(struct raw : 1 2))
|
|
||||||
|
|
||||||
(var ps [point 2])
|
|
||||||
(= [ps 0] p)
|
|
||||||
(= [ps 1] (origin))
|
|
||||||
|
|
||||||
(printf "p %d %d / n %d %s / area %d / sizes %zu %zu\n"
|
|
||||||
(. p x) (. p y) (. n id) (. n first-name)
|
|
||||||
(area [ps 0])
|
|
||||||
(sizeof point) (sizeof (struct raw)))
|
|
||||||
|
|
||||||
(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))))
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
((* const char) "%s")
|
((* const char) "%s")
|
||||||
(else (error "print-struct: unsupported field type"
|
(else (error "print-struct: unsupported field type"
|
||||||
name type))))
|
name type))))
|
||||||
(. v ,name))))))
|
(-> v ,name))))))
|
||||||
(if (not printers)
|
(if (not printers)
|
||||||
(error "print-struct: no such struct" type-name)
|
(error "print-struct: no such struct" type-name)
|
||||||
`(fn ,(cat 'print- type-name) ((v (* const struct ,type-name))) void
|
`(fn ,(cat 'print- type-name) ((v (* const struct ,type-name))) void
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "3.14 12.00 0.00"
|
|
||||||
"held once: a 1"
|
|
||||||
"nested: -(2 + 3) = -5"
|
|
||||||
"size: 4"
|
|
||||||
"tagged only: 1"
|
|
||||||
"broke out after 2"
|
|
||||||
"rows: 18 5")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A sum is a tag enum, a payload struct per variant that carries
|
|
||||||
;;; fields, and the record holding both; a constructor is the value
|
|
||||||
;;; itself, written in place. match is a switch over the tag whose arms
|
|
||||||
;;; bind the payload as locals, and the compiler refuses one that leaves
|
|
||||||
;;; a variant out -- which is the thing the form exists for.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(sum shape
|
|
||||||
((circle ((r float)))
|
|
||||||
(rect ((w float) (h float)))
|
|
||||||
(empty ())))
|
|
||||||
|
|
||||||
(fn area ((s shape)) float
|
|
||||||
(var out float 0.0)
|
|
||||||
(match s
|
|
||||||
((circle (r)) (= out (* 3.14159 r r)))
|
|
||||||
((rect (w h)) (= out (* w h)))
|
|
||||||
((empty ()) (= out 0.0)))
|
|
||||||
(return out))
|
|
||||||
|
|
||||||
;;; Recursive through pointers, because a value cannot hold itself
|
|
||||||
(sum expr
|
|
||||||
((lit ((v float)))
|
|
||||||
(neg ((e (* const expr))))
|
|
||||||
(add ((l (* const expr)) (r (* const expr))))))
|
|
||||||
|
|
||||||
(fn eval ((self (* const expr))) float
|
|
||||||
(match (* self)
|
|
||||||
((lit (v)) (return v))
|
|
||||||
((neg (e)) (return (- (eval e))))
|
|
||||||
((add (l r)) (return (+ (eval l) (eval r))))))
|
|
||||||
|
|
||||||
(fn show ((self (* const expr))) void
|
|
||||||
(match (* self)
|
|
||||||
((lit (v)) (printf "%g" v))
|
|
||||||
((neg (e)) (printf "-") (show e))
|
|
||||||
((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")"))))
|
|
||||||
|
|
||||||
;;; 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
|
|
||||||
(sum light ((red ()) (green ())))
|
|
||||||
|
|
||||||
(fn mk-shape () shape (return (shape/circle 1.0)))
|
|
||||||
|
|
||||||
(sum held ((a ((x int) (y int))) (b ())))
|
|
||||||
(fn mk-held () held (return (held/a 1 2)))
|
|
||||||
|
|
||||||
;;; An array field is handed elements, never an array: C copies neither
|
|
||||||
;;; into a parameter nor into another array, so both the constructor
|
|
||||||
;;; and the binder spell it out
|
|
||||||
(define N 4)
|
|
||||||
(sum row ((cells ((xs [int N]))) (none ())))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(printf "%.2f %.2f %.2f\n"
|
|
||||||
(area (mk-shape))
|
|
||||||
(area (shape/rect 3.0 4.0))
|
|
||||||
(area (shape/empty)))
|
|
||||||
|
|
||||||
;; the scrutinee is a call, so it is read into a local once
|
|
||||||
(match (mk-held)
|
|
||||||
((a (x _)) (printf "held once: a %d\n" x)) ; `_' drops y
|
|
||||||
(else (printf "held once: other\n")))
|
|
||||||
|
|
||||||
(var two expr (expr/lit 2.0))
|
|
||||||
(var three expr (expr/lit 3.0))
|
|
||||||
(var both expr (expr/add (& two) (& three)))
|
|
||||||
(var e expr (expr/neg (& both)))
|
|
||||||
(printf "nested: ")
|
|
||||||
(show (& e))
|
|
||||||
(printf " = %g\n" (eval (& e)))
|
|
||||||
(printf "size: %d\n" (size (& e)))
|
|
||||||
|
|
||||||
(var l light (light/green))
|
|
||||||
(match l
|
|
||||||
((red ()) (printf "tagged only: 0\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 rows [row 2] #((row/cells a) (row/cells #(1 2 3 4))))
|
|
||||||
(= [a 0] 50) ; the row holds a copy
|
|
||||||
(var sum int 0)
|
|
||||||
(for (var i int 0) (< i 2) (++ i)
|
|
||||||
(match [rows i]
|
|
||||||
((cells (xs))
|
|
||||||
(= [xs 0] 100) ; and so does the binder
|
|
||||||
(+= sum (+ [xs 1] [xs 2])))
|
|
||||||
((none ()) (+= sum 0))))
|
|
||||||
(printf "rows: %d %d\n" sum (. [rows 0] u cells [xs 0]))
|
|
||||||
(return 0))
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "arithmetic: 26"
|
|
||||||
"a bare step needs no parens: 20"
|
|
||||||
"through a path: 1 4"
|
|
||||||
"mixed with a method: 25"
|
|
||||||
"one step is just the value: 7")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A step may be a call, a bare name, a member path or a method, and
|
|
||||||
;;; the value goes in as its first argument.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
(import threading-macros)
|
|
||||||
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
(struct line ((a (* struct point)) (b (struct point))))
|
|
||||||
|
|
||||||
(fn double-it ((n int)) int
|
|
||||||
(return (* n 2)))
|
|
||||||
|
|
||||||
(fn add ((n int) (m int)) int
|
|
||||||
(return (+ n m)))
|
|
||||||
|
|
||||||
(ops point
|
|
||||||
(pub fn length-sq ((self (* const struct point))) int
|
|
||||||
(return (+ (* (. self x) (. self x))
|
|
||||||
(* (. self y) (. self y))))))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
;; (add (double-it 5) 3) doubled: inside out, written outside in
|
|
||||||
(printf "arithmetic: %d\n"
|
|
||||||
(-> 5
|
|
||||||
double-it
|
|
||||||
(add 3)
|
|
||||||
double-it))
|
|
||||||
(printf "a bare step needs no parens: %d\n" (-> 5 double-it double-it))
|
|
||||||
|
|
||||||
(var p (struct point) #(1 2))
|
|
||||||
(var l (struct line) #(struct line : .a (& p) .b #(3 4)))
|
|
||||||
(var lp (* struct line) (& l))
|
|
||||||
;; a member path is an ordinary step, and reads through both pointers
|
|
||||||
(printf "through a path: %d %d\n"
|
|
||||||
(-> lp (. a x))
|
|
||||||
(. lp b y))
|
|
||||||
|
|
||||||
(var q (struct point) #(3 4))
|
|
||||||
(printf "mixed with a method: %d\n" (-> q .length-sq))
|
|
||||||
|
|
||||||
(printf "one step is just the value: %d\n" (-> 7))
|
|
||||||
(return 0))
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "aggregate element: 3 4"
|
|
||||||
"pointer element: there"
|
|
||||||
"multi-word element: 9"
|
|
||||||
"through a pointer: 55"
|
|
||||||
"unsized of a typedef: 1 2"
|
|
||||||
"unsized of a pointer: 5"
|
|
||||||
"named bound: 2 4 b"
|
|
||||||
"unnamed parameters: 7 -1 2"
|
|
||||||
"typedefs: hi 4 2"
|
|
||||||
"sizeof a pointer type: 1 1"
|
|
||||||
"dimensions: 6 12 5"
|
|
||||||
"returned function: 42")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; Three questions about a written type that used to be answered in
|
|
||||||
;;; three places and disagreed: is `(a b)' a named parameter or a bare
|
|
||||||
;;; type, is the last element of a `[...]' its bound or the last word of
|
|
||||||
;;; its element type, and what is one element of an array.
|
|
||||||
;;;
|
|
||||||
;;; They are one question -- where does the type end -- so the answer
|
|
||||||
;;; lives in `types' and everything else asks it.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
|
|
||||||
(typedef small int)
|
|
||||||
(typedef cstr (* const char))
|
|
||||||
(typedef vec4 [float 4])
|
|
||||||
(typedef unary (fn ((small)) small))
|
|
||||||
|
|
||||||
(fn successor ((n int)) int (return (+ n 1)))
|
|
||||||
(fn stepper () (fn ((int)) int) (return successor))
|
|
||||||
|
|
||||||
(define CAP 2)
|
|
||||||
|
|
||||||
;;; a parameter that names nothing is a type, however many words it
|
|
||||||
;;; takes: `(unsigned int)' is one of them, not a `unsigned' called
|
|
||||||
;;; `int'
|
|
||||||
(fn width ((n unsigned int)) int
|
|
||||||
(return (cast n int)))
|
|
||||||
|
|
||||||
(fn sign ((c const char)) int
|
|
||||||
(if (== c #\a) (return -1))
|
|
||||||
(return 1))
|
|
||||||
|
|
||||||
(fn twice ((n small)) int
|
|
||||||
(return (* n 2)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
;; an element keeps every word of its type, tag and all
|
|
||||||
(var pts [(struct point) 2] #(#((struct point) : 1 2)
|
|
||||||
#((struct point) : 3 4)))
|
|
||||||
(var p _ [pts 1])
|
|
||||||
(printf "aggregate element: %d %d\n" (. p x) (. p y))
|
|
||||||
|
|
||||||
(var names [(* const char) 2] #("hi" "there"))
|
|
||||||
(var s _ [names 1])
|
|
||||||
(printf "pointer element: %s\n" s)
|
|
||||||
|
|
||||||
(var nums [unsigned int 3] #(7 8 9))
|
|
||||||
(var u _ [nums 2])
|
|
||||||
(printf "multi-word element: %u\n" u)
|
|
||||||
|
|
||||||
;; subscripting a pointer answers the same as subscripting an array
|
|
||||||
(var q (* (struct point)) (& [pts 0]))
|
|
||||||
(var r _ [q 1])
|
|
||||||
(printf "through a pointer: %d\n" (+ (. r x) (* 13 (. r y))))
|
|
||||||
|
|
||||||
;; the last word of an unsized array's type is not its bound: neither
|
|
||||||
;; a typedef name nor the target of a `*' can be one
|
|
||||||
(var tail [const small] #(1 2))
|
|
||||||
(printf "unsized of a typedef: %d %d\n" [tail 0] [tail 1])
|
|
||||||
|
|
||||||
(var one size-t 5)
|
|
||||||
(var sizes [* size-t] #((& one)))
|
|
||||||
(var w _ [sizes 0])
|
|
||||||
(printf "unsized of a pointer: %d\n" (cast (* w) int))
|
|
||||||
|
|
||||||
;; ...but after a whole type, a name is: `size-t' is a typedef only C
|
|
||||||
;; knows of, and `(* const char)' a type grouped into one element
|
|
||||||
(var ws [size-t CAP] #(3 4))
|
|
||||||
(var gs [(* const char) CAP] #("a" "b"))
|
|
||||||
(printf "named bound: %zu %zu %s\n"
|
|
||||||
(/ (sizeof ws) (sizeof [ws 0])) [ws 1] [gs 1])
|
|
||||||
|
|
||||||
;; the same question in type position: `(fn ((unsigned int)) int)'
|
|
||||||
;; takes one parameter, not two
|
|
||||||
(var fp (fn ((unsigned int)) int) width)
|
|
||||||
(printf "unnamed parameters: %d %d %d\n" (fp 7) (sign #\a) (twice 1))
|
|
||||||
|
|
||||||
;; a typedef's target is every one of those shapes as well
|
|
||||||
(var greeting cstr "hi")
|
|
||||||
(var v vec4 #(1.0 2.0 3.0 4.0))
|
|
||||||
(var op unary twice)
|
|
||||||
(printf "typedefs: %s %zu %d\n" greeting (/ (sizeof v) (sizeof [v 0])) (op 1))
|
|
||||||
|
|
||||||
;; `(* T)' is a type or a dereference, and only what is in scope says
|
|
||||||
(printf "sizeof a pointer type: %d %d\n"
|
|
||||||
(== (sizeof (* const char)) (sizeof greeting))
|
|
||||||
(== (sizeof (* greeting)) 1))
|
|
||||||
|
|
||||||
;; [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))
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
(input)
|
(input)
|
||||||
(output "café 日本語 🍺" "café1" "naïve: 3" "predicate: 1 0")
|
(output "café 日本語 🍺" "café1" "naïve: 3")
|
||||||
(return 0)
|
(return 0)
|
||||||
|
|
||||||
;;; Non-ASCII string literals and identifiers.
|
;;; Non-ASCII string literals and identifiers.
|
||||||
@@ -13,22 +13,12 @@
|
|||||||
;;; non-ASCII characters must survive unkebabify intact -- getting this
|
;;; non-ASCII characters must survive unkebabify intact -- getting this
|
||||||
;;; wrong truncates the name silently, and the program still compiles
|
;;; wrong truncates the name silently, and the program still compiles
|
||||||
;;; and runs, just under a different name than the one written.
|
;;; and runs, just under a different name than the one written.
|
||||||
;;;
|
|
||||||
;;; `?' and `!' end Lisp predicates and mutators, and C takes neither:
|
|
||||||
;;; they become the letters ʔ and ꜝ.
|
|
||||||
|
|
||||||
(include stdio.h)
|
(include stdio.h)
|
||||||
|
|
||||||
(fn zero? ((n int)) bool (return (== n 0)))
|
|
||||||
(fn clear! ((n (* int))) void (= (* n) 0))
|
|
||||||
|
|
||||||
(pub fn main () int
|
(pub fn main () int
|
||||||
(puts "café 日本語 🍺")
|
(puts "café 日本語 🍺")
|
||||||
(puts "café1")
|
(puts "café1")
|
||||||
(var naïve-count int 3)
|
(var naïve-count int 3)
|
||||||
(printf "naïve: %d\n" naïve-count)
|
(printf "naïve: %d\n" naïve-count)
|
||||||
(var n int 5)
|
|
||||||
(var before bool (zero? n))
|
|
||||||
(clear! (& n))
|
|
||||||
(printf "predicate: %d %d\n" (zero? n) before)
|
|
||||||
(return 0))
|
(return 0))
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "one word: 7"
|
|
||||||
"pointer: 2"
|
|
||||||
"aggregate: 3"
|
|
||||||
"array: 2.5"
|
|
||||||
"variadic: 1 two")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; A parameter that names nothing still has to reach the C writer as a
|
|
||||||
;;; type and a name, the name being absent. Handed the bare type
|
|
||||||
;;; instead, fmt-c read the type's own second word as the name -- so
|
|
||||||
;;; `(* const char)' came out `const char', which is a different
|
|
||||||
;;; function -- and a one-word type had no second word to read at all.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
(include stdarg.h)
|
|
||||||
|
|
||||||
(struct point ((x int) (y int)))
|
|
||||||
|
|
||||||
;;; declared here rather than included, so the prototype we emit is the
|
|
||||||
;;; one the C compiler checks the call against
|
|
||||||
(extern fn abs ((int)) int)
|
|
||||||
(extern fn strlen ((* const char)) size-t)
|
|
||||||
|
|
||||||
(fn origin-x ((p (* (struct point)))) int
|
|
||||||
(return (. (* p) x)))
|
|
||||||
|
|
||||||
(fn second-of ((xs [float 4])) float
|
|
||||||
(return [xs 1]))
|
|
||||||
|
|
||||||
(fn say ((fmt (* const char)) ...) void
|
|
||||||
(var ap va-list)
|
|
||||||
(va-start ap fmt)
|
|
||||||
(vprintf fmt ap)
|
|
||||||
(va-end ap))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(printf "one word: %d\n" (abs -7))
|
|
||||||
(printf "pointer: %d\n" (cast (strlen "hi") int))
|
|
||||||
|
|
||||||
;; the same parameter lists written as types
|
|
||||||
(var p (struct point) #((struct point) : 3 4))
|
|
||||||
(var f (fn ((* (struct point))) int) origin-x)
|
|
||||||
(printf "aggregate: %d\n" (f (& p)))
|
|
||||||
|
|
||||||
(var xs [float 4] #(1.5 2.5 3.5 4.5))
|
|
||||||
(var g (fn ([float 4]) float) second-of)
|
|
||||||
(printf "array: %g\n" (g xs))
|
|
||||||
|
|
||||||
(say "variadic: %d %s\n" 1 "two")
|
|
||||||
(return 0))
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
(input)
|
|
||||||
(output "literals: 42 3.5 hello"
|
|
||||||
"calls: 12"
|
|
||||||
"members: 1 2.5"
|
|
||||||
"pointers: 1 2.5"
|
|
||||||
"arrays: 30"
|
|
||||||
"loop: 0 1 2"
|
|
||||||
"shadowed: 9 then 42"
|
|
||||||
"still an int: 200"
|
|
||||||
"case scope: 200"
|
|
||||||
"partial: 1 2.5"
|
|
||||||
"joined: 43.5 84 49 1"
|
|
||||||
"promoted: 200 60000 3705032704"
|
|
||||||
"prelude: 400 6"
|
|
||||||
"from elements: 4 9 0")
|
|
||||||
(return 0)
|
|
||||||
|
|
||||||
;;; `_' as a type means "work it out from the initializer". What the
|
|
||||||
;;; pass can answer comes from declarations -- Sex writes a type at
|
|
||||||
;;; every binding site -- and from the signature of whatever a call
|
|
||||||
;;; names. A partial type like `(* _)' is solved by unifying what was
|
|
||||||
;;; written against what the initializer gives, so only the wildcard
|
|
||||||
;;; inside the spelling is filled in.
|
|
||||||
|
|
||||||
(include stdio.h)
|
|
||||||
|
|
||||||
(struct point ((x int) (y float)))
|
|
||||||
|
|
||||||
(fn area ((w int) (h int)) int
|
|
||||||
(return (* w h)))
|
|
||||||
|
|
||||||
(pub fn main () int
|
|
||||||
(var n _ 42)
|
|
||||||
(var f _ 3.5)
|
|
||||||
(var s _ "hello")
|
|
||||||
(printf "literals: %d %g %s\n" n f s)
|
|
||||||
|
|
||||||
(var a _ (area 3 4))
|
|
||||||
(printf "calls: %d\n" a)
|
|
||||||
|
|
||||||
(var p (struct point) #((struct point) : .x 1 .y 2.5))
|
|
||||||
(var px _ (. p x))
|
|
||||||
(var py _ (. p y))
|
|
||||||
(printf "members: %d %g\n" px py)
|
|
||||||
|
|
||||||
(var pp _ (& p))
|
|
||||||
(printf "pointers: %d %g\n" (. pp x) (. pp y))
|
|
||||||
|
|
||||||
(var table [int 3])
|
|
||||||
(= [table 0] 10)
|
|
||||||
(= [table 1] 20)
|
|
||||||
(var first _ [table 0])
|
|
||||||
(var second _ [table 1])
|
|
||||||
(printf "arrays: %d\n" (+ first second))
|
|
||||||
|
|
||||||
;; a for opens a scope, and its initializer is declared inside it
|
|
||||||
(printf "loop:")
|
|
||||||
(for (var i _ 0) (< i 3) (++ i)
|
|
||||||
(printf " %d" i))
|
|
||||||
(printf "\n")
|
|
||||||
|
|
||||||
;; a block's declarations end with it, and so do the declarations of
|
|
||||||
;; everything else C brackets -- a `while' body is a block with no
|
|
||||||
;; `do' written around it
|
|
||||||
(do (var n _ 9)
|
|
||||||
(printf "shadowed: %d then " n))
|
|
||||||
(printf "%d\n" n)
|
|
||||||
|
|
||||||
(var wide int 200)
|
|
||||||
(while false (var wide char 1) (printf "%d" wide))
|
|
||||||
(if false (do (var wide char 1) (printf "%d" wide)))
|
|
||||||
(switch a (case 1 (var wide char 1) (printf "%d" wide)))
|
|
||||||
;; a copy, not a sum: an arithmetic result would be promoted to `int'
|
|
||||||
;; whatever leaked, and say nothing
|
|
||||||
(var copy _ wide)
|
|
||||||
(printf "still an int: %d\n" copy)
|
|
||||||
|
|
||||||
;; each case is a block of its own: the second sees the outer `wide',
|
|
||||||
;; not the first one's
|
|
||||||
(switch 2
|
|
||||||
(case 1 (var wide double 1.5) (printf "%g" wide))
|
|
||||||
(case 2 (var seen _ wide) (printf "case scope: %d\n" seen)))
|
|
||||||
|
|
||||||
;; a wildcard inside a written type: only it is solved
|
|
||||||
(var pp2 (* _) (& p))
|
|
||||||
(printf "partial: %d %g\n" (. pp2 x) (. pp2 y))
|
|
||||||
|
|
||||||
;; C's usual arithmetic conversions, far enough to answer `_'
|
|
||||||
(var d double 1.5)
|
|
||||||
(var l long 7)
|
|
||||||
(var g float 0.5)
|
|
||||||
(var mixed _ (+ n d))
|
|
||||||
(var same _ (+ n n))
|
|
||||||
(var wider _ (+ n l))
|
|
||||||
(var single _ (+ g g))
|
|
||||||
(printf "joined: %g %d %ld %g\n" mixed same wider single)
|
|
||||||
|
|
||||||
;; ...including the promotions, which two operands of one narrow type
|
|
||||||
;; are exactly where they show: `char' + `char' is an `int'
|
|
||||||
(var c1 char 100)
|
|
||||||
(var c2 char 100)
|
|
||||||
(var h1 short 30000)
|
|
||||||
(var narrow _ (+ c1 c2))
|
|
||||||
(var narrower _ (+ h1 h1))
|
|
||||||
(var kept (unsigned int) 4000000000)
|
|
||||||
(var unpromoted _ (+ kept kept))
|
|
||||||
(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
|
|
||||||
;; the hole in the array type around it -- and the length stays as
|
|
||||||
;; written, whether or not every slot is initialized
|
|
||||||
(var squares [_ 4] #(0 1 4 9))
|
|
||||||
(var sparse [_ 8] #(0 1))
|
|
||||||
(printf "from elements: %d %d %d\n" [squares 2] [squares 3] [sparse 7])
|
|
||||||
(return 0))
|
|
||||||
3
tests/sexc.module.scm
Normal file
3
tests/sexc.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module sexc
|
||||||
|
*
|
||||||
|
"../sexc.scm")
|
||||||
3
tests/types.module.scm
Normal file
3
tests/types.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module types
|
||||||
|
*
|
||||||
|
"../types.scm")
|
||||||
149
tests/types.scm
149
tests/types.scm
@@ -42,89 +42,18 @@
|
|||||||
#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))
|
||||||
|
|
||||||
;; Reflection through an alias. Both spellings of the target occur:
|
|
||||||
;; (typedef point-t point) and (typedef point-t (struct point)).
|
|
||||||
(add-typedef 't-point-t '(typedef t-point-t t-point))
|
|
||||||
(test "a typedef to a struct has the struct's fields"
|
|
||||||
'((x int) (y int))
|
|
||||||
(get-fields 't-point-t))
|
|
||||||
(add-typedef 't-point-s '(typedef t-point-s (struct t-point)))
|
|
||||||
(test "written the other way round too"
|
|
||||||
'((x int) (y int))
|
|
||||||
(get-fields 't-point-s))
|
|
||||||
(add-typedef 't-point-2 '(typedef t-point-2 t-point-t))
|
|
||||||
(test "and through a chain of them"
|
|
||||||
'((x int) (y int))
|
|
||||||
(get-fields 't-point-2))
|
|
||||||
(test "map-fields follows an alias as well"
|
|
||||||
'((x int) (y int))
|
|
||||||
(map-fields 't-point-t (lambda (name type) (list name type))))
|
|
||||||
(add-typedef 't-color-t '(typedef t-color-t t-color))
|
|
||||||
(test "an aliased enum is still named as it was declared"
|
|
||||||
'((red (enum t-color)) (green (enum t-color)) (blue (enum t-color)))
|
|
||||||
(map-fields 't-color-t (lambda (name type) (list name type))))
|
|
||||||
(test "a typedef to a primitive has no fields"
|
|
||||||
#f
|
|
||||||
(get-fields 't-u8))
|
|
||||||
|
|
||||||
;; C keeps typedefs and ordinary identifiers apart, and the canonical way
|
|
||||||
;; to declare a struct uses both names at once. Neither declaration
|
|
||||||
;; may stand on the other.
|
|
||||||
(add-struct 't-node '(struct t-node ((next (* t-node)) (v int))))
|
|
||||||
(add-typedef 't-node '(typedef t-node (struct t-node)))
|
|
||||||
(test "a typedef of a struct's own name keeps the struct reachable"
|
|
||||||
'((next (* t-node)) (v int))
|
|
||||||
(get-fields 't-node))
|
|
||||||
(test "and the tag is there under its own name"
|
|
||||||
'(struct t-node ((next (* t-node)) (v int)))
|
|
||||||
(get-tag-info 't-node))
|
|
||||||
(add-struct 't-rect '(struct t-rect ((w int) (h int))))
|
|
||||||
(add-define 't-rect '(define t-rect 3))
|
|
||||||
(test "a define of a tag's name does not hide the fields"
|
|
||||||
'((w int) (h int))
|
|
||||||
(get-fields 't-rect))
|
|
||||||
|
|
||||||
;; A type built over a struct is not that struct. Handing back the
|
|
||||||
;; element's fields would have a macro write v->x for an array
|
|
||||||
(add-typedef 't-points '(typedef t-points (¤ t-point 4)))
|
|
||||||
(test "an array of a struct has no fields of its own"
|
|
||||||
#f
|
|
||||||
(get-fields 't-points))
|
|
||||||
(add-typedef 't-point-p '(typedef t-point-p (* t-point)))
|
|
||||||
(test "nor does a pointer to one"
|
|
||||||
#f
|
|
||||||
(get-fields 't-point-p))
|
|
||||||
(add-typedef 't-cb '(typedef t-cb (fn ((t-point)) void)))
|
|
||||||
(test "nor a function type over one"
|
|
||||||
#f
|
|
||||||
(get-fields 't-cb))
|
|
||||||
|
|
||||||
;; A typedef can be written to lead back to itself. Resolving it must
|
|
||||||
;; stop rather than spin
|
|
||||||
(add-typedef 't-loop-a '(typedef t-loop-a t-loop-b))
|
|
||||||
(add-typedef 't-loop-b '(typedef t-loop-b t-loop-a))
|
|
||||||
(test "a typedef cycle terminates"
|
|
||||||
't-loop-a
|
|
||||||
(get-underlying-type 't-loop-a))
|
|
||||||
(test "and has no fields"
|
|
||||||
#f
|
|
||||||
(get-fields 't-loop-a))
|
|
||||||
|
|
||||||
;; A #define keeps its value forms -- there can be more than one.
|
;; A #define keeps its value forms -- there can be more than one.
|
||||||
(add-define 't-maxn '(define t-maxn 8))
|
(add-define 't-maxn '(define t-maxn 8))
|
||||||
(test "defines are recorded"
|
(test "defines are recorded"
|
||||||
@@ -142,10 +71,6 @@
|
|||||||
(test "enum values are fields whose type is the enum"
|
(test "enum values are fields whose type is the enum"
|
||||||
'((red (enum t-color)) (green (enum t-color)) (blue (enum t-color)))
|
'((red (enum t-color)) (green (enum t-color)) (blue (enum t-color)))
|
||||||
(map-fields 't-color (lambda (name type) (list name type))))
|
(map-fields 't-color (lambda (name type) (list name type))))
|
||||||
(add-enum 't-wire '(enum t-wire ((t-varint 0) (t-fixed64 1) t-bytes)))
|
|
||||||
(test "an enumerator with a value is still named by its name"
|
|
||||||
'(t-varint t-fixed64 t-bytes)
|
|
||||||
(map-fields 't-wire (lambda (name type) name)))
|
|
||||||
(test "a typedef has no fields to map"
|
(test "a typedef has no fields to map"
|
||||||
#f
|
#f
|
||||||
(map-fields 't-u8 (lambda (name type) name)))
|
(map-fields 't-u8 (lambda (name type) name)))
|
||||||
@@ -173,75 +98,9 @@
|
|||||||
#f
|
#f
|
||||||
(type-match 'float (int 'yes)))
|
(type-match 'float (int 'yes)))
|
||||||
|
|
||||||
;; `_' in a pattern matches anything in that position; written last it
|
|
||||||
;; takes the rest, since a type's words are spread and not nested
|
|
||||||
(test "a wildcard matches an atom"
|
|
||||||
'yes (type-match 'int (_ 'yes) (else 'no)))
|
|
||||||
(test "a pointer to anything"
|
|
||||||
'yes (type-match '(* int) ((* _) 'yes) (else 'no)))
|
|
||||||
(test "including one spelled with qualifiers"
|
|
||||||
'yes (type-match '(* const char) ((* _) 'yes) (else 'no)))
|
|
||||||
(test "an array of anything, any length"
|
|
||||||
'yes (type-match '(¤ int 4) ((¤ _ _) 'yes) (else 'no)))
|
|
||||||
(test "but a sized pattern does not match an unsized array"
|
|
||||||
'no (type-match '(¤ int) ((¤ _ _) 'yes) (else 'no)))
|
|
||||||
(test "an aggregate of any tag"
|
|
||||||
'yes (type-match '(struct point) ((struct _) 'yes) (else 'no)))
|
|
||||||
(test "and the keyword still has to agree"
|
|
||||||
'no (type-match '(union point) ((struct _) 'yes) (else 'no)))
|
|
||||||
(test "a function of any signature"
|
|
||||||
'yes (type-match '(fn ((float)) int) ((fn _ _) 'yes) (else 'no)))
|
|
||||||
(test "an exact pattern is still exact"
|
|
||||||
'no (type-match '(* int) ((* const char) 'yes) (else 'no)))
|
|
||||||
|
|
||||||
(test "an undeclared name has no entry"
|
(test "an undeclared name has no entry"
|
||||||
#f
|
#f
|
||||||
(get-type-info 't-never-declared))
|
(get-type-info 't-never-declared))
|
||||||
(test "and no fields"
|
(test "and no fields"
|
||||||
#f
|
#f
|
||||||
(get-fields 't-never-declared))
|
(get-fields 't-never-declared)))
|
||||||
|
|
||||||
;; What type a *name* has -- the third table, which functions and
|
|
||||||
;; variables share because a function type has a surface spelling
|
|
||||||
(add-name-type! 't-sum '(fn ((int) (int)) int))
|
|
||||||
(add-name-type! 't-origin '(struct t-point))
|
|
||||||
(test "a function's signature comes back whole"
|
|
||||||
'(fn ((int) (int)) int)
|
|
||||||
(get-name-type 't-sum))
|
|
||||||
(test "and a variable's type"
|
|
||||||
'(struct t-point)
|
|
||||||
(get-name-type 't-origin))
|
|
||||||
(test "the return type is what a call site wants"
|
|
||||||
'int
|
|
||||||
(get-return-type 't-sum))
|
|
||||||
(test "a variable has no return type"
|
|
||||||
#f
|
|
||||||
(get-return-type 't-origin))
|
|
||||||
;; not an error: this is how a name from an included C header looks,
|
|
||||||
;; and the caller decides what to make of it
|
|
||||||
(test "an undeclared name has no type"
|
|
||||||
#f
|
|
||||||
(get-name-type 't-never-declared))
|
|
||||||
(test "nor a return type"
|
|
||||||
#f
|
|
||||||
(get-return-type 't-never-declared))
|
|
||||||
|
|
||||||
;; Where an array's element type ends is a matter of shape, not of
|
|
||||||
;; what the database happens to hold: a typedef from a C header is
|
|
||||||
;; never in it
|
|
||||||
(test-group "array bounds"
|
|
||||||
(test-assert "a number" (array-bound? '(¤ int 4)))
|
|
||||||
(test-assert "a name after a specifier" (array-bound? '(¤ int N)))
|
|
||||||
(test-assert "a name after a type name unknown to Sex"
|
|
||||||
(array-bound? '(¤ pthread-t N)))
|
|
||||||
(test-assert "a name after a grouped type"
|
|
||||||
(array-bound? '(¤ (* t-point) N)))
|
|
||||||
(test-assert "a name after a tag" (array-bound? '(¤ struct t-point N)))
|
|
||||||
(test-assert "not a lone type" (not (array-bound? '(¤ pthread-t))))
|
|
||||||
(test-assert "not a specifier" (not (array-bound? '(¤ unsigned int))))
|
|
||||||
(test-assert "not a qualified name" (not (array-bound? '(¤ const t))))
|
|
||||||
(test-assert "not a pointer's target" (not (array-bound? '(¤ * size-t))))
|
|
||||||
(test-assert "not a tag" (not (array-bound? '(¤ struct t-point))))
|
|
||||||
(test "the element of a grouped type is the group"
|
|
||||||
'(* t-point)
|
|
||||||
(array-element-type '(¤ (* t-point) N)))))
|
|
||||||
|
|||||||
3
tests/utils.module.scm
Normal file
3
tests/utils.module.scm
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
(module utils
|
||||||
|
*
|
||||||
|
"../utils.scm")
|
||||||
@@ -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))
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user