summaryrefslogtreecommitdiff
path: root/src/geiser/geiser.ss
blob: 806f5931d86297eaabec48f839c6e0e3926f123c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
;;; geiser.ss -- emacs/scheme interface

;; Copyright (c) 2022 Jose A Ortega Ruiz

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the Modified BSD License. You should
;; have received a copy of the license along with this program. If
;; not, see <http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5>.

;; Start date: Tue Apr 26 22:27:26 2016 +0200

(library (geiser)
  (export geiser:eval
          geiser:completions
          geiser:module-completions
          geiser:autodoc
          geiser:no-values
          geiser:load-file
          geiser:newline
          geiser:macroexpand
          geiser:symbol-location
          geiser:module-location
          geiser:add-to-load-path)
  (import (chezscheme))
  (import (geiser-data))

  (define-syntax as-string
    (syntax-rules () ((_ b ...) (with-output-to-string (lambda () b ...)))))

  (define (write-to-string x) (as-string (write x)))

  (define (pretty-string x)
    (parameterize ((print-extended-identifiers #t)
                   (print-vector-length #t))
      (as-string (pretty-print x))))

  (define (call-with-result thunk)
    (let ((output-string (open-output-string)))
      (write
       (call/cc
        (lambda (k)
          (with-exception-handler
              (lambda (e)
                (debug-condition e)     ; save the condition for the debugger
                (k `((result "")
                     (output . ,(get-output-string output-string))
                     (error (key . condition)
                            (msg . ,(as-string (display-condition e)))))))
            (lambda ()
              (call-with-values
                  (lambda ()
                    (parameterize ((current-output-port output-string)) (thunk)))
                (lambda result
                  `((result ,(write-to-string
                              (if (null? (cdr result)) (car result) result)))
                    (output . ,(get-output-string output-string))))))))))
      (newline)
      (close-output-port output-string)))

  (define (last-index-of str-list char idx last-idx)
    (if (null? str-list)
        last-idx
        (last-index-of (cdr str-list) char (+ 1 idx)
                       (if (char=? char (car str-list)) idx last-idx))))

  (define (with-extension name ext)
    (let ((idx (last-index-of (string->list name) #\. 0 -1)))
      (if (= idx -1)
          (string-append name ext)
          (string-append (substring name 0 idx) ext))))

  (define (obj-file-name name) (with-extension name ".so"))

  (define (file-directory filename)
    (let ((idx (last-index-of (string->list filename) #\/ 0 -1)))
      (if (= idx -1) filename (substring filename 0 idx))))

  (define (geiser:load-file filename)
    (let ((output-filename (obj-file-name filename)))
      (call-with-result
       (lambda ()
         (parameterize ([current-directory (file-directory filename)])
           (with-output-to-string
             (lambda () (maybe-compile-file filename output-filename)))
           (load output-filename))))))

  (define (geiser:add-to-load-path path)
    (let ((p (cons path path)))
      (library-directories (cons p (remove p (library-directories))))))

  (define string-prefix?
    (lambda (x y)
      (let ([n (string-length x)])
        (and (fx<= n (string-length y))
             (let prefix? ([i 0])
               (or (fx= i n)
                   (and (char=? (string-ref x i) (string-ref y i))
                        (prefix? (fx+ i 1)))))))))

  (define (geiser:completions prefix . rest)
    (sort string-ci<?
          (filter (lambda (el)
                    (string-prefix? prefix el))
                  (map write-to-string
                       (environment-symbols (interaction-environment))))))

  (define not-found (gensym))

  (define current-environment (make-parameter environment?))

  (define (module-env env)
    (cond ((environment? env) env)
          ((list? env) (environment env))
          (else #f)))

  (define (try-eval sym . env)
    (call/cc
     (lambda (k)
       (with-exception-handler (lambda (e) (k not-found))
         (let ((env (and (not (null? env)) (module-env (car env)))))
           (lambda () (if env (eval sym env) (eval sym))))))))

  (define (geiser:eval module form)
    (call-with-result
     (lambda ()
       (parameterize ((current-environment (module-env module)))
         (if (environment? (current-environment))
             (eval form (current-environment))
             (eval form))))))

  (define (geiser:module-completions prefix . rest)
    (define (substring? s1 s2)
      (let ([n1 (string-length s1)] [n2 (string-length s2)])
        (let loop2 ([i2 0])
          (let loop1 ([i1 0] [j i2])
            (if (fx= i1 n1)
                i2
                (and (not (fx= j n2))
                     (if (char=? (string-ref s1 i1) (string-ref s2 j))
                         (loop1 (fx+ i1 1) (fx+ j 1))
                         (loop2 (fx+ i2 1)))))))))
    (filter (lambda (el)
              (substring? prefix el))
            (map write-to-string (library-list))))

  (define (arity->parameter-list p)
    (define (nparams n)
      (map (lambda (n) (string->symbol (format "x~a" n))) (iota n)))
    (define (add-opt pl)
      (cons (append (if (null? pl) '() (car pl)) '(...)) pl))
    (let* ((m (procedure-arity-mask p))
           (pm (if (< m 0) (+ 1 (lognot m)) m))
           (n (if (> pm 0) (/ (log pm) (log 2)) 0)))
      (let loop ((k 1) (pl '()))
        (cond ((> k n) (reverse (if (< m 0) (add-opt pl) pl)))
              ((logbit? k pm) (loop (+ k 1) (cons (nparams k) pl)))
              (else (loop (+ k 1) pl))))))

  (define (source->parameter-list p)
    ;; same as (inspect object), then hitting c
    (let* ((s (((inspect/object p) 'code) 'source))
           (form (and s (s 'value))))
      (and (list? form)
           (>= (length form) 2)
           (case (car form)
             [(lambda) (list (cadr form))]
             [(case-lambda) (map car (cdr form))]
             [(record-predicate record-accessor)
              (list (list (record-type-name (cadr (cadr form)))))]
             [(record-mutator)
              (let ([rtd (cadr (cadr form))]
                    [field-idx (caddr form)])
                (list (list (record-type-name rtd)
                            (vector-ref (record-type-field-names rtd)
                                        field-idx))))]
             [(record-constructor)
              (let* ([rcd (cadr (cadr form))]
                     [rtd (((inspect/object rcd) 'ref 'rtd) 'value)])
                (list (vector->list (record-type-field-names rtd))))]
             [else #f]))))

  (define (value->string x)
    (define max-len 80)
    (define sub-str "...")
    (define sub-len (- max-len (string-length sub-str)))
    (let* ((s (pretty-string x))
           (l (string-length s)))
      (if (<= l max-len) s (string-append (substring s 0 sub-len) sub-str))))

  (define (docs->parameter-list id)
    (let ((s (symbol-signature id)))
      (and s (list s))))

  (define (operator-arglist operator)
    (define (procedure-parameter-list id p)
      (and (procedure? p)
           (or (source->parameter-list p)
               (docs->parameter-list id)
               (arity->parameter-list p))))
    (define (autodoc-arglist* args req)
      (cond ((null? args) (list (list* "required" (reverse req))))
            ((pair? args) (autodoc-arglist* (cdr args) (cons (car args) req)))
            (else `(("required" . ,(reverse req))
                    ("optional" ,args)))))
    (define (autodoc-arglist arglist) (autodoc-arglist* arglist '()))
    (let ([binding (try-eval operator)])
      (if (not (eq? binding not-found))
          (let ([arglists (procedure-parameter-list operator binding)])
            (cond ((null? arglists) `(,operator ("args" (("required")))))
                  (arglists
                   `(,operator ("args" ,@(map autodoc-arglist arglists))))
                  (else `(,operator ("value" . ,(value->string binding))))))
          (let ((s (symbol-signature operator)))
            (if s `(,operator ("args" (("required" ,@s)))) '())))))

  (define (geiser:autodoc ids)
    (cond ((null? ids) '())
          ((not (list? ids)) (geiser:autodoc (list ids)))
          ((not (symbol? (car ids))) (geiser:autodoc (cdr ids)))
          (else (map operator-arglist ids))))

  (define (geiser:symbol-location id . env)
    (let* ([b (try-eval id (current-environment))]
           [c (and (not (eq? not-found b))
                   ((inspect/object b) 'code))])
      (if c
          (call-with-values (lambda () (c 'source-path))
            (lambda (path line . col)
              (let ((line (if (null? col) '() line))
                    (char (if (null? col) line '()))
                    (col (if (null? col) '() (car col))))
                `(("name" . ,(c 'name))
                  ("file" . ,path)
                  ("line" . ,line)
                  ("column" . ,col)
                  ("char" . ,char)))))
          '())))

  (define (geiser:module-location id)
    (let ((obj (library-object-filename id)))
      (let loop ((exts (if obj (map car (library-extensions)) '())))
        (cond ((null? exts) '())
              ((file-exists? (with-extension obj (car exts)))
               `(("file" . ,(with-extension obj (car exts)))))
              (else (loop (cdr exts)))))))

  (define (geiser:no-values) #f)

  (define (geiser:newline) #f)

  (define (geiser:macroexpand form . rest)
    (with-output-to-string
      (lambda () (pretty-print (syntax->datum (expand form)))))))