Compare commits

..

10 Commits

Author SHA1 Message Date
Pavel Kulyov
e2f71d23a0 emacs: load the server beside sex-mode
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m54s
2026-11-15 00:06:41 +03:00
Pavel Kulyov
0aef571f68 serve the index over LSP
sex-lsp answers:
- hover,
- definition,
- completion,
- symbols,
- diagnostics.

--expand-lines and sex/expand return the C for a line
range. clangd is off unless --c-backend=clangd, and it is asked about
names the compiler never parsed.
2026-11-15 00:06:41 +03:00
Pavel Kulyov
7bbb8e19ac index a unit past its first bad form
Record plain declarations, with location and docstring, and keep going
when one toplevel form is wrong. sexc --check and --symbols print
that. Specs, realizations, and closure helpers stay out of the index
for future rework (@alex-eg).
2026-11-15 00:06:35 +03:00
5e842c4df6 sex-mode: drop the closure keyword
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m28s
Sex CI / build-linux (push) Successful in 5m26s
The compiler no longer has it.
2026-11-11 09:17:58 +03:00
be2f4e407b remove closures, keep lambdas
A closure was a code pointer beside an inline environment: capture
records, per-signature structs, conversion thunks and call helpers. It
is gone; a lambda still lifts to an ordinary function and a (fn ...)
value is still a bare code pointer. The capture budget, the environment
union and the closure glyph go with it.

The implementation is kept at tag 0.0.1.
2026-11-11 09:17:54 +03:00
ad37a2492e sex-mode: drop spec and realize keywords
The compiler no longer has them.
2026-11-11 08:54:31 +03:00
2c78756e61 remove spec and realize
They were too much surface for a language this small: a nominal
contract layer, per-type default synthesis and a pub interface of their
own. Type introspection and macros are the intended replacement, so the
storage, the forms and the tests that pin them go; the ops method
registry they leaned on stays.

The implementation is kept at tag 0.0.1.
2026-11-11 08:54:29 +03:00
Pavel Kulyov
7315694faf sex-mode: add supported keywords, drop chicken-*
All checks were successful
Sex CI / build-linux (pull_request) Successful in 5m59s
Sex CI / build-linux (push) Successful in 5m42s
2026-10-30 00:07:43 +03:00
Pavel Kulyov
1214d118e1 readme: add sex-mode.el installation via quelpa 2026-10-29 23:57:50 +03:00
Pavel Kulyov
13be48093b sex-mode: add header and footer, fix lint errors
That makes the package installable via quelpa.
2026-10-29 23:57:45 +03:00
37 changed files with 2325 additions and 1675 deletions

1
.gitignore vendored
View File

@@ -10,6 +10,7 @@
/sexc
/sex-tests
/sextest
/sex-lsp
# Scrapped design docs, kept for reference
/attic

View File

@@ -38,7 +38,7 @@ all: sexc
include eggs.mk
# Each program, and the source it is built from
PROGRAMS = sexc=main.scm sextest=tools/sextest/sextest.scm sex-tests=tests/run.scm
PROGRAMS = sexc=main.scm sextest=tools/sextest/sextest.scm sex-tests=tests/run.scm sex-lsp=sex-lsp.scm
PROGRAM_NAMES = $(foreach p,$(PROGRAMS),$(firstword $(subst =, ,$(p))))
PROGRAM_OBJ = $(foreach p,$(PROGRAMS),$(patsubst %.scm,%.o,$(lastword $(subst =, ,$(p)))))
@@ -85,7 +85,7 @@ $(PROGRAM_NAMES):
# they import
SEX_TEST_PROGRAMS = $(wildcard tests/sex-programs/*.sex)
check run-tests: sexc sex-tests sextest
check run-tests: sexc sex-tests sextest sex-lsp
./sex-tests
./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS)
@$(MAKE) --no-print-directory check-modules
@@ -98,6 +98,7 @@ check-modules check-exit-code check-command-line: check-%: sexc
install: all installdirs
$(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc
$(INSTALL_PROGRAM) sex-lsp $(DESTDIR)$(bindir)/sex-lsp
$(INSTALL_DATA) $(SEX_LIB) $(DESTDIR)$(sexlibdir)
install-strip:
@@ -107,7 +108,7 @@ installdirs:
$(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(sexlibdir)
uninstall:
rm -f $(DESTDIR)$(bindir)/sexc
rm -f $(DESTDIR)$(bindir)/sexc $(DESTDIR)$(bindir)/sex-lsp
rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%)
-rmdir $(DESTDIR)$(sexlibdir)

View File

@@ -123,6 +123,23 @@ Alex
Hello, Alex!
#+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
** Full C interoperability
Just ~(include "Your/Favourite/Library.h")~ and use it as you would
@@ -317,8 +334,23 @@ best option.
*** sex-mode.el
To harness the power of sex-mode, add the following lines to your
~$HOME/.config/emacs/init.el~:
#+begin_src emacs-lisp
(use-package sex-mode
:load-path "/path/to/sex"
:mode ("\\.sex\\'"))
(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 . eglot-ensure) ; if you use eglot
:hook (sex-mode . lsp-deferred) ; if you use lsp-mode
:config (require 'sex-lsp))
#+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.

View File

@@ -1 +1 @@
fmt getopt-long brev-separate test srfi-1 srfi-13 srfi-69 matchable
fmt getopt-long brev-separate test srfi-1 srfi-13 srfi-69 matchable medea

View File

@@ -1,8 +1,12 @@
(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")

View File

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

View File

@@ -134,7 +134,7 @@ forms, and what remains."
;;; because the compiler composes these names and the user does not: a
;;; hand-written vec2__length would collide, and an identifier holding
;;; `__' is reserved in C++, which a pub header may be included from.
;;; Lifted closures carry a ƛ for the same reason.
;;; 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

View File

@@ -21,6 +21,7 @@
(chicken module)
(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)
@@ -28,6 +29,7 @@
(export
read-from-file
read-raw-forms
read-sex-string
current-features
platform-features
@@ -613,3 +615,9 @@
(parameterize ((current-source-file "stdin"))
(parse-all (current-input-port)))
(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))))

808
semen.scm

File diff suppressed because it is too large Load Diff

178
sex-lsp.el Normal file
View File

@@ -0,0 +1,178 @@
;;; 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 Normal file
View File

@@ -0,0 +1,889 @@
;;; 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)

View File

@@ -16,7 +16,8 @@
apply-macro
defmacro
macro-definition
restore-macro!)
restore-macro!
reset-macros!)
(define (cat-syms s-1 s-2)
(fmt #f s-1 s-2))
@@ -30,7 +31,15 @@
(define (comment . _)
(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)
(note-macro-name! name)
(put! name 'sex-macro
`(lambda ,arglist
;; A macro body is ordinary Scheme, evaluated at compile
@@ -46,10 +55,7 @@
get-underlying-type type-match type-pattern-matches?
map-fields
get-name-type get-return-type type-of
;; what a generic asks before it expands:
;; (realizes? 'ord type) beats a wall of C
;; errors two stages downstream
realizes? get-method))
get-method))
,@body)))
(define (get-macro name)
@@ -99,9 +105,14 @@
(define (restore-macro! name definition)
(if definition
(put! name 'sex-macro 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)
(let ((arglist (car form))
(body (cdr form)))

View File

@@ -1,8 +1,44 @@
;;; 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)
(defgroup sex-mode nil
"Major mode for Sex code."
:prefix 'sex-
:prefix "sex-"
:group 'languages)
(define-abbrev-table 'sex-mode-abbrev-table ()
@@ -11,8 +47,8 @@ It has `scheme-mode-abbrev-table' as its parent."
:parents (list scheme-mode-abbrev-table))
(defvar sex-mode-syntax-table
(let ((table (make-syntax-table lisp-data-mode-syntax-table)))
table))
(make-syntax-table lisp-data-mode-syntax-table)
"Syntax table used in Sex mode.")
(defvar sex-mode-map
(let ((map (make-sparse-keymap)))
@@ -21,58 +57,72 @@ It has `scheme-mode-abbrev-table' as its parent."
"Keymap for Sex mode.
All commands in `lisp-mode-shared-map' are inherited by this map.")
(defvar sex-mode-line-process "")
(defvar sex-mode-line-process ""
"Mode-line process string for Sex mode.")
(defconst sex-font-lock-keywords
(eval-when-compile
(list
;; Declarations
;; Declarations. `pub' and `extern' are optional prefixes, so
;; `(pub fn main' highlights both keywords and the name.
(list (concat "("
(regexp-opt '("chicken-define"
"chicken-define-syntax"
"chicken-import"
"chicken-load"
"define"
"\\(?:\\(pub\\|extern\\)[[:space:]]+\\)?"
(regexp-opt '("define"
"defmacro"
"extern"
"enum"
"fn"
"import"
"include"
"fn"
"ops"
"pub"
"record"
"realize"
"spec"
"struct"
"sum"
"var"
"union")
'word)
"\\>"
"typedef"
"union"
"var")
'words)
"[[:space:]]*"
"\\([[:word:]]*\\)")
'(1 font-lock-keyword-face)
'(2 font-lock-function-name-face))
;; Keywords
'(1 font-lock-keyword-face nil t)
'(2 font-lock-keyword-face)
'(3 font-lock-function-name-face nil t))
;; Statement and expression heads, plus the macro-language forms
;; that appear in `defmacro' bodies.
(list (concat "("
(regexp-opt '(
"do"
(regexp-opt '("break"
"c-bit-or"
"c-bit-or="
"c-or"
"case"
"case/fallthrough"
"cast"
"continue"
"default"
"do"
"if"
"else"
"for"
"get-method"
"goto"
"if"
"lambda"
"map-fields"
"match"
"return"
"sizeof"
"static-assert"
"switch"
"var"
"while")
'word)
"\\>")
'(1 'font-lock-builtin-face)))))
"type-match"
"type-of"
"while"
"$"
"."
":")
'words))
'(1 font-lock-builtin-face))))
"Font-lock keywords for Sex mode.")
(defun sex-mode-set-variables ()
"Set up buffer-local variables for Sex mode."
(set-syntax-table sex-mode-syntax-table)
(setq local-abbrev-table sex-mode-abbrev-table)
(setq mode-line-process '("" sex-mode-line-process))
@@ -89,8 +139,6 @@ All commands in `lisp-mode-shared-map' are inherited by this map.")
(put 'defmacro 'lisp-indent-function 'defun)
(put 'record 'lisp-indent-function 'defun)
(put 'sum 'lisp-indent-function 'defun)
(put 'spec 'lisp-indent-function 'defun)
(put 'realize 'lisp-indent-function 'defun)
(put 'ops 'lisp-indent-function 'defun)
(put 'match 'lisp-indent-function 1)
(put 'struct 'lisp-indent-function 'defun)
@@ -113,6 +161,8 @@ Blank lines separate paragraphs. Semicolons start comments.
(sex-mode-set-variables))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.\\(sex\\|hsex\\)\\'" . sex-mode))
(add-to-list 'auto-mode-alist '("\\.sex\\'" . sex-mode))
(provide 'sex-mode)
;;; sex-mode.el ends here

View File

@@ -21,7 +21,8 @@
load-persistent-module-paths
check-public-interface
module-dependencies
read-public-interface)
read-public-interface
reset-modules!)
(define +persistent-module-paths+ (list))
@@ -35,6 +36,14 @@
(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:
;; For each module IMPORT-FORM names, construct path, find module by
@@ -270,7 +279,6 @@
(fold
(lambda (form acc)
(check-written-out form)
(check-realized-spec form visible hidden)
(fold (lambda (use acc) (check-type-use form use visible hidden acc))
acc
(append-map (lambda (type) (type-uses type #f))
@@ -292,22 +300,6 @@
(_ #f)))
(_ #f)))
;;; A pub realization goes to importers, who look its spec up; one they
;;; cannot see failed there, in whichever named this module before the
;;; spec's, and said nothing of where it was written
(define (check-realized-spec form visible hidden)
(match form
(('pub 'realize ((? symbol? spec) _) . _)
(let ((kept (assq spec hidden)))
(when (and kept (not (assq spec visible)))
(sex-error form
(string-append "importers cannot see this spec; "
(if (fourth kept)
"import its module with pub"
"make it pub"))
spec))))
(_ #f)))
;;; USE is (name . behind-a-pointer?)
(define (check-type-use form use visible hidden acc)
(let* ((name (car use))
@@ -363,9 +355,6 @@
(remove comment-form? variants)))
(('ops type . methods)
(append-map interface-types (filter pub-form? methods)))
(('pub 'realize spec . methods)
(append-map (lambda (m) (interface-types (cons 'pub m)))
(remove comment-form? methods)))
(_ (list))))
(define (field-types fields)
@@ -392,7 +381,7 @@
((¤) (let ((element (array-element-type type)))
(append (if element (type-uses element behind?) (list))
(if (array-bound? type) (bound-uses (array-bound type)) (list)))))
((fn closure)
((fn)
(if (and (pair? (cdr type)) (list? (second type)))
(append-map (lambda (t) (type-uses t #f))
(signature-types (second type) (last type)))
@@ -409,24 +398,23 @@
((pair? bound) (append-map bound-uses (cdr bound)))
(else (list))))
;;; The types, constants and specs FORMS declare, as (name kind body?):
;;; 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)
;;; (spec (shown T) ...) -> (shown spec #t)
(define (declared-types forms)
(filter-map
(lambda (form)
(and (pair? form)
(let* ((core (strip-pub form))
(name (and (pair? core) (pair? (cdr core))
(if (and (memq (car core) '(define spec))
(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 spec))
'(record struct union enum sum typedef define))
(symbol? name)
(list name
(car core)
@@ -520,19 +508,6 @@
(copy-form-source! form
`(ops ,type ,@(map public-fn-interface methods))))))
;;; A realization leaves with the methods written in it, reduced to
;;; prototypes. Its defaults do not travel: the importer synthesizes
;;; its own static copies from the spec, which is why a default is
;;; static even when the realization is pub.
(define (realize-public-interface form)
(let ((core (cdr form)))
(copy-form-source!
form
`(pub realize ,(second core)
;; pub goes back on at the realize, not on its methods
,@(map (lambda (m) (cdr (public-fn-interface (cons 'pub m))))
(remove comment-form? (cddr core)))))))
;;; TODO: use semen facilities to analyze modules
(define (process-public-interface-form form acc)
(match form
@@ -543,13 +518,11 @@
(('pub 'var . _)
(match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
(cons (copy-form-source! form `(extern var ,name ,type)) acc)))
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'spec 'struct 'sum 'typedef 'union) . _)
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc))
(('ops . _)
(let ((exported (ops-public-interface form)))
(if exported (cons exported acc) acc)))
(('pub 'realize . _)
(cons (realize-public-interface form) acc))
(('pub . _)
(sex-error form "pub must be followed by a definition" form))
(_ acc)))

426
sex-query.scm Normal file
View File

@@ -0,0 +1,426 @@
;;; 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))))

View File

@@ -17,6 +17,7 @@
getopt-long
sex-macros
sex-modules
sex-query
reader
semen
srfi-1 ; list routines
@@ -80,6 +81,19 @@
(pad padding) "land on the right source line; `none' is for reading -C" nl
(pad padding) "output by eye")
(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)))))
(define (print-help)
@@ -169,7 +183,7 @@
;;; 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)))
'(emit-c macro-expand public-interface check symbols expand-lines)))
(define (write-to-file-or-stdout output what)
(if (stdout-output? output)
@@ -251,28 +265,43 @@ status, which is ours to pass on."
(mark-imported! (to-absolute-pathname input-source)))
(let ((process (lambda ()
(check-public-interface unit-forms)
(semen-process (append prelude unit-forms)))))
(semen-process (append (compiler-prelude) unit-forms)))))
(if (eq? input-source 'stdin)
(process)
(with-directory input-source (process)))))
(define prelude
(append
'((include inttypes.h)
(include stdbool.h)
(include stddef.h) ; max_align_t, for closure environments
(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))
;; The closure environment is the part of the ABI, so include it in
;; every module
(list (closure-env-declaration))))
;;; Query output. C from --expand-lines owns stdout; diagnostics and the
;;; symbol table go beside it on stderr so a slice stays valid text.
;;; On their own they are the stdout of the command.
(define (report-query analysis args output)
(let* ((expanding? (get-arg args 'expand-lines #f))
(want-check? (get-arg args 'check #f))
(want-symbols? (get-arg args 'symbols #f))
(range (and expanding? (parse-expand-lines expanding?))))
;; A reader failure is the one non-zero status. Say what it was,
;; on stdout for --check and on stderr when stdout is C.
(unless (analysis-read? analysis)
(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
@@ -312,7 +341,7 @@ status, which is ours to pass on."
(print-help)
(return #f))
(when (and (equal? output "-") (not (text-output? args)))
(error "-o - is stdout, which takes only -C, -m or --public-interface"))
(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)))
@@ -329,6 +358,15 @@ status, which is ours to pass on."
;; 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)
(assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument")

View File

@@ -474,52 +474,12 @@
(not (emits? (in-fn "(static-assert (== (sizeof int) 4) \"x\")")
"static_assert("))))
;; A closure is a code pointer beside its captures. The struct is
;; named from the signature, so separate translation units agree on
;; it, and calling one goes through `code' with `env' passed first.
;;
;; A closure struct, and the helper its calls go through, are each
;; emitted once per signature; the registries deciding that are
;; compile-time state like the type databases, and outlive a single
;; `sex->c' here. So every case below that looks for a *definition*
;; uses a signature of its own -- cases looking at a call site can
;; share one.
(test-group "closures"
(test-assert "the type becomes a struct named for its signature"
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"struct ƛint_int"))
;; captures are a closure's other parameters, under C's rule for
;; those: no two alike, and none redeclared at the body's top level.
;; Both were C's redefinition errors
;; ((+ a 1)) was a capture named `+', holding a
(test-assert "a capture is a name, or a name and a value"
(reports? (in-fn "(var c (closure () int) (closure () int ((+ a 1)) (return 1)))")
"a capture is a name, or (name value)"))
(test-assert "a capture named like a parameter is refused"
(reports? (in-fn "(var c (closure ((int)) int) (closure ((a int)) int (a) (return a)))")
"a capture and a parameter share a name"))
(test-assert "so is one captured twice"
(reports? (in-fn "(var c (closure () int) (closure () int (a a) (return a)))")
"two captures share a name"))
(test-assert "so is one redeclared at the top of the body"
(reports? (in-fn "(var c (closure () int) (closure () int (a) (var a int 5) (return a)))")
"the body redeclares a capture"))
(test-assert "while a block inside may shadow it"
(emits? (in-fn "(var c (closure () int) (closure () int (a) (do (var a int 5) (g a)) (return a)))")
"int a = 5;"))
;; the closure's type was built from each parameter's second element,
;; which a type alone has none of
(test-assert "a parameter may name nothing"
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
"struct ƛint__int"))
(test-assert "and its code names it, a definition needing one before C23"
(emits? (in-fn "(var c (closure ((int) (int)) int) (closure ((int) (b int)) int () (return b)))")
"int ƛu0, int b)"))
;; a definition names every parameter before C23, a lambda's as a
;; closure's code does
(test-group "lambdas"
;; a definition names every parameter before C23, so one written as a
;; type alone gets a name nothing reads
(test-assert "a lambda's unnamed parameter is named in its definition"
(emits? "(fn f () void (var g (fn ((int) (int)) int) (lambda ((int) (b int)) int (return b))))"
"λ0_f (int ƛu0, int b)"))
"λ0_f (int λu0, int b)"))
(test-assert "and a variadic one keeps its ..."
(emits? "(fn f () void (var g (fn ((int) ...) int) (lambda ((n int) ...) int (return n))))"
"λ0_f (int n, ...)"))
@@ -527,120 +487,7 @@
;; nothing defined it
(test-assert "an empty lambda is an empty function"
(emits? "(fn f () void (var g (fn () void) (lambda () void)))"
"static void λ0_f (void) {}"))
(test-assert "so is an empty closure's code"
(emits? (in-fn "(var c (closure () void) (closure () void ()))") "(void * ƛe) {}"))
;; the call helper would have to forward the rest, which C cannot
(test-assert "a closure cannot be variadic"
(reports? (in-fn "(var c _ (closure ((n int) ...) int () (return n)))")
"a closure cannot be variadic; a lambda can"))
;; The environment is one shared union, declared in the prelude --
;; its layout is part of the ABI two units agree on, so it cannot
;; depend on what either file contains. `sex->c' has no prelude, so
;; what is visible here is the member
(test-assert "whose environment is the shared union"
(emits? "(fn f ((c (closure ((float)) int))) int (return (c 1.0)))"
"union ƛenv env;"))
;; The receiver goes through a helper rather than being written
;; out twice, so that `[table (++ i)]' evaluates its index once,
;; exactly as it would for an array of function pointers
(test-assert "a call passes the receiver to a helper"
(emits? "(fn f ((c (closure ((int)) int))) int (return (c 1)))"
"ƛint_int_call(c, 1)"))
(test-assert "and the helper is what dereferences it"
(emits? "(fn f ((c (closure ((long)) int))) int (return (c 1)))"
"ƛc.code(&ƛc.env, ƛa0)"))
(test-assert "a subscript receiver is evaluated once"
(emits? "(fn f ((t [(closure ((int)) int) 4]) (i int)) int (return ([t (++ i)] 1)))"
"ƛint_int_call(t[++i], 1)"))
(test-assert "so is a member receiver"
(emits? "(struct h ((cb (closure ((int)) int))))
(fn f ((s (struct h))) int (return ((. s cb) 1)))"
"ƛint_int_call(s.cb, 1)"))
(test-assert "a captured name is rebound in the lifted body"
(emits? "(fn f ((n int)) (closure ((char)) int) (return (closure ((x char)) int (n) (return n))))"
"int n = ƛcaptures->n;"))
(test-assert "captures are checked against the environment"
(emits? "(fn f ((n int)) (closure ((short)) int) (return (closure ((x short)) int (n) (return n))))"
"_Static_assert(sizeof(struct"))
;; A closure over nothing has no record to point at, and C has no
;; empty struct to declare for it
(test-assert "no captures means no capture record"
(not (emits? "(fn f () (closure () int) (return (closure () int () (return 7))))"
"_captures {")))
;; `(name expr)' names a capture and gives what it holds, so the
;; expression is evaluated once, where the closure is written
(test-assert "a named capture takes its type from the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"int sum;"))
(test-assert "and the constructor is handed the expression"
(emits? "(struct p ((x int) (y int)))
(fn f ((s (struct p))) (closure () int)
(return (closure () int ((sum (+ (. s x) (. s y)))) (return sum))))"
"_make(s.x + s.y)"))
(test-assert "capturing a pointer is how by-reference is spelled"
(emits? "(struct p ((x int)))
(fn f ((s (* (struct p)))) (closure () int)
(return (closure () int ((q s)) (return (-> q x)))))"
"struct p* q;"))
;; A bare function is a closure that captures nothing, so it
;; converts wherever one is expected -- the pointer goes in the
;; environment and one thunk per signature reads it back out
(test-assert "a named function in a var initializer"
(emits? "(fn g ((n int)) int (return n))
(fn f () void (var c (closure ((int)) int) g))"
"ƛint_int_fromfn(g)"))
(test-assert "a lambda, which is a bare function too"
(emits? "(fn f () void (var c (closure ((int)) int)
(lambda ((n int)) int (return n))))"
"ƛint_int_fromfn(λ0_f)"))
(test-assert "an argument, against the parameter that signature wrote"
(emits? "(fn g ((n int)) int (return n))
(fn h ((c (closure ((int)) int))) int (return (c 1)))
(fn f () int (return (h g)))"
"h(ƛint_int_fromfn(g))"))
(test-assert "a return, against the declared return type"
(emits? "(fn g ((n int)) int (return n))
(fn f () (closure ((int)) int) (return g))"
"return ƛint_int_fromfn(g)"))
(test-assert "the thunk reads the pointer out of the environment"
(emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((float)) int) g))"
"return ƛcaptures->f(ƛa0)"))
;; a signature that does not match is left alone, and C rejects it
(test-assert "a function of the wrong signature does not convert"
(not (emits? "(fn g ((n float)) int (return 1))
(fn f () void (var c (closure ((int)) int) g))"
"_fromfn(g)")))
;; a closure is lifted into the function it was written in, so
;; there has to be one
(test-assert "a closure at toplevel is refused"
(reports? "(var c (closure () int) (closure () int () (return 1)))"
"only be written inside a function"))
(test-assert "and so is one in a struct field"
(reports? "(struct s ((f (closure () int) (closure () int () (return 1)))))"
"only be written inside a function"))
;; A block opens a scope, so what it declares ends with it
(test-assert "a name shadowed in a block does not escape it"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"ƛvoid_int_call(c)"))
(test-assert "and the shadowing declaration is what the block sees"
(emits? "(fn mk () (closure () int) (return (closure () int () (return 1))))
(fn f () int (var c (closure () int) (mk))
(do (var c int 9) (g c))
(return (c)))"
"g(c)"))
;; The receiver is written twice, so a name used as an argument
;; must not be mistaken for a call of its own
(test-assert "a closure passed as an argument stays a value"
(emits? "(fn g ((c (closure ((int)) int))) int (return 0))
(fn f ((c (closure ((int)) int))) int (return (g c)))"
"g(c)")))
"static void λ0_f (void) {}")))
;; An include target is a path, so none of the identifier mangling
;; applies to it: GL/gl.h is a file and GLːgl.h is not.
@@ -696,16 +543,16 @@
(defmacro (t x) (type-match (type-of x) (float 1) (else 0)))
(fn f () int (return (t (g))))"
"return 1;"))
;; a macro is shown the written spelling, not the generated struct
(test-assert "a closure, spelled the way it was written"
(emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(defmacro (t x) (type-match (type-of x) ((closure _ _) 1) (else 0)))
;; a macro is shown the written spelling, not a generated name
(test-assert "a function pointer, spelled the way it was written"
(emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(defmacro (t x) (type-match (type-of x) ((fn _ _) 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t c)))"
"return 1;"))
(test-assert "and calling one has the closure's return type"
(emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(test-assert "and calling one has the function's return type"
(emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(defmacro (t x) (type-match (type-of x) (int 1) (else 0)))
(fn f () int (var c _ (mk)) (return (t (c 1))))"
"return 1;"))
@@ -786,9 +633,6 @@
(test-assert "a lambda's as well"
(reports? (in-fn "(var l (fn ((int)) int) (lambda ((x _)) int (return x)))")
"a function's types are written out"))
(test-assert "and a closure's"
(reports? (in-fn "(var c (closure ((int)) int) (closure ((x int)) _ () (return x)))")
"a function's types are written out"))
;; a call was typed by asking the global table what a function of
;; that name returns, which a local pointer is not
;; a value if had no rule either: it is the join of its values
@@ -820,13 +664,6 @@
(emits? (string-append "(struct ops ((op (fn ((int)) float))))"
"(fn f ((o (struct ops))) void (var r _ ((. o op) 1)))")
"float r = o.op(1)"))
(test-assert "a closure's call, which goes through a helper nothing typed"
(emits? "(fn f ((c (closure ((int)) int))) void (var r _ (c 4)))"
"int r = ƛint_int_call(c, 4)"))
(test-assert "and one returning a closure is called as one"
(emits? (string-append "(fn mk ((k int)) (closure ((int)) int) (return (closure ((b int)) int (k) (return (+ k b)))))"
"(fn f () void (var fp (fn ((int)) (closure ((int)) int)) mk) (var r _ ((fp 3) 4)))")
"int r = ƛint_int_call(fp(3), 4)"))
(test-assert "while a function is the pointer it already is"
(emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))"
"int (*p)(int) = g"))
@@ -879,18 +716,17 @@
(emits? (in-fn "(var t [_ 10] #(1 2))") "int t[10] = {1, 2}"))
(test-assert "and they have to agree with each other"
(reports? (in-fn "(var t [_ 2] #(1 \"s\"))") "type mismatch"))
;; a closure type reaches the solver as the struct that stands for
;; it, which is the spelling `parse-type' knows
(test-assert "a closure, from the signature that produced it"
(emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
;; a function pointer type reaches the solver as itself
(test-assert "a lambda, from the signature that produced it"
(emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(fn f () void (var c _ (mk)))"
"struct ƛint_int c = mk()"))
"int (*c)(int) = mk()"))
(test-assert "and it is callable once inferred"
(emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(fn f () int (var c _ (mk)) (return (c 1)))"
"ƛint_int_call(c, 1)"))
"return c(1)"))
;; C's usual arithmetic conversions, far enough to answer `_'
(test-assert "floating beats integral"
(emits? (in-fn "(var d double 1.0) (var x _ (+ a d))") "double x = a + d"))
@@ -964,16 +800,16 @@
;; without `$' a list is one form, so a head that is itself a form
;; stays a call rather than becoming two statements
(test-assert "a computed callee stays one form"
(emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))"
"ƛint_int_call(mk(), 5)"))
"mk()(5)"))
;; spliced, it would have become two forms in the `return' -- the
;; comma operator, and the wrong answer
(test-assert "rather than two forms in its context"
(not (emits? "(fn mk () (closure ((int)) int)
(return (closure ((b int)) int () (return b))))
(not (emits? "(fn mk () (fn ((int)) int)
(return (lambda ((b int)) int (return b))))
(defmacro (apply-it x) `((mk) ,x))
(fn f () int (return (apply-it 5)))"
"return mk(), 5"))))

View File

@@ -42,16 +42,6 @@ ahead of its pub forms."
"(fn f () void (var s shape (shape/circle 1.0)) (var out float 0.0) "
(apply string-append body) ")"))
(define (spec-src . body)
(string-append
"(record v ((x int)))"
"(spec (p T)"
" (fn s ((self (* const T))) void)"
" (fn both ((self (* const T))) void (.s self)))"
"(realize (p v)"
" (fn s ((self (* const v))) void (return)))"
(apply string-append body)))
(test-group "encapsulation"
;; A record is a struct plus a typedef of its own name, so the bare
@@ -279,12 +269,12 @@ ahead of its pub forms."
(reports? "(sum box ((inner ((x [box 2])))))" "a sum holds itself through a pointer"))
(test-assert "though it can point at itself"
(emits? "(sum box ((inner ((x (* box))))))" "box * x;"))
(test-assert "a function argument becomes the closure its field holds"
(test-assert "a function fills a function-pointer field"
(emits? (string-append
"(fn g ((n int)) int (return n))"
"(sum t ((a ((k (closure ((int)) int))))))"
"(sum t ((a ((k (fn ((int)) int))))))"
"(fn f () t (return (t/a g)))")
"ƛint_int_fromfn(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"
@@ -296,104 +286,6 @@ ahead of its pub forms."
(test-assert "and is declared once"
(reports? "(sum t ((a ((x int))) (a ())))" "variant is declared twice")))
;; A spec is a contract that emits nothing; a realization is its
;; methods for one type. The refusals are what make it a contract.
(test-group "spec and realize"
(test-assert "a spec on its own emits nothing"
(not (emits? "(spec (p T) (fn s ((a (* const T))) void))" "p")))
(test-assert "a realization mangles type, spec and method"
(emits? (spec-src "") "void vːpːs"))
(test-assert "a default is copied per realizing type"
(emits? (spec-src "") "vːpːboth"))
(test-assert "and its parameter is substituted"
(emits? (spec-src "") "void vːpːboth (const v * self)"))
(test-assert "a default calls that type's own required method"
(emits? (spec-src "") "vːpːs(self)"))
(test-assert "a default is static even when the realization is pub"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn d ((a (* const T))) void (.s a)))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːd"))
(test-assert "but a written method is not"
(not (emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(pub realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"static void vːpːs")))
(test-assert "a spec method answers to .method"
(emits? (spec-src "(fn f () void (var a v #(v : 1)) (.s (& a)))") "vːpːs(&a)"))
(test-assert "a spec is declared once"
(reports? "(spec (p T) (fn s ((a T)) void))(spec (p T) (fn q ((a T)) void))"
"spec is already declared"))
(test-assert "a typedef realizes what its type does"
(reports? (string-append (spec-src "") "(typedef alias v)(realize (p alias))")
"spec is already realized for"))
(test-assert "a type realizes a spec once"
(reports? (string-append (spec-src "") "(realize (p v)"
" (fn s ((a (* const v))) void (return)))")
"spec is already realized for"))
(test-assert "a realization names a spec that exists"
(reports? "(record v ((x int)))(realize (nope v))" "no such spec"))
(test-assert "every required method is provided"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"realization is missing a method of"))
(test-assert "and the missing one is named"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void)"
" (fn q ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"q"))
(test-assert "a docstring is not a body"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void \"doc\"))"
"(realize (p v))")
"realization is missing a method of"))
(test-assert "nor is a comment"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) int\n"
" ;; must be implemented\n"
" ))"
"(realize (p v))")
"realization is missing a method of"))
(test-assert "a documented default is still a default"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) int \"doc\" (return 1)))"
"(realize (p v))")
"/* doc */"))
(test-assert "a method the spec has not got is refused"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return))"
" (fn z ((a (* const v))) void (return)))")
"spec has no such method"))
(test-assert "a return type has to match the spec"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) int (return 1)))")
"return type does not match"))
(test-assert "so do the arguments"
(reports? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a v)) void (return)))")
"arguments do not match"))
(test-assert "but not on how a pointer is spelled"
(emits? (string-append "(record v ((x int)))"
"(spec (p T) (fn s ((a * const T)) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"void vːpːs (const v * a)"))
(test-assert "a method name already taken on the type is refused"
(reports? (string-append "(record v ((x int)))"
"(ops v (fn s ((a (* const v))) void (return)))"
"(spec (p T) (fn s ((a (* const T))) void))"
"(realize (p v) (fn s ((a (* const v))) void (return)))")
"method is already defined on")))
;; match is an if over the tag whose arms bind the payload. What
;; it refuses is why it exists.
(test-group "match"
@@ -416,18 +308,18 @@ ahead of its pub forms."
").h")))
(test-assert "a scrutinee that is not a path is read once"
(emits? (sum-src "(match (mk) ((circle (r)) (= out r)) (else (= out 0.0)))")
"shape ƛm0 = mk()"))
"shape λm0 = mk()"))
(test-assert "a path scrutinee is not copied"
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"ƛm0")))
"λm0")))
(test-assert "unless a binder is named like a part of it"
(emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))")
"shape ƛm0 = s"))
"shape λm0 = s"))
(test-assert "a macro scrutinee is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)"
(sum-src "(match (the s) ((circle (r)) (= out r))"
" (else (= out 0.0)))"))
"shape ƛm0 = s"))
"shape λm0 = s"))
(test-assert "a typedef of a sum is matched as the sum"
(emits? (string-append
"(sum shape ((circle ((r int))) (empty ())))"
@@ -500,10 +392,10 @@ ahead of its pub forms."
(emits? (sum-src "(switch 1 (case 1 (match s ((circle (r)) (= out r))"
" (else (= out 0.0)))))")
"s.tag == shapeǂcircle"))
(test-assert "and so is a closure's, wherever the closure stands"
(emits? (sum-src "(var c (closure () int) (closure () int ((t s))"
" (match t ((circle (r)) (return 1)) (else (return 0)))))")
"t.tag == shapeǂcircle"))
(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'
@@ -557,17 +449,6 @@ ahead of its pub forms."
(interface-reports? "(pub var n _ 42)" "write it out"))
(test-assert "all of it"
(interface-reports? "(pub var p (* _) 0)" "write it out"))
;; a spec is seen by importers as a type is: pub, or not at all
(test-assert "a pub realization of a private spec is refused"
(interface-reports? (string-append "(spec (shown T) (fn show ((self (* const T))) int))"
"(pub record m ((c int)))"
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")
"importers cannot see this spec; make it pub"))
(test "and of a pub one is not"
'()
(interface-of (string-append "(pub spec (shown T) (fn show ((self (* const T))) int))"
"(pub record m ((c int)))"
"(pub realize (shown m) (fn show ((self (* const m))) int (return 1)))")))
(test "a private one is solved where it is"
'()
(interface-of "(var n _ 42)"))

132
tests/lsp.scm Normal file
View File

@@ -0,0 +1,132 @@
;;; 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)))))

View File

@@ -10,11 +10,8 @@
;;;
;;; It also checks what only a second translation unit can check: that an
;;; imported type reaches the type database, by expanding a macro that
;;; reads the imported struct's fields; and that a closure type crossing
;;; the boundary works both ways -- one built in the module and called
;;; here, one built here and called there, through a code pointer that is
;;; static in the other object. And that a record can cross as a handle
;;; alone, its fields left behind and its methods still found.
;;; 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
@@ -145,12 +142,6 @@
(let ((err (error-of sexc "--public-interface" "gen/broken.sex")))
(and err (irregex-search "broken\\.sex:8: expanding boom: nope" err))))
;;; ...while a realization of a spec importers cannot see is refused by
;;; the module that writes it, not by an importer naming it first
(test-assert "a pub realization of a spec imported without pub is refused"
(let ((err (error-of sexc "specs/money.sex" "-C" "-o" "-")))
(and err (irregex-search "money.sex:8: importers cannot see this spec" err) #t)))
(test "the app runs through both"
'("hello, world"
"hello, sex"
@@ -158,9 +149,7 @@
"text times "
"text times "
"mood 1"
"closure 15 21 201"
"vec2 7 7"
"vec2(3 4)"
"tally 2"
"board 42"
"ledger 2"

View File

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

View File

@@ -62,19 +62,6 @@
(pub fn ledger-total ((l (* const ledger))) int
(return (. l total)))
;;; A closure type crossing the boundary. Both units generate the
;;; struct for this signature independently, so they have to agree on
;;; its tag and its layout, or the value is passed wrong and nothing
;;; says so.
(pub fn make-adder ((n int)) (closure ((int)) int)
(return (closure ((b int)) int (n)
(return (+ n b)))))
;;; The other direction: a closure built by the importer, whose code
;;; pointer is static in *its* object, called from here
(pub fn apply-twice ((f (closure ((int)) int)) (x int)) int
(return (f (f x))))
;;; A record and an ops block crossing the boundary. The record has to
;;; arrive as the struct *and* its typedef, or the bare name does not
;;; work there; the ops block has to arrive as a block rather than as
@@ -110,20 +97,6 @@
;;; called, so there is no function for two units to both define.
(pub sum colour ((rgb ((r int) (g int) (b int))) (none ())))
;;; A spec and a realization over the boundary. The written method
;;; travels as a prototype and keeps external linkage; the default
;;; does not travel at all -- the importer synthesizes its own static
;;; copy from the spec, which is why a default is static even here.
(pub spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void
(.show self)
(printf "\n")))
(pub realize (printable vec2)
(fn show ((self (* const vec2))) void
(printf "vec2(%d %d)" (. self x) (. self y))))
;;; Not `pub': invisible to importers, and static in the generated C.
(fn unused-helper () void
(printf "private\n"))

View File

@@ -1,9 +0,0 @@
;;; Imports shown without pub, so its importers cannot see the spec
;;; this realizes: refused here, rather than in whichever importer
;;; names money before shown
(import shown)
(pub record money ((cents int)))
(pub realize (shown money)
(fn show ((self (* const money))) int (return (. self cents))))

View File

@@ -1,2 +0,0 @@
(pub spec (shown T)
(fn show ((self (* const T))) int))

177
tests/query.scm Normal file
View File

@@ -0,0 +1,177 @@
;;; 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)))

View File

@@ -12,6 +12,8 @@
(include-relative "module-path.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
(test-exit)

View File

@@ -9,10 +9,10 @@
;;; one that reaches past it -- a GNU statement expression, a C23
;;; keyword -- fails here rather than on a user's compiler.
;;;
;;; A capturing closure is the one that leans on C11 itself, through
;;; max_align_t in the environment and `_Static_assert' on its size;
;;; the record, the method and the match are here for what they emit,
;;; and the globals for initializers that have to be constants.
;;; 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
@@ -44,9 +44,8 @@
(pub fn main () int
(var p point #(point : 6 7))
(var k int 1)
(var add-k (closure ((int)) int)
(closure ((v int)) int (k) (return (+ v k))))
(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)

View File

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

View File

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

View File

@@ -3,8 +3,8 @@
"-5")
(return 0)
;;; A recursive sum, an inherent method on it, and a spec realized for
;;; it: every layer of encapsulation in one program, built at once.
;;; A recursive sum and an inherent method on it: every layer of
;;; encapsulation in one program, built at once.
(include stdio.h)
@@ -19,20 +19,15 @@
(match (* self)
((lit (v)) (return v))
((neg (e)) (return (- (.eval e))))
((add (l r)) (return (+ (.eval l) (.eval r)))))))
(spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void ; default, calls the required one
(.show self)
(printf "\n")))
(realize (printable expr)
(fn show ((self (* const expr))) void
((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 ")")))))
((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))

View File

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

View File

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

View File

@@ -6,7 +6,6 @@
"decayed: 2 2 there"
"unsigned wins either way: 4294967295 4294967295"
"toplevel: 1 2.5 hi 12"
"closure in place: 5"
"a type is not a call: 7"
"radix literals: 224 5 128"
"a double reaches C whole: 1"
@@ -35,9 +34,6 @@
(var s _ "hi")
(var a _ (+ 3 (* 3 3)))
(fn make-adder ((k int)) (closure ((int)) int)
(return (closure ((b int)) int (k) (return (+ k b)))))
(pub fn main () int
(var x int 6)
(var y int 3)
@@ -80,14 +76,9 @@
(printf "toplevel: %d %g %s %d\n" n d s a)
;; a closure literal is its own type, so it can be called where it is
;; written, the way a lambda already could
(printf "closure in place: %d\n"
((closure ((v int)) int () (return v)) 5))
;; a `fn' type's parameter list looks exactly like a call; with a
;; closure named `f' in scope it used to be read as one
(var f (closure ((int)) int) (make-adder 1))
;; 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))

View File

@@ -1,83 +0,0 @@
(input)
(output "$12.34"
"(3, 4)"
"max 1234"
"realizes ord: money 1, point 0"
"calls its own: 9")
(return 0)
;;; A spec is a contract and emits nothing; a realization is the
;;; spec's methods for one type, mangled typeːspecːmethod. A default
;;; is copied into every realizing type with the parameter
;;; substituted, so the `show' it calls is that type's own.
;;;
;;; What the layer is for is the last line: a generic asks `realizes?'
;;; before it expands, and says so itself rather than leaving a wall
;;; of C errors two stages downstream.
(include stdio.h)
(record money ((cents int)))
(record point ((x int) (y int)))
(spec (printable T)
(fn show ((self (* const T))) void)
(fn show-line ((self (* const T))) void ; default, calls the required one
(.show self)
(printf "\n")))
(spec (ord T)
(fn less ((a (* const T)) (b (* const T))) bool))
(realize (printable money)
(fn show ((self (* const money))) void
(printf "$%d.%02d" (/ (. self cents) 100) (% (. self cents) 100))))
(realize (printable point)
(fn show ((self (* const point))) void
(printf "(%d, %d)" (. self x) (. self y))))
(realize (ord money)
(fn less ((a (* const money)) (b (* const money))) bool
(return (< (. a cents) (. b cents)))))
;;; A bounded generic: the macro refuses before it expands
(defmacro (max-of type)
(unless (realizes? 'ord type)
(error "does not realize ord" type))
`(fn ,(cat 'max- type) ((a (* const ,type)) (b (* const ,type))) ,type
(if (,(cat type '/ord/less) a b)
(return (* b))
(return (* a)))))
(max-of money)
(defmacro (ord? type) (if (realizes? 'ord type) 1 0))
;;; A realization's methods may call one another, whatever order they
;;; come in: `total', written, calls the default `doubled', which calls
;;; the later default `plus-one', which calls `base', written below them
(spec (sized T)
(fn total ((self (* const T))) int)
(fn doubled ((self (* const T))) int (return (* 2 (.plus-one self))))
(fn plus-one ((self (* const T))) int (return (+ 1 (.base self))))
(fn base ((self (* const T))) int))
(realize (sized point)
(fn total ((self (* const point))) int (return (+ 1 (.doubled self))))
(fn base ((self (* const point))) int (return (. self x))))
(pub fn main () int
(var m money #(money : 1234))
(var p point #(point : 3 4))
(.show-line m) ; the default, through the registry
(point/printable/show-line (& p)) ; and spelled out
(var cheap money #(money : 150))
(var big money (max-money (& m) (& cheap)))
(printf "max %d\n" (. big cents))
(printf "realizes ord: money %d, point %d\n" (ord? money) (ord? point))
(printf "calls its own: %d\n" (.total p))
(return 0))

View File

@@ -189,8 +189,8 @@
'yes (type-match '(struct point) ((struct _) 'yes) (else 'no)))
(test "and the keyword still has to agree"
'no (type-match '(union point) ((struct _) 'yes) (else 'no)))
(test "a closure of any signature"
'yes (type-match '(closure ((float)) int) ((closure _ _) '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)))

View File

@@ -33,13 +33,8 @@
get-constructor
variant-fields
reset-declarations!
reset-name-tables!
add-spec!
get-spec
spec-parameter
spec-methods
add-realization!
realizes?
normalize-fields
add-method!
@@ -324,43 +319,21 @@
((memq (car type) '(const volatile)) (ops-key (cadr type)))
(else #f)))
;;; A spec is a parameter and a list of methods, each of which either
;;; declares a signature or also carries a default body:
;;;
;;; (spec (printable T) (fn show ((self (* const T))) void))
;;; -> printable -> (T (fn show ((self (* const T))) void))
;;;
;;; And a realization is only ever asked whether it exists -- the
;;; methods it provides land in +ops-db+ like any others.
(define +spec-db+ (make-hash-table))
(define +realize-db+ (make-hash-table))
(define (add-spec! name parameter methods)
(hash-table-set! +spec-db+ name (cons parameter methods)))
(define (get-spec name)
(hash-table-ref/default +spec-db+ name #f))
(define (spec-parameter spec) (car spec))
(define (spec-methods spec) (cdr spec))
(define (add-realization! spec type)
(hash-table-set! +realize-db+ (cons spec (type-key type)) #t))
;;; What a generic macro asks before it expands: (realizes? 'ord 'circle)
(define (realizes? spec type)
(known type (hash-table-exists? +realize-db+ (cons spec (type-key type)))))
;;; Sums, constructors, methods and specs refuse a second declaration
;;; Sums, constructors and methods refuse a second declaration
;;; of the same name, which is per translation unit rather than per
;;; process -- so a process that compiles two units has to start the
;;; second one clean.
(define (reset-declarations!)
(set! +sum-db+ (make-hash-table))
(set! +constructor-db+ (make-hash-table))
(set! +ops-db+ (make-hash-table))
(set! +spec-db+ (make-hash-table))
(set! +realize-db+ (make-hash-table)))
(set! +ops-db+ (make-hash-table)))
;;; What `reset-declarations!' leaves, and what a second unit must not see.
(define (reset-name-tables!)
(set! +type-db+ (make-hash-table))
(set! +tag-db+ (make-hash-table))
(set! +name-db+ (make-hash-table))
(reset-declarations!))
;;; Type matcher macro
;;; (type-match type
@@ -378,8 +351,8 @@
;;;
;;; `_' in a pattern matches anything in that position, the same thing
;;; it means in a type. Without it every spelling has to be enumerated:
;;; `(closure ((int)) int)' and `(closure ((float)) int)' are separate
;;; clauses for what is one case.
;;; `(fn ((int)) int)' and `(fn ((float)) int)' are separate clauses for
;;; what is one case.
;;;
;;; A `_' written last takes everything that remains, because a type's
;;; words are spread rather than nested -- `(* const char)' is three

119
utils.scm
View File

@@ -2,6 +2,7 @@
scheme
(scheme base) ; make-parameter
(chicken base)
(chicken condition)
(chicken module)
(chicken pathname)
(chicken process-context)
@@ -26,6 +27,19 @@
stamp-form-source!
sex-error
sex-warning
sex-condition?
sex-diagnostics
sex-symbols
sex-scope-range
sex-index-suppressed?
make-note-box
note-box-items
record-diagnostic!
record-diagnostic-at!
record-exception!
record-symbol!
form-line-range
reset-form-sources!
(with-directory set-working-directory))
(define-syntax prog1
@@ -162,20 +176,107 @@ wrap a form-building expression."
(string-append (car src) ":" (number->string (cadr src)) ": ")
"")))
;;; A long-running query collects into these instead of aborting the
;;; process or writing warnings out. Each is #f, or a box whose car is
;;; the newest-first list. `sex-scope-range' is the line span of the
;;; block a local is being declared in, (start . end). Suppressing the
;;; index drops forms the compiler invented, such as a sum's payloads.
(define sex-diagnostics (make-parameter #f))
(define sex-symbols (make-parameter #f))
(define sex-scope-range (make-parameter #f))
(define sex-index-suppressed? (make-parameter #f))
(define (make-note-box) (list '()))
(define (note-box-items box) (car box))
(define (note-box-push! box item)
(set-car! box (cons item (car box))))
(define (form-line-range form)
"The (start . end) lines of FORM, or #f when it was not read from a file."
(let ((src (and (pair? form) (form-source form))))
(and src (cons (cadr src) (caddr src)))))
(define (record-diagnostic-at! severity file line end message args)
(let ((box (sex-diagnostics)))
(when box
(note-box-push! box (list severity file line end message args)))))
(define (record-diagnostic! severity form message args)
(let ((src (and (pair? form) (form-source form))))
(record-diagnostic-at! severity
(if src (car src) (current-source-file))
(if src (cadr src) 1)
(if src (caddr src) 1)
message
args)))
;;; Names the compiler minted: closure helpers, sum tags, variant payloads.
(define (generated-name? name)
(let ((s (symbol->string name)))
(let loop ((i 0))
(and (< i (string-length s))
(or (memv (string-ref s i) '(#\ƛ #\ǂ #\ː))
(loop (+ i 1)))))))
;;; SCOPED? asks for the current block. A local met outside one is dropped
;;; rather than published as a global. A form the reader never stamped,
;;; such as the prelude, is not a name the unit declared.
(define (record-symbol! kind name form signature doc scoped?)
(let ((box (sex-symbols))
(scope (and scoped? (sex-scope-range))))
(when (and box (not (sex-index-suppressed?))
(symbol? name) (not (generated-name? name))
(or (not scoped?) scope))
(let ((src (and (pair? form) (form-source form))))
(when src
(note-box-push! box
(list kind name (car src) (cadr src) (caddr src)
signature doc
(and scope (car scope))
(and scope (cdr scope)))))))))
(define (sex-error form message . args)
"Signal an error about FORM, prefixed with where it was written."
(apply error (string-append (form-location form) message) args))
"Signal an error about FORM, prefixed with where it was written.
When diagnostics are being collected the same error is recorded first,
so a caller that continues still knows about it."
(record-diagnostic! 'error form message args)
(abort
(make-composite-condition
(make-property-condition 'exn
'message (string-append (form-location form) message)
'arguments args)
(make-property-condition 'sex 'form form))))
(define (sex-condition? exn)
(and (condition? exn) ((condition-predicate 'sex) exn)))
;;; A `sex-error' has already been recorded. Anything else raised while
;;; collecting -- a macro's own `error', an assertion -- is recorded
;;; against FORM so the walk can continue.
(define (record-exception! form exn)
(unless (sex-condition? exn)
(let ((message ((condition-property-accessor 'exn 'message #f) exn))
(args ((condition-property-accessor 'exn 'arguments (list)) exn)))
(record-diagnostic! 'error form (or message "error")
(if message args (list exn))))))
(define (sex-warning form message . args)
"Report something about FORM that does not stop the compilation.
Goes to stderr, prefixed with where the form was written, so a warning
reads like an error and sorts alongside one in a build log."
(let ((port (current-error-port)))
(display (form-location form) port)
(display "warning: " port)
(display message port)
(for-each (lambda (arg) (display " " port) (display arg port)) args)
(newline port)))
reads like an error and sorts alongside one in a build log. Collected
instead when diagnostics are being gathered."
(if (sex-diagnostics)
(record-diagnostic! 'warning form message args)
(let ((port (current-error-port)))
(display (form-location form) port)
(display "warning: " port)
(display message port)
(for-each (lambda (arg) (display " " port) (display arg port)) args)
(newline port))))
(define (reset-form-sources!)
(set! +form-sources+ (make-hash-table eq?)))
(define (stamp-form-source! form src)
"Give FORM and every subform that has none the location SRC. Used for