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