diff --git a/.gitignore b/.gitignore index 53ae9561..7373efec 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ /sexc /sex-tests /sextest +/sex-lsp # Scrapped design docs, kept for reference /attic diff --git a/Makefile b/Makefile index 06e5cb0d..7ace22ab 100644 --- a/Makefile +++ b/Makefile @@ -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) diff --git a/dependencies.txt b/dependencies.txt index fbd17eb3..decfb98a 100644 --- a/dependencies.txt +++ b/dependencies.txt @@ -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 diff --git a/eggs.lock b/eggs.lock index aeca2543..61935621 100644 --- a/eggs.lock +++ b/eggs.lock @@ -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") diff --git a/sex-lsp.scm b/sex-lsp.scm new file mode 100644 index 00000000..b29f9162 --- /dev/null +++ b/sex-lsp.scm @@ -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) diff --git a/tests/lsp.scm b/tests/lsp.scm new file mode 100644 index 00000000..6d623181 --- /dev/null +++ b/tests/lsp.scm @@ -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))))) diff --git a/tests/run.scm b/tests/run.scm index d28ee01a..db0496fd 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -13,6 +13,7 @@ (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)