From 7bbb8e19ac48f1297c414ec7a715f5165bc147d4 Mon Sep 17 00:00:00 2001 From: Pavel Kulyov Date: Wed, 11 Nov 2026 07:38:33 +0300 Subject: [PATCH 1/3] 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). --- reader.scm | 8 + semen.scm | 85 +++++++--- sex-macros.scm | 18 +- sex-modules.scm | 11 +- sex-query.scm | 426 ++++++++++++++++++++++++++++++++++++++++++++++++ sexc.scm | 73 +++++++-- tests/query.scm | 177 ++++++++++++++++++++ tests/run.scm | 1 + types.scm | 8 + utils.scm | 119 +++++++++++++- 10 files changed, 876 insertions(+), 50 deletions(-) create mode 100644 sex-query.scm create mode 100644 tests/query.scm diff --git a/reader.scm b/reader.scm index f998827..9e2a1a1 100644 --- a/reader.scm +++ b/reader.scm @@ -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)))) diff --git a/semen.scm b/semen.scm index 1b1e83e..f5486f6 100644 --- a/semen.scm +++ b/semen.scm @@ -4,6 +4,7 @@ scheme (only (scheme base) make-parameter) (chicken base) + (chicken condition) (chicken keyword) (chicken string) (chicken module) @@ -47,18 +48,27 @@ (string-append "called at " (form-file call) ":" (number->string (form-line call))))))) +(define (process-one forms acc) + (if (macro? (car forms)) + (process-rec (macroexpand (car forms) (cdr forms)) acc) + (let* ((processed (match-sex-form (car forms) acc)) + (new (take-until processed acc))) + (process-rec (cdr forms) + (append new acc))))) + +;;; One bad toplevel form is one diagnostic. The rest of the unit is +;;; still worth indexing. A compile that is not collecting still stops +;;; at the first error, as it always has. (define (process-rec forms acc) (cond ((null? forms) (reverse acc)) - ((macro? (car forms)) - (process-rec - (macroexpand (car forms) (cdr forms)) - acc)) - (else - (let* ((processed (match-sex-form (car forms) acc)) - (new (take-until processed acc))) - (process-rec (cdr forms) - (append new acc)))))) + ((sex-diagnostics) + (handle-exceptions exn + (begin + (record-exception! (car forms) exn) + (process-rec (cdr forms) acc)) + (process-one forms acc))) + (else (process-one forms acc)))) (define (take-until forms tail) (if (eq? forms tail) @@ -207,6 +217,7 @@ ;;; Typdef (define (process-typedef form new-type target acc) + (record-symbol! 'typedef new-type form target #f #f) (cons (copy-form-source! form `(typedef ,target ,new-type)) acc)) ;;; Fn processing @@ -297,10 +308,22 @@ "a function's types are written out; `_' is a variable's" (sex-fn-name expanded))) (add-name-type! (sex-fn-name expanded) (fn-type-of expanded)) + (record-symbol! 'fn (sex-fn-name expanded) sex-fn-raw + `(fn ,(sex-fn-name expanded) + ,(sex-fn-arglist expanded) + ,(sex-fn-return-type expanded)) + doc #f) (let* ((env (make-fn-env expanded)) ;; the parameters are the body's outermost scope (header (take expanded boundary)) - (body (parameterize ((operand-position? #f)) + (body (parameterize ((sex-scope-range (form-line-range sex-fn-raw)) + (operand-position? #f)) + (for-each + (lambda (param) + (when (named-arg? param) + (record-symbol! 'var (first param) sex-fn-raw + (named-arg-type param) #f #t))) + (sex-fn-arglist expanded)) (walk-body (drop expanded boundary) env))) ;; A function is header and body stitched together, so the ;; result is fresh structure: without this the definition @@ -424,10 +447,11 @@ (or (hash-table-ref/default (car scopes) name #f) (search (cdr scopes)))))) -(define (with-scope env body) - (let ((enclosing (hash-table-ref env :scopes))) +(define (with-scope env form body) + (let ((enclosing (hash-table-ref env :scopes)) + (range (or (form-line-range form) (sex-scope-range)))) (set! (hash-table-ref env :scopes) (cons (make-hash-table) enclosing)) - (let ((walked (body))) + (let ((walked (parameterize ((sex-scope-range range)) (body)))) (set! (hash-table-ref env :scopes) enclosing) walked))) @@ -496,10 +520,10 @@ (case (car form) ((do default) (parameterize ((operand-position? #f)) - (with-scope env (lambda () (walk-parts form env))))) + (with-scope env form (lambda () (walk-parts form env))))) ((for while if switch case case/fallthrough) - (with-scope env (lambda () (walk-control form env)))) + (with-scope env form (lambda () (walk-control form env)))) ((lambda) (let ((name (aux-name! env make-lambda-name))) @@ -525,7 +549,8 @@ (list)))) env))) (when (>= (length walked) 3) - (declare-name! env (second walked) (third walked))) + (declare-name! env (second walked) (third walked)) + (record-symbol! 'var (second walked) walked (third walked) #f #t)) walked)) ((return) @@ -1436,6 +1461,9 @@ ;;; Record the named structs, unions and enums in the type database (define (process-struct sex-struct acc) (let-values (((doc form) (extract-aggregate-docstring sex-struct))) + (let ((core (if (eq? (car form) 'pub) (cdr form) form))) + (when (and (pair? (cdr core)) (symbol? (cadr core))) + (record-symbol! (car core) (cadr core) sex-struct #f doc #f))) (register-aggregate! form) (with-docstring doc form acc))) @@ -1473,11 +1501,20 @@ (for-each (lambda (v) (add-constructor! (qualify-op name (car v)) name (car v))) variants) - ;; the docstring goes ahead of everything the sum is made of - (fold match-sex-form - (if doc (cons (copy-form-source! form (list 'comment doc)) acc) acc) - (map (lambda (f) (copy-form-source! form f)) - (sum-forms name variants))))))) + (record-symbol! 'sum name written `(struct ,name) doc #f) + (for-each (lambda (v) + (record-symbol! 'fn (qualify-op name (car v)) written + `(fn ,(map second (cdr v)) ,name) + #f #f)) + variants) + ;; the docstring goes ahead of everything the sum is made of. + ;; The generated structs and typedefs are the compiler's, and + ;; the sum itself is already indexed. + (parameterize ((sex-index-suppressed? #t)) + (fold match-sex-form + (if doc (cons (copy-form-source! form (list 'comment doc)) acc) acc) + (map (lambda (f) (copy-form-source! form f)) + (sum-forms name variants)))))))) (define (parse-variant form v) (unless (and (list? v) (= 2 (length v)) (symbol? (car v)) (list? (cadr v))) @@ -1602,7 +1639,8 @@ (for-each (lambda (value) (let ((constant (if (pair? value) (car value) value))) (when (symbol? constant) - (add-name-type! constant `(enum ,name))))) + (add-name-type! constant `(enum ,name)) + (record-symbol! 'const constant form `(enum ,name) #f #f)))) (remove comment-form? (caddr f))))))))) ;;; No function around a toplevel form, so no scope chain: what a @@ -1650,7 +1688,8 @@ (copy-form-source! sex-var (cons qualifier core)) core))) (when (and (pair? (cdr core)) (pair? (cddr core)) (symbol? (second core))) - (add-name-type! (second core) (third core))) + (add-name-type! (second core) (third core)) + (record-symbol! 'var (second core) sex-var (third core) #f #f)) (cons form (append (hash-table-ref env :lambda-aux-code) acc)))) ;;; A compound literal is not a constant, though cc lets one pass at file diff --git a/sex-macros.scm b/sex-macros.scm index dde851f..287f336 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -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 @@ -96,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))) diff --git a/sex-modules.scm b/sex-modules.scm index b476c35..cc36d79 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -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 diff --git a/sex-query.scm b/sex-query.scm new file mode 100644 index 0000000..a3cd7ed --- /dev/null +++ b/sex-query.scm @@ -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 ""))) + (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)))) diff --git a/sexc.scm b/sexc.scm index 4a5e145..3a1bf3c 100644 --- a/sexc.scm +++ b/sexc.scm @@ -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,23 +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 - '((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))) +;;; 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 @@ -307,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))) @@ -324,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") diff --git a/tests/query.scm b/tests/query.scm new file mode 100644 index 0000000..9c818ae --- /dev/null +++ b/tests/query.scm @@ -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 ")))))) + +(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 ")) + (test-assert "the unit's header" (string-contains probe "#include ")) + (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))) diff --git a/tests/run.scm b/tests/run.scm index 32e3068..d28ee01 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -12,6 +12,7 @@ (include-relative "module-path.scm") (include-relative "types.scm") (include-relative "infer.scm") +(include-relative "query.scm") ;;; Should be the last in the test suite (test-exit) diff --git a/types.scm b/types.scm index 4217c07..7a99174 100644 --- a/types.scm +++ b/types.scm @@ -33,6 +33,7 @@ get-constructor variant-fields reset-declarations! + reset-name-tables! normalize-fields @@ -327,6 +328,13 @@ (set! +constructor-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 ;;; (int ...) diff --git a/utils.scm b/utils.scm index 7ea0123..a520389 100644 --- a/utils.scm +++ b/utils.scm @@ -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 -- 2.52.0 From 0aef571f688ace22fc4cfba5973d283025a7ffa6 Mon Sep 17 00:00:00 2001 From: Pavel Kulyov Date: Wed, 11 Nov 2026 07:41:03 +0300 Subject: [PATCH 2/3] 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. --- .gitignore | 1 + Makefile | 7 +- dependencies.txt | 2 +- eggs.lock | 4 + sex-lsp.scm | 889 +++++++++++++++++++++++++++++++++++++++++++++++ tests/lsp.scm | 132 +++++++ tests/run.scm | 1 + 7 files changed, 1032 insertions(+), 4 deletions(-) create mode 100644 sex-lsp.scm create mode 100644 tests/lsp.scm diff --git a/.gitignore b/.gitignore index 53ae956..7373efe 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 06e5cb0..7ace22a 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 fbd17eb..decfb98 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 aeca254..6193562 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 0000000..b29f916 --- /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 0000000..6d62318 --- /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 d28ee01..db0496f 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) -- 2.52.0 From e2f71d23a0d72b83909d697befb6a35e5e4d864e Mon Sep 17 00:00:00 2001 From: Pavel Kulyov Date: Wed, 11 Nov 2026 07:58:11 +0300 Subject: [PATCH 3/3] emacs: load the server beside sex-mode --- Readme.org | 41 +++++++++--- sex-lsp.el | 178 ++++++++++++++++++++++++++++++++++++++++++++++++++++ sex-mode.el | 12 ++-- 3 files changed, 219 insertions(+), 12 deletions(-) create mode 100644 sex-lsp.el diff --git a/Readme.org b/Readme.org index 0e073c8..c67066f 100644 --- a/Readme.org +++ b/Readme.org @@ -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 @@ -319,13 +336,21 @@ 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 - :ensure nil - :quelpa - (sex-mode :fetcher git - :url "https://git.kotobank.ch/alex-eg/sex.git" - :files ("sex-mode.el") - :upgrade t)) + (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~. +~.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. diff --git a/sex-lsp.el b/sex-lsp.el new file mode 100644 index 0000000..aa1660b --- /dev/null +++ b/sex-lsp.el @@ -0,0 +1,178 @@ +;;; sex-lsp.el --- Language server client for Sex -*- lexical-binding: t -*- + +;; Copyright (C) 2025-2026 alex-eg + +;; Author: alex-eg +;; 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 diff --git a/sex-mode.el b/sex-mode.el index affca8f..c9ea228 100644 --- a/sex-mode.el +++ b/sex-mode.el @@ -15,16 +15,20 @@ ;; The mode derives from `lisp-data-mode' and fontifies Sex ;; declarations and keywords. ;; -;; `sex-mode' is one file in the Sex repository. Quelpa installs it -;; from that git remote: +;; `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") -;; :upgrade t)) +;; :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. -- 2.52.0