glime.lisp 109 KB
Newer Older
1
2
3
;;; Modified version of swank-arglists.lisp, copied from slime master repo as of Oct 13, 2015.
;;;
;; Original credits:
4
5
6
7
8
9
;; Authors: Matthias Koeppe  <mkoeppe@mail.math.uni-magdeburg.de>
;;          Tobias C. Rittweiler <tcr@freebits.de>
;;          and others
;;
;; License: Public Domain

10
11
;; Original GENDL customizations for SLIME:  Nick Levine, Ravenbrook Limited, 2013-05-02

12
(eval-when (:compile-toplevel :load-toplevel :execute)
Gail Zacharias's avatar
Gail Zacharias committed
13
  (swank:swank-require :swank-arglists))
14
15

(eval-when (:compile-toplevel :load-toplevel :execute)
16
17
18
19
20
21
22
  (defpackage :gendl-swank
    (:use :common-lisp) ;; clean package
    ;; Internal swank symbols that we use
    (:import-from :swank
		  #:dcase #:match #:with-bindings #:with-struct #:with-buffer-syntax #:without-printing-errors
		  #:debug-on-swank-error
		  ;; #:arglist -- see below, we don't want to import the structure name.
23
		  #:parse-symbol #:valid-function-name-p #:ensure-list #:call/truncated-output-to-string #:from-string
24
25
26
27
28
29
30
31
32
		  #:type-specifier-arglist #:declaration-arglist
		  #:find-matching-symbols-in-list #:tokenize-symbol
		  #:format-completion-set #:completion-output-symbol-converter
		  #:longest-compound-prefix #:make-compound-prefix-matcher
		  #:*echo-area-prefix*
		  #:keyword-package)))

(in-package :gendl-swank)

33
(defvar *enable-glime* t "If true, GLIME extensions are enabled. If false, run the unmodified original SWANK versions of everything.")
34

35
36
(defparameter *gendl-slime-release* "0.1.2")

37
38
;;;; Utilities

39
40
(defparameter +cursor-marker+ 'swank::%cursor-marker%)

41
42
43
44
;; We don't want to import swank::arglist because then we'd be overwriting the swank::arglist structure.
(defun arglist (fn)
  (swank::arglist fn))

45
46
47
48
49
50
(defmacro when-let (binding &body body)
  (destructuring-bind (var val) binding
    `(let ((,var ,val))
       (when ,var
	 ,@body))))

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(defun compose (&rest functions)
  "Compose FUNCTIONS right-associatively, returning a function"
  #'(lambda (x)
      (reduce #'funcall functions :initial-value x :from-end t)))

(defun length= (seq n)
  "Test for whether SEQ contains N number of elements. I.e. it's equivalent
 to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
 efficiently implemented."
  (etypecase seq
    (list (do ((i n (1- i))
               (list seq (cdr list)))
              ((or (<= i 0) (null list))
               (and (zerop i) (null list)))))
    (sequence (= (length seq) n))))

67
68
69
(defun whitespacep (c)
  (memq c '(#\Return #\Linefeed #\space #\tab)))

70
71
72
73
(declaim (inline memq))
(defun memq (item list)
  (member item list :test #'eq))

74
75
76
77
78
79
80
81
82
(defun quoted-form-p (form)
  (and (consp form)
       (eq (car form) 'quote)
       (consp (cdr form))
       (null (cddr form))))

(defun quoted-symbol-p (form)
  (and (quoted-form-p form) (symbolp (cadr form))))

83
84
85
86
87
88
89
90
91
92
(defun exactly-one-p (&rest values)
  "If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
  (let ((found nil))
    (dolist (v values)
      (when v (if found
                  (return-from exactly-one-p nil)
                  (setq found v))))
    found))

93
94
95
96
(defun string-starts-with-p (start string)
  (let ((n (length start)))
    (and (<= n (length string)) (string-equal start string :end1 n :end2 n))))

97
98
(defun valid-operator-symbol-p (symbol)
  "Is SYMBOL the name of a function, a macro, or a special-operator?"
99
100
101
102
103
104
  (and (symbolp symbol)
       (not (eq symbol +cursor-marker+))
       (or (fboundp symbol)
	   (macro-function symbol)
	   (special-operator-p symbol)
	   (member symbol '(declare declaim)))))
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

(defun function-exists-p (form)
  (and (valid-function-name-p form)
       (fboundp form)
       t))

(defmacro multiple-value-or (&rest forms)
  (if (null forms)
      nil
      (let ((first (first forms))
            (rest (rest forms)))
        `(let* ((values (multiple-value-list ,first))
                (primary-value (first values)))
          (if primary-value
              (values-list values)
              (multiple-value-or ,@rest))))))

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
(defmacro orf (location form &environment env)
  (multiple-value-bind (vars values new setter getter)
      (get-setf-expansion location env)
    (when (cdr new)
      (error "Can't work with setf-expansion for ~s - ~d values from setter ~s"
             location (length new) new))
    (let ((current (car new)))
      `(let* (,@(mapcar 'list vars values)
              (,current ,getter))
         (or ,current
             (progn (setf ,current ,form)
               ,setter))))))

;; We could do with more informative error handling than SLIME provides. Getting
;; this right can be quite a lot of work, but making a start is cheap.
(defmacro handling-whatever ((&rest options) &body body)
  (declare (ignore options))
  `(handler-bind ((serious-condition (lambda (condition)
                                       ;; Print the problem and decline to handle.
                                       (format *terminal-io* "~&;; Error: ~a~%" condition))))
     ,@body))


145
146
147
148
149
150
151
152
153
(defun arglist-available-p (arglist)
  (not (eql arglist :not-available)))

(defmacro with-available-arglist ((var &rest more-vars) form &body body)
  `(multiple-value-bind (,var ,@more-vars) ,form
     (if (eql ,var :not-available)
         :not-available
         (progn ,@body))))

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
(defmacro defslimefun (name &rest body)
  (multiple-value-bind (swank-sym flag) (find-symbol (symbol-name name) :swank)
    (assert (eq flag :external))
    `(progn
       (defun ,name ,@body)
       (redefine-slimefun ',swank-sym ',name))))

(defun redefine-slimefun (swank-sym new-fn)
  (multiple-value-bind (sym flag) (find-symbol (symbol-name swank-sym) :swank)
    (assert (and (eq sym swank-sym) (eq flag :external))))
  (unless (get swank-sym 'gendl-unwrapped)
    (setf (get swank-sym 'gendl-unwrapped) (symbol-function swank-sym)))
  (setf (symbol-function swank-sym)
	(lambda (&rest args)
	  (declare (dynamic-extent args))
	  (if *enable-glime*
	      (apply new-fn args)
	      (when-let (old-fn (get swank-sym 'gendl-unwrapped))
		(apply old-fn args)))))
  new-fn)

(defun remove-glime ()
  (do-external-symbols (swank-sym :swank)
    (when-let (fn (get swank-sym 'gendl-unwrapped))
      (setf (symbol-function swank-sym) fn)
      (remprop swank-sym 'gendl-unwrapped))))

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

;;;; Arglist Definition

(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
  provided-args         ; list of the provided actual arguments
  required-args         ; list of the required arguments
  optional-args         ; list of the optional arguments
  key-p                 ; whether &key appeared
  keyword-args          ; list of the keywords
  rest                  ; name of the &rest or &body argument (if any)
  body-p                ; whether the rest argument is a &body
  allow-other-keys-p    ; whether &allow-other-keys appeared
  aux-args              ; list of &aux variables
  any-p                 ; whether &any appeared
  any-args              ; list of &any arguments  [*]
  known-junk            ; &whole, &environment
197
198
  unknown-junk          ; unparsed stuff
  doc-plist)		; arg documentation
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

;;;
;;; [*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
;;;     and is only used to describe certain arglists that cannot be
;;;     described in another way.
;;;
;;;     &ANY is very similiar to &KEY but while &KEY is based upon
;;;     the idea of a plist (key1 value1 key2 value2), &ANY is a
;;;     cross between &OPTIONAL, &KEY and *FEATURES* lists:
;;;
;;;        a) (&ANY :A :B :C) means that you can provide any (non-null)
;;;              set consisting of the keywords `:A', `:B', or `:C' in
;;;              the arglist. E.g. (:A) or (:C :B :A).
;;;
;;;        (This is not restricted to keywords only, but any self-evaluating
;;;         expression is allowed.)
;;;
;;;        b) (&ANY (key1 v1) (key2 v2) (key3 v3)) means that you can
;;;              provide any (non-null) set consisting of lists where
;;;              the CAR of the list is one of `key1', `key2', or `key3'.
;;;              E.g. ((key1 100) (key3 42)), or ((key3 66) (key2 23))
;;;
;;;
;;;     For example, a) let us describe the situations of EVAL-WHEN as
;;;
;;;     (EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
;;;
;;;     and b) let us describe the optimization qualifiers that are valid
;;;     in the declaration specifier `OPTIMIZE':
;;;
;;;       (DECLARE (OPTIMIZE &ANY (compilation-speed 1) (safety 1) ...))
;;;

;; This is a wrapper object around anything that came from Slime and
;; could not reliably be read.
(defstruct (arglist-dummy
	     (:conc-name #:arglist-dummy.)
             (:constructor make-arglist-dummy (string-representation)))
  string-representation)

239
240
241
242
(defmethod print-object ((dummy arglist-dummy) stream)
  (print-unreadable-object (dummy stream :type t :identity nil)
    (prin1 (arglist-dummy.string-representation dummy) stream)))

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
(defun empty-arg-p (dummy)
  (and (arglist-dummy-p dummy)
       (zerop (length (arglist-dummy.string-representation dummy)))))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter +lambda-list-keywords+
    '(&provided &required &optional &rest &key &any)))

(defmacro do-decoded-arglist (decoded-arglist &body clauses)
  (assert (loop for clause in clauses
		thereis (member (car clause) +lambda-list-keywords+)))
  (flet ((parse-clauses (clauses)
	   (let* ((size    (length +lambda-list-keywords+))
		  (initial (make-hash-table :test #'eq :size size))
		  (main    (make-hash-table :test #'eq :size size))
		  (final   (make-hash-table :test #'eq :size size)))
	     (loop for clause in clauses
		   for lambda-list-keyword = (first clause)
		   for clause-parameter    = (second clause)
		   do
                   (case clause-parameter
                     (:initially
                      (setf (gethash lambda-list-keyword initial) clause))
                     (:finally
                      (setf (gethash lambda-list-keyword final) clause))
                     (t
                      (setf (gethash lambda-list-keyword main) clause)))
		   finally
                   (return (values initial main final)))))
	 (generate-main-clause (clause arglist)
	   (dcase clause
             ((&provided (&optional arg) . body)
              (let ((gensym (gensym "PROVIDED-ARG+")))
		`(dolist (,gensym (arglist.provided-args ,arglist))
		   (declare (ignorable ,gensym))
		   (let (,@(when arg `((,arg ,gensym))))
		     ,@body))))
	     ((&required (&optional arg) . body)
	      (let ((gensym (gensym "REQUIRED-ARG+")))
		`(dolist (,gensym (arglist.required-args ,arglist))
		   (declare (ignorable ,gensym))
		   (let (,@(when arg `((,arg ,gensym))))
		     ,@body))))
	     ((&optional (&optional arg init) . body)
	      (let ((optarg (gensym "OPTIONAL-ARG+")))
		`(dolist (,optarg (arglist.optional-args ,arglist))
		   (declare (ignorable ,optarg))
		   (let (,@(when arg
                             `((,arg (optional-arg.arg-name ,optarg))))
			 ,@(when init
                             `((,init (optional-arg.default-arg ,optarg)))))
		     ,@body))))
295
	     ((&key (&optional keyword arg init type) . body)
296
297
298
299
300
301
302
303
	      (let ((keyarg (gensym "KEY-ARG+")))
		`(dolist (,keyarg (arglist.keyword-args ,arglist))
		   (declare (ignorable ,keyarg))
		   (let (,@(when keyword
                             `((,keyword (keyword-arg.keyword ,keyarg))))
			 ,@(when arg
                             `((,arg (keyword-arg.arg-name ,keyarg))))
			 ,@(when init
304
305
306
                             `((,init (keyword-arg.default-arg ,keyarg))))
			 ,@(when type
			     `((,type (keyword-arg.key-type ,keyarg)))))
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
		     ,@body))))
	     ((&rest (&optional arg body-p) . body)
	      `(when (arglist.rest ,arglist)
		 (let (,@(when arg    `((,arg (arglist.rest ,arglist))))
		       ,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
		   ,@body)))
	     ((&any (&optional arg) . body)
              (let ((gensym (gensym "REQUIRED-ARG+")))
                `(dolist (,gensym (arglist.any-args ,arglist))
                    (declare (ignorable ,gensym))
                    (let (,@(when arg `((,arg ,gensym))))
                      ,@body)))))))
    (let ((arglist (gensym "DECODED-ARGLIST+")))
      (multiple-value-bind (initially-clauses main-clauses finally-clauses)
	  (parse-clauses clauses)
	`(let ((,arglist ,decoded-arglist))
	   (block do-decoded-arglist
	     ,@(loop for keyword in '(&provided &required
                                      &optional &rest &key &any)
		     append (cddr (gethash keyword initially-clauses))
		     collect (let ((clause (gethash keyword main-clauses)))
			       (when clause
                                 (generate-main-clause clause arglist)))
		     append (cddr (gethash keyword finally-clauses)))))))))

;;;; Arglist Printing

(defun undummy (x)
  (if (typep x 'arglist-dummy)
      (arglist-dummy.string-representation x)
      (prin1-to-string x)))

(defun print-decoded-arglist (arglist &key operator provided-args highlight)
  (let ((first-space-after-operator (and operator t)))
    (macrolet ((space ()
                 ;; Kludge: When OPERATOR is not given, we don't want to
                 ;; print a space for the first argument.
                 `(if (not operator)
                      (setq operator t)
                      (progn (write-char #\space)
                             (if first-space-after-operator
                                 (setq first-space-after-operator nil)
                                 (pprint-newline :fill)))))
               (with-highlighting ((&key index) &body body)
                 `(if (eql ,index (car highlight))
                      (progn (princ "===> ") ,@body (princ " <==="))
                      (progn ,@body)))
               (print-arglist-recursively (argl &key index)
                 `(if (eql ,index (car highlight))
                      (print-decoded-arglist ,argl :highlight (cdr highlight))
                      (print-decoded-arglist ,argl))))
358
359
      (let ((index 0)
	    (key-type nil))
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        (pprint-logical-block (nil nil :prefix "(" :suffix ")")
          (when operator
            (print-arg operator)
            (pprint-indent :current 1)) ; 1 due to possibly added space
          (do-decoded-arglist (remove-given-args arglist provided-args)
            (&provided (arg)
                       (space)
                       (print-arg arg :literal-strings t)
                       (incf index))
            (&required (arg)
                       (space)
                       (if (arglist-p arg)
                           (print-arglist-recursively arg :index index)
                           (with-highlighting (:index index)
                             (print-arg arg)))
                       (incf index))
            (&optional :initially
                       (when (arglist.optional-args arglist)
                         (space)
                         (princ '&optional)))
            (&optional (arg init-value)
                       (space)
                       (if (arglist-p arg)
                           (print-arglist-recursively arg :index index)
                           (with-highlighting (:index index)
                             (if (null init-value)
                                 (print-arg arg)
                                 (format t "~:@<~A ~A~@:>"
                                         (undummy arg) (undummy init-value)))))
                       (incf index))
            (&key :initially
391
392
                  (when (and (arglist.key-p arglist)
			     (null (arglist.keyword-args arglist)))
393
394
                    (space)
                    (princ '&key)))
395
396
397
398
            (&key (keyword arg init new-type)
		  (unless (eq key-type new-type)
		    (space)
		    (princ (setq key-type new-type)))
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
                  (space)
                  (if (arglist-p arg)
                      (pprint-logical-block (nil nil :prefix "(" :suffix ")")
                        (prin1 keyword) (space)
                        (print-arglist-recursively arg :index keyword))
                      (with-highlighting (:index keyword)
                        (cond ((and init (keywordp keyword))
                               (format t "~:@<~A ~A~@:>" keyword (undummy init)))
                              (init
                               (format t "~:@<(~A ..) ~A~@:>"
                                       (undummy keyword) (undummy init)))
                              ((not (keywordp keyword))
                               (format t "~:@<(~S ..)~@:>" keyword))
                              (t
                               (princ keyword))))))
            (&key :finally
                  (when (arglist.allow-other-keys-p arglist)
                    (space)
                    (princ '&allow-other-keys)))
            (&any :initially
                  (when (arglist.any-p arglist)
                    (space)
                    (princ '&any)))
            (&any (arg)
                  (space)
                  (print-arg arg))
            (&rest (args bodyp)
                   (space)
                   (princ (if bodyp '&body '&rest))
                   (space)
                   (if (arglist-p args)
                       (print-arglist-recursively args :index index)
                       (with-highlighting (:index index)
                         (print-arg args))))
            ;; FIXME: add &UNKNOWN-JUNK?
            ))))))

436
437
438
439
440
;; Print symbol without package prefix (but escaping any special chars as usual).
(defun write-symbol-name (sym)
  (let ((*print-gensym* nil))
    (prin1 (if (or (keywordp sym) (null (symbol-package sym))) sym (make-symbol (symbol-name sym))))))

441
(defun print-arg (arg &key literal-strings)
442
443
444
445
446
447
448
449
  (declare (ignore literal-strings))
  (if (arglist-dummy-p arg)
      (princ (arglist-dummy.string-representation arg))
      (if (symbolp arg)
	  (write-symbol-name arg)
	  (let ((*print-length* 10)
		(*print-level* 3))
	    (prin1 arg)))))
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496

(defun print-decoded-arglist-as-template (decoded-arglist &key
                                          (prefix "(") (suffix ")"))
  (let ((first-p t))
    (flet ((space ()
             (unless first-p
               (write-char #\space))
             (setq first-p nil))
           (print-arg-or-pattern (arg)
             (etypecase arg
               (symbol        (if (keywordp arg) (prin1 arg) (princ arg)))
               (string        (princ arg))
               (list          (princ arg))
               (arglist-dummy (princ
                               (arglist-dummy.string-representation arg)))
               (arglist       (print-decoded-arglist-as-template arg)))
             (pprint-newline :fill)))
      (pprint-logical-block (nil nil :prefix prefix :suffix suffix)
        (do-decoded-arglist decoded-arglist
          (&provided ()) ; do nothing; provided args are in the buffer already.
          (&required (arg)
            (space) (print-arg-or-pattern arg))
          (&optional (arg)
            (space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
          (&key (keyword arg)
            (space)
            (prin1 (if (keywordp keyword) keyword `',keyword))
            (space)
            (print-arg-or-pattern arg)
            (pprint-newline :linear))
          (&any (arg)
            (space) (print-arg-or-pattern arg))
          (&rest (args)
            (when (or (not (arglist.keyword-args decoded-arglist))
                      (arglist.allow-other-keys-p decoded-arglist))
              (space)
              (format t "~A..." args))))))))

(defvar *arglist-pprint-bindings*
  '((*print-case*     . :downcase)
    (*print-pretty*   . t)
    (*print-circle*   . nil)
    (*print-readably* . nil)
    (*print-level*    . 10)
    (*print-length*   . 20)
    (*print-escape*   . nil)))

497
498
499
500
;; The default is to view symbols as if we were in the CL-USER
;; package. I can't see how this helps anybody, so I'm
;; disabling it.
(defvar *arglist-show-packages* nil)
501
502
503
504
505
506
507
508
509
510
511
512
513
514

(defmacro with-arglist-io-syntax (&body body)
  (let ((package (gensym)))
    `(let ((,package *package*))
       (with-standard-io-syntax
         (let ((*package* (if *arglist-show-packages*
                              *package*
                              ,package)))
           (with-bindings *arglist-pprint-bindings*
             ,@body))))))

(defun decoded-arglist-to-string (decoded-arglist
                                  &key operator highlight
                                  print-right-margin)
515
516
  (if (message-list-arglist-p operator decoded-arglist)
      (print-message-list-for-autodoc decoded-arglist print-right-margin)
517
518
519
520
521
522
523
      (or (find-current-argdoc decoded-arglist highlight)
	  (with-output-to-string (*standard-output*)
	    (with-arglist-io-syntax
	      (let ((*print-right-margin* print-right-margin))
		(print-decoded-arglist decoded-arglist
				       :operator operator
				       :highlight highlight)))))))
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558

(defun decoded-arglist-to-template-string (decoded-arglist
                                           &key (prefix "(") (suffix ")"))
  (with-output-to-string (*standard-output*)
    (with-arglist-io-syntax
      (print-decoded-arglist-as-template decoded-arglist
                                         :prefix prefix
                                         :suffix suffix))))

;;;; Arglist Decoding / Encoding

(defun decode-required-arg (arg)
  "ARG can be a symbol or a destructuring pattern."
  (etypecase arg
    (symbol        arg)
    (arglist-dummy arg)
    (list          (decode-arglist arg))))

(defun encode-required-arg (arg)
  (etypecase arg
    (symbol arg)
    (arglist (encode-arglist arg))))

(defstruct (keyword-arg
            (:conc-name keyword-arg.)
            (:constructor %make-keyword-arg))
  keyword
  arg-name
  default-arg)

(defun canonicalize-default-arg (form)
  (if (equalp ''nil form)
      nil
      form))

559
560
561
562
563
564
(defun make-keyword-arg (keyword &optional (arg-name nil) (default-arg nil))
  (unless arg-name
    (if (keywordp keyword)
	(setq arg-name (make-symbol (symbol-name keyword)))
	(setq arg-name keyword
	      keyword (intern-arg keyword keyword-package))))
565
566
567
568
  (%make-keyword-arg :keyword keyword
                     :arg-name arg-name
                     :default-arg (canonicalize-default-arg default-arg)))

569
;; Interns arg if it's symbol-like, otherwise returns nil
570
(defun intern-arg (arg package &optional (createp t))
571
572
  (typecase arg
    (symbol (unless (or (null arg) (eq arg +cursor-marker+))
573
574
575
	      (if createp
		  (intern (symbol-name arg) package)
		  (find-symbol (symbol-name arg) package))))
576
577
578
579
    (arglist-dummy (let ((string (arglist-dummy.string-representation arg)))
		     (unless (string= string "")
		       (unless (eq (readtable-case *readtable*) :preserve)
			 (setq string (string-upcase string)))
580
581
582
		       (if createp
			   (intern string package)
			   (find-symbol string package)))))
583
584
    (t nil)))

585
586
587
(defun decode-keyword-arg (arg)
  "Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
588
  (flet ((intern-as-keyword (arg) (intern-arg arg keyword-package)))
589
    (cond ((or (symbolp arg) (arglist-dummy-p arg))
590
           (make-keyword-arg (intern-as-keyword arg) arg))
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
          ((and (consp arg)
                (consp (car arg)))
           (make-keyword-arg (caar arg)
                             (decode-required-arg (cadar arg))
                             (cadr arg)))
          ((consp arg)
           (make-keyword-arg (intern-as-keyword (car arg))
                             (car arg) (cadr arg)))
          (t
           (error "Bad keyword item of formal argument list")))))

(defun encode-keyword-arg (arg)
  (cond
    ((arglist-p (keyword-arg.arg-name arg))
     ;; Destructuring pattern
     (let ((keyword/name (list (keyword-arg.keyword arg)
                               (encode-required-arg
                                (keyword-arg.arg-name arg)))))
       (if (keyword-arg.default-arg arg)
           (list keyword/name
                 (keyword-arg.default-arg arg))
           (list keyword/name))))
613
    ((eql (intern-arg (keyword-arg.arg-name arg) keyword-package)
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
          (keyword-arg.keyword arg))
     (if (keyword-arg.default-arg arg)
         (list (keyword-arg.arg-name arg)
               (keyword-arg.default-arg arg))
         (keyword-arg.arg-name arg)))
    (t
     (let ((keyword/name (list (keyword-arg.keyword arg)
                               (keyword-arg.arg-name arg))))
       (if (keyword-arg.default-arg arg)
           (list keyword/name
                 (keyword-arg.default-arg arg))
           (list keyword/name))))))

(progn
  (assert (equalp (decode-keyword-arg 'x)
                  (make-keyword-arg :x 'x nil)))
  (assert (equalp (decode-keyword-arg '(x t))
                  (make-keyword-arg :x 'x t)))
  (assert (equalp (decode-keyword-arg '((:x y)))
                  (make-keyword-arg :x 'y nil)))
  (assert (equalp (decode-keyword-arg '((:x y) t))
                  (make-keyword-arg :x 'y t))))

;;; FIXME suppliedp?
(defstruct (optional-arg
            (:conc-name optional-arg.)
            (:constructor %make-optional-arg))
  arg-name
  default-arg)

(defun make-optional-arg (arg-name default-arg)
  (%make-optional-arg :arg-name arg-name
                      :default-arg (canonicalize-default-arg default-arg)))

(defun decode-optional-arg (arg)
  "Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
  (etypecase arg
    (symbol        (make-optional-arg arg nil))
    (arglist-dummy (make-optional-arg arg nil))
    (list          (make-optional-arg (decode-required-arg (car arg))
                                      (cadr arg)))))

(defun encode-optional-arg (optional-arg)
  (if (or (optional-arg.default-arg optional-arg)
          (arglist-p (optional-arg.arg-name optional-arg)))
      (list (encode-required-arg
             (optional-arg.arg-name optional-arg))
            (optional-arg.default-arg optional-arg))
      (optional-arg.arg-name optional-arg)))

(progn
  (assert (equalp (decode-optional-arg 'x)
                  (make-optional-arg 'x nil)))
  (assert (equalp (decode-optional-arg '(x t))
                  (make-optional-arg 'x t))))

(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")

(defun decode-arglist (arglist)
  "Parse the list ARGLIST and return an ARGLIST structure."
  (etypecase arglist
    ((eql :not-available) (return-from decode-arglist
                            :not-available))
    (list))
  (loop
    with mode = nil
    with result = (make-arglist)
    for arg = (if (consp arglist)
                  (pop arglist)
                  (progn
                    (prog1 arglist
                      (setf mode '&rest
                            arglist nil))))
    do (cond
         ((eql mode '&unknown-junk)
          ;; don't leave this mode -- we don't know how the arglist
          ;; after unknown lambda-list keywords is interpreted
          (push arg (arglist.unknown-junk result)))
         ((eql arg '&allow-other-keys)
          (setf (arglist.allow-other-keys-p result) t))
         ((eql arg '&key)
          (setf (arglist.key-p result) t
                mode arg))
         ((memq arg '(&optional &rest &body &aux))
          (setq mode arg))
         ((memq arg '(&whole &environment))
          (setq mode arg)
          (push arg (arglist.known-junk result)))
         ((and (symbolp arg)
               (string= (symbol-name arg) (string '#:&any))) ; may be interned
          (setf (arglist.any-p result) t) ;  in any *package*.
          (setq mode '&any))
         ((memq arg lambda-list-keywords)
          (setq mode '&unknown-junk)
          (push arg (arglist.unknown-junk result)))
         (t
          (ecase mode
            (&key
               (push (decode-keyword-arg arg)
                     (arglist.keyword-args result)))
            (&optional
               (push (decode-optional-arg arg)
                     (arglist.optional-args result)))
            (&body
               (setf (arglist.body-p result) t
                     (arglist.rest result) arg))
            (&rest
               (setf (arglist.rest result) arg))
            (&aux
               (push (decode-optional-arg arg)
                     (arglist.aux-args result)))
            ((nil)
               (push (decode-required-arg arg)
                     (arglist.required-args result)))
            ((&whole &environment)
               (setf mode nil)
               (push arg (arglist.known-junk result)))
            (&any
               (push arg (arglist.any-args result))))))
        until (null arglist)
    finally (nreversef (arglist.required-args result))
    finally (nreversef (arglist.optional-args result))
    finally (nreversef (arglist.keyword-args result))
    finally (nreversef (arglist.aux-args result))
    finally (nreversef (arglist.any-args result))
    finally (nreversef (arglist.known-junk result))
    finally (nreversef (arglist.unknown-junk result))
    finally (assert (or (and (not (arglist.key-p result))
                             (not (arglist.any-p result)))
                        (exactly-one-p (arglist.key-p result)
                                       (arglist.any-p result))))
    finally (return result)))

(defun encode-arglist (decoded-arglist)
  (append (mapcar #'encode-required-arg
                  (arglist.required-args decoded-arglist))
          (when (arglist.optional-args decoded-arglist)
            '(&optional))
          (mapcar #'encode-optional-arg
                  (arglist.optional-args decoded-arglist))
          (when (arglist.key-p decoded-arglist)
            '(&key))
          (mapcar #'encode-keyword-arg
                  (arglist.keyword-args decoded-arglist))
          (when (arglist.allow-other-keys-p decoded-arglist)
            '(&allow-other-keys))
          (when (arglist.any-args decoded-arglist)
            `(&any ,@(arglist.any-args decoded-arglist)))
          (cond ((not (arglist.rest decoded-arglist))
                 '())
                ((arglist.body-p decoded-arglist)
                 `(&body ,(arglist.rest decoded-arglist)))
                (t
                 `(&rest ,(arglist.rest decoded-arglist))))
          (when (arglist.aux-args decoded-arglist)
            `(&aux ,(arglist.aux-args decoded-arglist)))
          (arglist.known-junk decoded-arglist)
          (arglist.unknown-junk decoded-arglist)))

;;;; Arglist Enrichment

(defun arglist-keywords (lambda-list)
  "Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
  (let ((decoded-arglist (decode-arglist lambda-list)))
    (values (arglist.keyword-args decoded-arglist)
	    (arglist.allow-other-keys-p decoded-arglist))))


(defun methods-keywords (methods)
  "Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
  (let ((keywords '())
	(allow-other-keys nil))
    (dolist (method methods)
      (multiple-value-bind (kw aok)
	  (arglist-keywords
	   (swank-mop:method-lambda-list method))
	(setq keywords (remove-duplicates (append keywords kw)
                                          :key #'keyword-arg.keyword)
	      allow-other-keys (or allow-other-keys aok))))
    (values keywords allow-other-keys)))

(defun generic-function-keywords (generic-function)
  "Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
  (methods-keywords
   (swank-mop:generic-function-methods generic-function)))

(defun applicable-methods-keywords (generic-function arguments)
  "Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES.  As a secondary value, return
whether &allow-other-keys appears somewhere."
  (methods-keywords
   (multiple-value-bind (amuc okp)
       (swank-mop:compute-applicable-methods-using-classes
        generic-function (mapcar #'class-of arguments))
     (if okp
         amuc
         (compute-applicable-methods generic-function arguments)))))

(defgeneric extra-keywords (operator &rest args)
   (:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))

;;; We make sure that symbol-from-KEYWORD-using keywords come before
;;; symbol-from-arbitrary-package-using keywords. And we sort the
;;; latter according to how their home-packages relate to *PACKAGE*.
;;;
;;; Rationale is to show those key parameters first which make most
;;; sense in the current context. And in particular: to put
;;; implementation-internal stuff last.
;;;
;;; This matters tremendeously on Allegro in combination with
;;; AllegroCache as that does some evil tinkering with initargs,
;;; obfuscating the arglist of MAKE-INSTANCE.
;;;

(defmethod extra-keywords :around (op &rest args)
  (declare (ignorable op args))
  (multiple-value-bind (keywords aok enrichments) (call-next-method)
    (values (sort-extra-keywords keywords) aok enrichments)))

(defun make-package-comparator (reference-packages)
  "Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
  (let ((package-use-table (make-hash-table :test 'eq)))
    ;; Walk the package dependency graph breadth-fist, and fill
    ;; PACKAGE-USE-TABLE accordingly.
    (loop with queue = (copy-list reference-packages)
	  with bfn   = 0		; Breadth-First Number
	  for p      = (pop queue)
	  unless (gethash p package-use-table)
	    do      (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
	    and do  (setf queue (nconc queue (copy-list (package-use-list p))))
	  while queue)
    #'(lambda (p1 p2)
	(let ((bfn1 (gethash p1 package-use-table))
	      (bfn2 (gethash p2 package-use-table)))
859
	  (cond ((and bfn1 bfn2) (< bfn1 bfn2))
860
861
		(bfn1            bfn1)
		(bfn2            nil)	; p2 is used, p1 not
862
		(t (string< (package-name p1) (package-name p2))))))))
863
864
865
866
867
868
869
870
871
872
873
874
875
876

(defun sort-extra-keywords (kwds)
  (stable-sort kwds (make-package-comparator (list keyword-package *package*))
               :key (compose #'symbol-package #'keyword-arg.keyword)))

(defmethod extra-keywords (operator &rest args)
  ;; default method
  (declare (ignore args))
  (let ((symbol-function (symbol-function operator)))
    (if (typep symbol-function 'generic-function)
        (generic-function-keywords symbol-function)
        nil)))

(defun class-from-class-name-form (class-name-form)
877
878
  (when (quoted-symbol-p class-name-form)
    (let ((class (find-class (cadr class-name-form) nil)))
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
      (when (and class
                 (not (swank-mop:class-finalized-p class)))
        ;; Try to finalize the class, which can fail if
        ;; superclasses are not defined yet
        (ignore-errors (swank-mop:finalize-inheritance class)))
      class)))

(defun extra-keywords/slots (class)
  (multiple-value-bind (slots allow-other-keys-p)
      (if (swank-mop:class-finalized-p class)
          (values (swank-mop:class-slots class) nil)
          (values (swank-mop:class-direct-slots class) t))
    (let ((slot-init-keywords
            (loop for slot in slots append
                  (mapcar (lambda (initarg)
                            (make-keyword-arg
                             initarg
                             (swank-mop:slot-definition-name slot)
                             (and (swank-mop:slot-definition-initfunction slot)
                                  (swank-mop:slot-definition-initform slot))))
                          (swank-mop:slot-definition-initargs slot)))))
      (values slot-init-keywords allow-other-keys-p))))

(defun extra-keywords/make-instance (operator &rest args)
  (declare (ignore operator))
  (unless (null args)
    (let* ((class-name-form (car args))
           (class (class-from-class-name-form class-name-form)))
      (when class
        (multiple-value-bind (slot-init-keywords class-aokp)
            (extra-keywords/slots class)
          (multiple-value-bind (allocate-instance-keywords ai-aokp)
              (applicable-methods-keywords
               #'allocate-instance (list class))
            (multiple-value-bind (initialize-instance-keywords ii-aokp)
                (ignore-errors
                 (applicable-methods-keywords
                  #'initialize-instance
                  (list (swank-mop:class-prototype class))))
              (multiple-value-bind (shared-initialize-keywords si-aokp)
                  (ignore-errors
                   (applicable-methods-keywords
                    #'shared-initialize
                    (list (swank-mop:class-prototype class) t)))
                (values (append slot-init-keywords
                                allocate-instance-keywords
                                initialize-instance-keywords
                                shared-initialize-keywords)
                        (or class-aokp ai-aokp ii-aokp si-aokp)
                        (list class-name-form))))))))))

(defun extra-keywords/change-class (operator &rest args)
  (declare (ignore operator))
  (unless (null args)
    (let* ((class-name-form (car args))
           (class (class-from-class-name-form class-name-form)))
      (when class
        (multiple-value-bind (slot-init-keywords class-aokp)
            (extra-keywords/slots class)
          (declare (ignore class-aokp))
          (multiple-value-bind (shared-initialize-keywords si-aokp)
              (ignore-errors
                (applicable-methods-keywords
                 #'shared-initialize
                 (list (swank-mop:class-prototype class) t)))
            ;; FIXME: much as it would be nice to include the
            ;; applicable keywords from
            ;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
            ;; how to do it: so we punt, always declaring
            ;; &ALLOW-OTHER-KEYS.
            (declare (ignore si-aokp))
            (values (append slot-init-keywords shared-initialize-keywords)
                    t
                    (list class-name-form))))))))

(defmethod extra-keywords ((operator (eql 'make-instance))
                           &rest args)
  (multiple-value-or (apply #'extra-keywords/make-instance operator args)
                     (call-next-method)))

(defmethod extra-keywords ((operator (eql 'make-condition))
                           &rest args)
  (multiple-value-or (apply #'extra-keywords/make-instance operator args)
                     (call-next-method)))

(defmethod extra-keywords ((operator (eql 'error))
                           &rest args)
  (multiple-value-or (apply #'extra-keywords/make-instance operator args)
                     (call-next-method)))

(defmethod extra-keywords ((operator (eql 'signal))
                           &rest args)
  (multiple-value-or (apply #'extra-keywords/make-instance operator args)
                     (call-next-method)))

(defmethod extra-keywords ((operator (eql 'warn))
                           &rest args)
  (multiple-value-or (apply #'extra-keywords/make-instance operator args)
                     (call-next-method)))

(defmethod extra-keywords ((operator (eql 'cerror))
                           &rest args)
  (multiple-value-bind (keywords aok determiners)
      (apply #'extra-keywords/make-instance operator
             (cdr args))
    (if keywords
        (values keywords aok
                (cons (car args) determiners))
        (call-next-method))))

(defmethod extra-keywords ((operator (eql 'change-class))
                           &rest args)
  (multiple-value-bind (keywords aok determiners)
      (apply #'extra-keywords/change-class operator (cdr args))
    (if keywords
        (values keywords aok
                (cons (car args) determiners))
        (call-next-method))))

(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords
                                             allow-other-keys-p)
  "Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
  (when keywords
    (setf (arglist.key-p decoded-arglist) t)
    (setf (arglist.keyword-args decoded-arglist)
          (remove-duplicates
           (append (arglist.keyword-args decoded-arglist)
                   keywords)
           :key #'keyword-arg.keyword)))
  (setf (arglist.allow-other-keys-p decoded-arglist)
        (or (arglist.allow-other-keys-p decoded-arglist)
            allow-other-keys-p)))

(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
  "Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them.  As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
1016
keywords."
1017
1018
1019
1020
1021
1022
  (multiple-value-bind (extra-keywords extra-aok determining-args)
      (apply #'extra-keywords form)
    ;; enrich the list of keywords with the extra keywords
    (enrich-decoded-arglist-with-keywords decoded-arglist
                                          extra-keywords extra-aok)
    (values decoded-arglist
1023
            determining-args)))
1024

1025
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms env)
1026
  (:documentation
1027
1028
   "Return two values: DECODED-ARGLIST and DETERMINING-ARGS,
just like enrich-decoded-arglist-with-extra-keywords.
1029
1030
If the arglist is not available, return :NOT-AVAILABLE."))

1031
1032
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms env)
  (declare (ignore env))
1033
1034
1035
  (with-available-arglist (decoded-arglist)
      (decode-arglist (arglist operator-form))
    (enrich-decoded-arglist-with-extra-keywords decoded-arglist
1036
1037
						(cons operator-form
						      argument-forms))))
1038
1039

(defmethod compute-enriched-decoded-arglist
1040
    ((operator-form (eql 'with-open-file)) argument-forms env)
1041
1042
1043
  (declare (ignore argument-forms))
  (multiple-value-bind (decoded-arglist determining-args)
      (call-next-method)
1044
1045
1046
1047
1048
1049
1050
1051
1052
    (when (arglist-available-p decoded-arglist)
      (let ((first-arg (first (arglist.required-args decoded-arglist)))
	    (open-arglist (compute-enriched-decoded-arglist 'open nil env)))
	(when (and (arglist-p first-arg) (arglist-p open-arglist))
	  (enrich-decoded-arglist-with-keywords
	   first-arg
	   (arglist.keyword-args open-arglist)
 	   nil))))
    (values decoded-arglist determining-args)))
1053
1054

(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
1055
					     argument-forms env)
1056
1057
1058
1059
1060
1061
1062
1063
  (let ((function-name-form (car argument-forms)))
    (when (and (listp function-name-form)
               (length= function-name-form 2)
               (memq (car function-name-form) '(quote function)))
      (let ((function-name (cadr function-name-form)))
        (when (valid-operator-symbol-p function-name)
          (let ((function-arglist
                 (compute-enriched-decoded-arglist function-name
1064
						   (cdr argument-forms) env)))
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
            (return-from compute-enriched-decoded-arglist
              (values
               (make-arglist :required-args
                             (list 'function)
                             :optional-args
                             (append
                              (mapcar #'(lambda (arg)
                                          (make-optional-arg arg nil))
                                      (arglist.required-args function-arglist))
                              (arglist.optional-args function-arglist))
                             :key-p
                             (arglist.key-p function-arglist)
                             :keyword-args
                             (arglist.keyword-args function-arglist)
                             :rest
                             'args
                             :allow-other-keys-p
                             (arglist.allow-other-keys-p function-arglist))
1083
               (list function-name-form))))))))
1084
1085
1086
  (call-next-method))

(defmethod compute-enriched-decoded-arglist
1087
1088
    ((operator-form (eql 'multiple-value-call)) argument-forms env)
  (compute-enriched-decoded-arglist 'apply argument-forms env))
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121

(defun delete-given-args (decoded-arglist args)
  "Delete given ARGS from DECODED-ARGLIST."
  (macrolet ((pop-or-return (list)
	       `(if (null ,list)
		    (return-from do-decoded-arglist)
		    (pop ,list))))
    (do-decoded-arglist decoded-arglist
      (&provided ()
       (assert (eq (pop-or-return args)
                   (pop (arglist.provided-args decoded-arglist)))))
      (&required ()
       (pop-or-return args)
       (pop (arglist.required-args decoded-arglist)))
      (&optional ()
       (pop-or-return args)
       (pop (arglist.optional-args decoded-arglist)))
      (&key (keyword)
       ;; N.b. we consider a keyword to be given only when the keyword
       ;; _and_ a value has been given for it.
       (loop for (key value) on args by #'cddr
	     when (and (eq keyword key) value)
	       do (setf (arglist.keyword-args decoded-arglist)
			(remove keyword (arglist.keyword-args decoded-arglist)
				:key #'keyword-arg.keyword))))))
  decoded-arglist)

(defun remove-given-args (decoded-arglist args)
  ;; FIXME: We actually needa deep copy here.
  (delete-given-args (copy-arglist decoded-arglist) args))

;;;; Arglist Retrieval

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
(defmethod arglist-dispatch (operator arguments env)
  (if (valid-operator-symbol-p operator) ;; TODO: what about (setf name)
      (multiple-value-bind (decoded-arglist determining-args)
	  (compute-enriched-decoded-arglist operator arguments env)
	(with-available-arglist (arglist) decoded-arglist
	  ;; replace some formal args by determining actual args
	  (setf arglist (delete-given-args arglist determining-args))
	  (setf (arglist.provided-args arglist) determining-args)
	  arglist))
      :not-available))

(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments env)
  (declare (ignore env))
1135
1136
1137
1138
1139
1140
  (match (cons operator arguments)
    (('defmethod (#'function-exists-p gf-name) . rest)
     (let ((gf (fdefinition gf-name)))
       (when (typep gf 'generic-function)
         (with-available-arglist (arglist) (decode-arglist (arglist gf))
           (let ((qualifiers (loop for x in rest
1141
                                   until (or (listp x) (empty-arg-p x) (eq x +cursor-marker+))
1142
1143
1144
1145
1146
1147
1148
1149
                                   collect x)))
             (return-from arglist-dispatch
               (make-arglist :provided-args (cons gf-name qualifiers)
                             :required-args (list arglist)
                             :rest "body" :body-p t)))))))
    (_)) ; Fall through
  (call-next-method))

1150
1151
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments env)
  (declare (ignore env))
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
  (match (cons operator arguments)
    (('define-compiler-macro (#'function-exists-p gf-name) . _)
     (let ((gf (fdefinition gf-name)))
       (with-available-arglist (arglist) (decode-arglist (arglist gf))
         (return-from arglist-dispatch
           (make-arglist :provided-args (list gf-name)
                         :required-args (list arglist)
                         :rest "body" :body-p t)))))
    (_)) ; Fall through
  (call-next-method))

1163
1164
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments env)
  (declare (ignore arguments env))
1165
1166
1167
1168
1169
    (let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
    (make-arglist
     :required-args (list (make-arglist :any-p t :any-args eval-when-args))
     :rest '#:body :body-p t)))

1170
1171
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments env)
  (declare (ignore env))
1172
1173
1174
1175
1176
  (flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
           (with-available-arglist (typespec-arglist)
               (decoded-arglist-for-type-specifier typespec)
             (make-arglist
              :required-args (list (make-arglist
1177
                                    :provided-args (and identifier (list identifier))
1178
1179
                                    :required-args (list typespec-arglist)
                                    :rest rest-var-name))))))
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
  (let* ((declaration (cons operator (last arguments)))
	 (typedecl-arglist (match declaration
			     (('declare ('type (#'consp typespec) . decl-args))
			      (%arglist-for-type-declaration 'type typespec '#:variables))
			     (('declare ('ftype (#'consp typespec) . decl-args))
			      (%arglist-for-type-declaration 'ftype typespec '#:function-names))
			     (_ :not-available))))
    (if (arglist-available-p typedecl-arglist)
        typedecl-arglist
        (match declaration
	  (('declare ((#'consp typespec) . decl-args))
	   (%arglist-for-type-declaration nil typespec '#:variables))
          (('declare (decl-identifier . decl-args))
	   (with-available-arglist (arglist)
	       (decode-arglist (declaration-arglist decl-identifier))
	     (setf (arglist.provided-args arglist) (list decl-identifier))
	     (make-arglist :required-args (list arglist))))
          (_ (make-arglist :rest '#:declaration-specifiers)))))))

(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments env)
  (arglist-dispatch 'declare arguments env))
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248

(defun decoded-arglist-for-type-specifier (type-specifier)
  (etypecase type-specifier
    (arglist-dummy :not-available)
    (cons (decoded-arglist-for-type-specifier (car type-specifier)))
    (symbol
     (with-available-arglist (arglist)
         (decode-arglist (type-specifier-arglist type-specifier))
       (setf (arglist.provided-args arglist) (list type-specifier))
       arglist))))

;;; Slimefuns

;;; We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
;;; user's point in Emacs. A RAW-FORM looks like
;;;
;;;       ("FOO" ("BAR" ...) "QUUX" ("ZURP" SWANK::%CURSOR-MARKER%))
;;;
;;; The expression before the cursor marker is the expression where
;;; user's cursor points at. An explicit marker is necessary to
;;; disambiguate between
;;;
;;;       ("IF" ("PRED")
;;;             ("F" "X" "Y" %CURSOR-MARKER%))
;;;
;;; and
;;;       ("IF" ("PRED")
;;;             ("F" "X" "Y") %CURSOR-MARKER%)

;;; Notice that for a form like (FOO (BAR |) QUUX), where | denotes
;;; user's point, the following should be sent ("FOO" ("BAR" ""
;;; %CURSOR-MARKER%)). Only the forms up to point should be
;;; considered.

(defslimefun autodoc (raw-form &key print-right-margin)
  "Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.

Second, a boolean value telling whether the returned string can be cached."
  (handler-bind ((serious-condition
                  #'(lambda (c)
                      (unless (debug-on-swank-error)
                        (let ((*print-right-margin* print-right-margin))
                          (return-from autodoc
                            (format nil "Arglist Error: \"~A\"" c)))))))
    (with-buffer-syntax ()
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
	(multiple-value-bind (form arglist obj-at-cursor form-path)
	    (find-subform-with-arglist (parse-raw-form raw-form))
	  (cond ((boundp-and-interesting obj-at-cursor)
		 (list (print-variable-to-string obj-at-cursor) nil))
		(t
		 (list
		  (with-available-arglist (arglist) arglist
		    (decoded-arglist-to-string
		     arglist
		     :print-right-margin print-right-margin
		     :operator (car form)
		     :highlight (form-path-to-arglist-path form-path
							   form
							   arglist)))
		  t)))))))
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283

(defun boundp-and-interesting (symbol)
  (and symbol
       (symbolp symbol)
       (boundp symbol)
       (not (memq symbol '(cl:t cl:nil)))
       (not (keywordp symbol))))

(defun print-variable-to-string (symbol)
  "Return a short description of VARIABLE-NAME, or NIL."
  (let ((*print-pretty* t) (*print-level* 4)
        (*print-length* 10) (*print-lines* 1)
        (*print-readably* nil)
        (value (symbol-value symbol)))
    (call/truncated-output-to-string
     75 (lambda (s)
          (without-printing-errors (:object value :stream s)
            (format s "~A ~A~S" symbol *echo-area-prefix* value))))))


1284
;; used by slime-complete-form, c-c c-s
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
(defslimefun complete-form (raw-form)
  "Read FORM-STRING in the current buffer package, then complete it
  by adding a template for the missing arguments."
  ;; We do not catch errors here because COMPLETE-FORM is an
  ;; interactive command, not automatically run in the background like
  ;; ARGLIST-FOR-ECHO-AREA.
  (with-buffer-syntax ()
    (multiple-value-bind (arglist provided-args)
        (find-immediately-containing-arglist (parse-raw-form raw-form))
      (with-available-arglist (arglist) arglist
        (decoded-arglist-to-template-string
         (delete-given-args arglist
                            (remove-if #'empty-arg-p provided-args
                                       :from-end t :count 1))
         :prefix "" :suffix "")))))

1301
;; used by slime-complete-symbol, m-t, c-c c-i 
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
(defslimefun completions-for-keyword (keyword-string raw-form)
  "Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
  (with-buffer-syntax ()
    (let ((arglist (find-immediately-containing-arglist
                    (parse-raw-form raw-form))))
      (when (arglist-available-p arglist)
        ;; It would be possible to complete keywords only if we are in
        ;; a keyword position, but it is not clear if we want that.
        (let* ((keywords
                (append (mapcar #'keyword-arg.keyword
                                (arglist.keyword-args arglist))
                        (remove-if-not #'keywordp (arglist.any-args arglist))))
               (keyword-name
                (tokenize-symbol keyword-string))
               (matching-keywords
                (find-matching-symbols-in-list
                 keyword-name keywords (make-compound-prefix-matcher #\-)))
               (converter (completion-output-symbol-converter keyword-string))
               (strings
                (mapcar converter
                        (mapcar #'symbol-name matching-keywords)))
               (completion-set
                (format-completion-set strings nil "")))
          (list completion-set
                (longest-compound-prefix completion-set)))))))

1329
1330
1331
1332
;; Code walker environment, an alist of (KEY . VAL).
;;  Mostly, KEY = local fn, VAL = arglist.
;;  Special case: KEY = +object-marker+, VAL = the current define-object form.

1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
(defvar +object-marker+ '#:define-object)

(defparameter +define-object-sections+
  '(:input-slots :computed-slots :objects :hidden-objects :functions :methods))

(defstruct object-defn
  classname
  mixins
  keys
  ;; We almost always care about this so might as well precompute.
  section
  slot-form)
1345
1346
1347

;; Record in the environment when we're inside a define-object
(defmethod extract-local-op-arglists ((operator (eql 'gendl:define-object)) args)
1348
1349
1350
1351
1352
1353
  (destructuring-bind (classname &optional (mixins nil mixins-p) &rest keys) args
    (let ((defn (cond ((or (not mixins-p) (empty-arg-p classname)) ;; entering classname
		       nil)
		      ((or (not keys) (empty-arg-p mixins)) ;; entering mixins
		       (make-object-defn :classname classname))
		      (t
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
		       (destructuring-bind (key &optional section) (plist-tail keys)
			 (if (and (consp section) (memq key +define-object-sections+))
			     (let ((slot-form (car (last section))))
			       (make-object-defn
				:classname classname :mixins mixins :keys keys
				:section key
				;; NIL if between slots e.g. ((slot-1) ^ )
				:slot-form (and (consp slot-form) slot-form)))
			     (make-object-defn
			      :classname classname :mixins mixins :keys keys)))))))
1364
      (when defn (list (cons +object-marker+ defn))))))
1365
1366
1367
1368
1369

(defun augment-env (operator args env)
  ;; Make sure to pick up the arglists of local function/macro definitions.
  (nconc (extract-local-op-arglists operator args) env))

1370
1371
1372
1373
;; If class is specified, return defn only if defines class.
(defun object-definition-in-env (env &optional class)
  (when-let (defn (cdr (assoc +object-marker+ env)))
    (when (or (null class)
1374
	      (eq (object-defn-classname defn) (class-name-or-dummy class)))
1375
1376
      defn)))

1377
;; Returns the class (name or actual class) and the message-in-progress
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
(defun the-class-in-env (operator arguments env)
  (let ((defn (object-definition-in-env env)))
    (case operator
      (gendl:the
       (when-let (class (if defn
			    (object-defn-classname defn)
			    (eval-form-to-class 'gendl:self)))
	 (the-reference-chain-class class arguments)))
      (gendl:the-child
       (when defn ;; only meaningful inside define-object
1388
1389
1390
1391
1392
	 (when-let (slot-form (and (memq (object-defn-section defn) '(:objects :hidden-objects))
				   (object-defn-slot-form defn)))
	   (when-let (classname-form (slot-form-type-form slot-form))
	     (when (quoted-symbol-p classname-form)
	       (the-reference-chain-class (cadr classname-form) arguments))))))
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
      (gendl:the-object
       ;; TODO: should we try to handle this inside define-object? seems like in practice it
       ;; always refers to something in the lexical environment, so it wouldn't work anyway.
       (unless defn
	 (when-let (class (eval-form-to-class (car arguments)))
	   (the-reference-chain-class class (cdr arguments))))))))

;; Returns a quantified category or nil.
(defun sequence-slot-form-p (key slot-form)
  (when-let (cell (assoc key '((:objects . :quantified-objects)
			       (:hidden-objects . :quantified-hidden-objects))))
1404
1405
1406
1407
    (and (consp slot-form)
	 (or (find-key :sequence (cdr slot-form))
	     (find-key :quantify (cdr slot-form)))
	 (cdr cell))))
1408

1409
1410
1411
1412
1413
(defun destrung-slot-form (slot-form)
  (loop while (and (consp slot-form) (stringp (car slot-form)))
     do (setq slot-form (cdr slot-form)))
  slot-form)
       
1414
1415
1416
1417
1418
(defun messages-from-defn (defn &key functionp sequencedp)
  (loop with classname = (object-defn-classname defn)
     with keys = (object-defn-keys defn) while keys
     for key = (pop keys) for section = (pop keys)
     when (and (memq key +define-object-sections+) (consp section))
1419
1420
     nconc (loop for raw-slot-form in section
	      for slot-form = (destrung-slot-form raw-slot-form)
1421
	      as symbol = (if (consp slot-form)
1422
			      (car slot-form)
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
			      slot-form)
	      as message = (intern-arg symbol keyword-package)
	      when (and message
			(if functionp
			    (or (eq key :functions)
				(sequence-slot-form-p key slot-form))
			    (unless (and (eq section :functions)
					 (consp slot-form)
					 (required-args-p (cadr slot-form)))
			      ;; TODO: This is copied from what old code did, but is it right?
			      ;;   This makes it so inside THE-CHILD of a sequenced object, we can
			      ;;   refer to other quantified objects without a quantifier.
			      ;; see also gendl-local-messages
			      (or sequencedp
				  (not (sequence-slot-form-p key slot-form))))))
	      collect (make-message-arg :keyword message
					:classname classname
					:section key
					:slot-form (if (consp slot-form) slot-form (list slot-form))))))

(defun message-arglist-from-defn (defn operator)
  (when-let (message (intern-arg operator keyword-package))
    (loop with keys = (object-defn-keys defn) while keys
       for key = (pop keys) for section = (pop keys)
       thereis (and (memq key +define-object-sections+)
		    (consp section)
1449
1450
		    (loop for raw-slot-form in section
		       as slot-form = (destrung-slot-form raw-slot-form)
1451
		       as symbol = (if (consp slot-form)
1452
				       (car slot-form)
1453
1454
				       slot-form)
		       when (eq message (intern-arg symbol keyword-package))
1455
		       return (unless (and (eq raw-slot-form (object-defn-slot-form defn))
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
					   (eq key :functions)
					   (or (null (cddr slot-form))
					       (not (listp (cadr slot-form)))))
				(decode-arglist (cond ((eq key :functions)
						       (cadr slot-form))
						      ((sequence-slot-form-p key slot-form)
						       '(gendl::index))
						      (t ())))))))))

;; [gendl] make your own defparameter for now, but flag it that it
;; might be redundant with something we already have defined
(defparameter *internal-packages*
  (loop for designator in
        '(:gendl :geom-base :surf :gwl :yadd :tasty)
        collect
        (find-package designator)))

(defparameter *messages-to-suppress*
  (list ;; from vanilla-mixin*:
        :aggregate :all-mixins :children-uncached :direct-mixins :documentation
	:hidden? :leaves-uncached :message-documentation :message-list :mixins :name-for-display
	:restore-all-defaults! :restore-tree! :root :root-path-local :root? :safe-children
	:safe-hidden-children :slot-documentation :slot-source :slot-status :update! :visible-children
	:write-snapshot
        ;; from base-object:
        :image-file :local-bbox :local-box :local-center :local-center*
        :local-orientation :obliqueness
        ))

(defparameter *messages-to-suppress-when-not-sequence-member*
  (list* :first? :index :last? :next :previous
	 *messages-to-suppress*))

1489
(defun direct-messages-from-class (class requiredp optionalp functionp sequencedp)
1490
  "Return a list of messages. Take anything from a user-defined class (not
1491
1492
1493
1494
1495
1496
1497
in one of the *internal-packages*), otherwise filter for non-nil message-remarks.
If requiredp is true, only return required input slots
else if optionalp is true, only return optional input slots
else if functionp is true, only return function and quantified object messages.
else eliminate any function messages with required keywords, and
    then furthermore, if sequencep is false, eliminate quantified object as well.
"
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
  (let* ((classname (safe-class-name class))
	 (suppress (and (find (symbol-package classname) *internal-packages*)
			(if sequencedp
			    *messages-to-suppress*
			    *messages-to-suppress-when-not-sequence-member*))))
    (when-let (prototype (and (not (find classname '(gendl::gdl-basis standard-object t)))
			      (gendl-class-prototype class)))
      (flet ((filter (category keyword)
	       (when (or (null suppress) ;; following restrictions only for internal classes
			 (and (not (memq keyword suppress))
			      (gendl:the-object prototype (message-remarks keyword))))
1509
1510
1511
1512
1513
		 (cond (requiredp (eq category :required-input-slots))
		       (optionalp
			(and (memq category '(:optional-input-slots :settable-optional-input-slots
					       :defaulted-input-slots :settable-defaulted-input-slots))
			     (or (null suppress) (not (internal-name-p keyword)))))
Gail Zacharias's avatar
Gail Zacharias committed
1514
		       (functionp (memq category '(:functions :quantified-objects :quantified-hidden-objects)))
1515
1516
1517
1518
1519
1520
1521
1522
1523
		       (t 
			(unless (and (eq category :functions)
				     (required-args-p (car (gendl-source classname keyword))))
			  ;; TODO: This is copied from what old code did, but is it right?
			  ;;   This makes it so inside THE-CHILD of a sequenced object, we can
			  ;;   refer to other quantified objects without a quantifier.
			  ;; see also messages-from-defn
			  (or sequencedp
			      (not (memq category '(:quantified-objects :quantified-hidden-objects))))))))))
1524
1525
1526
1527
1528
1529
1530
1531
1532
	(let* ((plist (gendl:the-object prototype (:message-list :message-type :local
								 :return-category? t
								 :filter #'filter)))
	       (messages (loop for (message category) on plist by #'cddr
			    collect (make-message-arg :keyword message
						      :classname classname
						      :category category))))
	  (sort messages #'string< :key #'message-arg-keyword))))))

1533
1534
1535
1536
1537
1538
(defun all-messages-from-class (class env &key requiredp optionalp functionp sequencedp)
  (delete-duplicates
   (loop for class in (gendl-superclasses-in-env class env)
      nconc (direct-messages-from-class class requiredp optionalp functionp sequencedp))
   :key #'keyword-arg.keyword
   :from-end t))
1539
1540
1541

(defun message-arglist-from-class (class message)
  (when-let (category (gendl-category class message))
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
    (with-available-arglist (arglist)
	(decode-arglist
	 (case category
	   (:functions (car (gendl-source class message)))
	   ((:quantified-objects :quantified-hidden-objects) '(gendl::index))
	   (t '())))
      (setf (arglist.doc-plist arglist) (gendl-arglist-doc class message))
      arglist)))

(defun parse-gendl-arglist-doc (string &optional (keywords '(:arguments :&optional :&key :&rest :&body)))
  (let ((revplist nil)
	(in-pre? nil)
	(key nil)
	(key-end nil))
    (flet ((collect (key start &optional (end (length string)))
	     (when (eq key :args) (setq key :arguments))
	     (when (and key (or (null keywords) (member key keywords)))
	       (let ((val (if (member key '(:arguments :&optional :&key :&rest :&body))
			      (loop while (< start end)
				 as val = (multiple-value-bind (val idx)
					      (read-from-string string nil string :start start :end end)
					    (setq start idx)
					    val)
				 unless (eq val string) collect val)
			      (subseq string start end))))
		 ;; Sometimes the surrounding parens are there, sometimes not...
		 (when (and (consp val) (null (cdr val))) (setq val (car val)))
		 (setq revplist (list* val key revplist))))))
      (loop
	 for start = 0 then (1+ end)
	 for end = (position #\newline string :start start)
	 do (cond ((search "<pre>" string :start2 start :end2 end) (setq in-pre? t))
		  ((search "</pre>" string :start2 start :end2 end) (setq in-pre? nil)))
	 do (unless in-pre?
	      (when-let (pos (position-if-not #'whitespacep string :start start :end end))
		;; non-blank line.
		(when (or (eql (aref string pos) #\:)
			  (let ((epos (position-if-not #'upper-case-p string :start pos :end end)))
			    (and (or (null epos) (whitespacep (aref string epos)))
				 (> (or epos (length string)) (+ pos 3)))))
		  (collect key key-end start)
		  (let ((*package* keyword-package))
		    (multiple-value-setq (key key-end)
		      (read-from-string string t nil :start start :end end))))))
	 do (when (null end)
	      (collect key key-end)
	      (return)))
      (nreverse revplist))))

(defun gendl-arglist-doc (class arg)
  (when-let (proto (gendl-class-prototype class))
    (when-let (message (intern-arg arg keyword-package nil))
      (when-let (doc (cadr (gendl:the-object proto (:slot-documentation message))))
	(when (stringp doc)
	  (parse-gendl-arglist-doc doc))))))

(defun find-argdoc-by-name (arg doc-plist)
  (let ((string (if (arglist-dummy-p arg)
		    (arglist-dummy.string-representation arg)
		    (symbol-name arg))))
    (flet ((match (arg)
	     (loop while (consp arg) do (setq arg (car arg)))
	     (and (symbolp arg) (string-equal (symbol-name arg) string))))
      (loop for (nil arg-info) on doc-plist by #'cddr
	 ;; It looks like sometimes we get a plist and sometimes an alist
	 thereis (if (every #'consp arg-info)
		     (loop for (arg doc) in arg-info when (match arg) return doc)
		     (loop for (arg doc) on arg-info by #'cddr when (match arg) return doc))))))

(defun find-argdoc-by-position (index doc-plist)
  (flet ((fetch (list)
	   (let ((len (length list)))
	     (cond ((every #'consp list)
		    (when (< index len)
		      (return-from find-argdoc-by-position (cadr (nth index list))))
		    (decf index len))
		   (t (let ((pindex (1+ (* index 2))))
			(when (< pindex len)
			  (return-from find-argdoc-by-position (nth pindex list))))
		      (decf index (ceiling len 2)))))))
    (fetch (getf doc-plist :arguments))
    (fetch (getf doc-plist :&optional))
    nil))

(defun find-current-argdoc (arglist highlight)
  (when-let (cur-index (car highlight))
    (when-let (doc-plist (arglist.doc-plist arglist))
      (let* ((index 0)
	     (arg (do-decoded-arglist arglist
		    (&provided () (incf index))
		    (&required (arg)
			       (when (eql index cur-index)
				 (return-from do-decoded-arglist arg))
			       (incf index))
		    (&optional (arg)
			       (when (eql index cur-index)
				 (return-from do-decoded-arglist arg))
			       (incf index))
		    (&key (keyword)
			  (when (eql keyword cur-index)
			    (setq index nil)
			    (return-from do-decoded-arglist keyword)))
		    (&rest (arg)
			   (when (eq index cur-index)
			     (setq index nil)
			     (return-from do-decoded-arglist arg))))))
	(when-let (doc (and arg
			    ;; we don't have doc for structured arglists, so just punt
			    (not (arglist-p arg))
			    (or (find-argdoc-by-name arg doc-plist)
				(and index (find-argdoc-by-position index doc-plist)))))
	  (concatenate 'string
		       (with-output-to-string (*standard-output*) (print-arg arg))
		       " - "
		       (gdl-clean-doc doc)))))))
1657
1658

;; If parent is a THE form, get the arglist of functional message named by operator.
1659
1660
(defun message-arglist (operator env the-form)
  (when-let (class (the-class-in-env (car the-form) (cdr the-form) env))
1661
1662
1663
1664
1665
    (or (when (or (eq operator 'gendl:evaluate)
		  (and (consp operator) (eq (car operator) 'gendl:evaluate)))
	  (decode-arglist '(gendl::expression)))
	(when-let (defn (object-definition-in-env env class))
	  (message-arglist-from-defn defn operator))
1666
1667
1668
1669
	(message-arglist-from-class class operator)
	(when-let (defn (object-definition-in-env env class))
	  (loop for superclass in (object-defn-mixins defn)
	     thereis (message-arglist-from-class superclass operator))))))
1670

1671
1672
(defparameter *extra-object-slot-keyword-args*
  (mapcar #'make-keyword-arg '(gendl::type gendl::sequence gendl::parameters gendl::pass-down gendl::pseudo-inputs)))
1673
1674
1675
1676
1677
1678

(defun slot-form-arglist (key slot-form env)
  (or (and (memq key '(:objects :hidden-objects))
	   (object-slot-form-arglist slot-form env))
      (when-let (source (case key
			  ((:objects :hidden-objects)
1679
			   `(slot-name &key ,.(mapcar #'keyword-arg.arg-name *extra-object-slot-keyword-args*) &allow-other-keys))
1680
1681
1682
			  ((:functions)
			   `(slot-name lambda-list &body body))
			  ((:input-slots)
1683
			   '(slot-name &optional default-value &any settable defaulting))
1684
			  ((:computed-slots)
1685
			   '(slot-name &optional default-value &any settable))))
1686
1687
1688
	;; If have slot-name, don't include it.
	(when (and (cdr slot-form) (not (empty-arg-p (car slot-form))))
	  (pop source))
1689
1690
	(decode-arglist source))
      :not-available))
1691
1692

(defun object-slot-form-arglist (slot-form env)
1693
1694
1695
1696
1697
  (when-let (classname-form (slot-form-type-form slot-form))
    (with-available-arglist (arglist)
	(operator-arglist 'gendl:make-object (cons classname-form (cdr slot-form)) env)
      (pop (arglist.required-args arglist)) ;; remove the type arg.
      (setf (arglist.rest arglist) nil)
1698
      (unless (arglist.key-p arglist)
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
	(setf (arglist.allow-other-keys-p arglist) t)
	(setf (arglist.key-p arglist) t))
      (let ((provided-keys (loop for (key val . rest) = (cdr slot-form) then rest
			      while (and rest (not (empty-arg-p val)))
			      when (keywordp key) collect key)))
	(setf (arglist.keyword-args arglist)
	      (remove-if (lambda (key-arg)
			   (memq (keyword-arg.keyword key-arg) provided-keys))
			 (nconc (arglist.keyword-args arglist)
				*extra-object-slot-keyword-args*))))
1709
      arglist)))
1710

1711
1712
1713
1714
1715
1716
1717
1718
1719
(defun local-function-arglist (operator env)
  (when-let (entry (assoc operator env :test (lambda (op1 op2)
					       (cond ((and (symbolp op1) (symbolp op2))
						      (eq op1 op2))
						     ((and (arglist-dummy-p op1) (arglist-dummy-p op2))
						      (string= (arglist-dummy.string-representation op1)
							       (arglist-dummy.string-representation op2)))))))
    (decode-arglist (cdr entry))))

1720
1721
1722
1723
1724
(defun operator-arglist (operator arguments env)
  (or (local-function-arglist operator env)
      (arglist-dispatch operator arguments env)
      :not-available))

1725
1726
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

1727
(defun grovel-for-cursor (form env)
1728
  "Returns two values: the innermost functional form containing the +CURSOR-MARKER+, and the
1729
  decoded arglist for the form.
1730
1731

  Descend FORM top-down, always taking the rightmost branch, until +CURSOR-MARKER+. Then
1732
  climb up to first form with a known operator."
1733
  (when (consp form) ;; fail if we're inside a vector or something weird like that
1734
1735
1736
    (let ((operator (car form))
	  (arguments (cdr form)))
      (multiple-value-bind (inner-form arglist) (grovel-for-inner-cursor operator form env)
1737
	(if inner-form
1738
	    (values inner-form arglist)
1739
1740
	    ;; Nothing known deeper in, so we're the lowest level.  See if OPERATOR is known.
	    (let ((arglist (operator-arglist operator arguments env)))
1741
1742
	      (when (arglist-available-p arglist)
		(values form arglist))))))))
1743

1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
;; Return the subform/arglist for the innermost subform of FORM with known arglist, or NIL if there
;; aren't any, i.e. it returns NIL if FORM itself maybe the innermost potentially-known subform.
(defmethod grovel-for-inner-cursor ((operator t) form env)
  (let ((env (augment-env operator (cdr form) env)))
    (and (consp form) (grovel-for-cursor (car (last form)) env))))

;; Don't descend QUOTE because it's just data
(defmethod grovel-for-inner-cursor ((operator (eql 'cl:quote)) form env)
  (declare (ignore form env))
  nil)

;; Don't descend declarations because some typespecs clash with function names.
(defmethod grovel-for-inner-cursor ((operator (eql 'cl:declare)) form env)
  (declare (ignore form env))
  nil)
(defmethod grovel-for-inner-cursor ((operator (eql 'cl:declaim)) form env)
  (declare (ignore form env))
  nil)

;; exit BLOCK if FORM is or contains a known subform.
(defmacro exit-grovel-if-known (block form env)
  `(multiple-value-bind (_inner-form _inner-arglist) (grovel-for-cursor ,form ,env)
     (when _inner-form
       (return-from ,block (values _inner-form _inner-arglist)))))

(defmethod grovel-for-inner-cursor ((operator (eql 'gendl:define-object)) form env)
  (when-let (keys (cdddr form))
    (destructuring-bind (key &optional section) (plist-tail keys)
      (when (consp section)
	(let ((slot-form (car (last section))))
	  (when (consp slot-form)
	    ;; TODO: augment-env inline since already did all the destructuring.
	    (let ((env (augment-env operator (cdr form) env)))
	      (exit-grovel-if-known grovel-for-inner-cursor (car (last slot-form)) env)
	      (let ((arglist (slot-form-arglist key slot-form env)))
		(when (arglist-available-p arglist)
		  (values slot-form arglist))))))))))

(defmethod grovel-for-inner-cursor ((operator (eql 'gendl:the)) form env)
  (grovel-for-inner-cursor-in-THE form env))

(defmethod grovel-for-inner-cursor ((operator (eql 'gendl:the-object)) form env)
  (grovel-for-inner-cursor-in-THE form env))

(defmethod grovel-for-inner-cursor ((operator (eql 'gendl:the-child)) form env)
  (grovel-for-inner-cursor-in-THE form env))

(defun grovel-for-inner-cursor-in-THE (the-form env)
  (let ((message-form (car (last the-form))))
    (when (consp message-form)
      (exit-grovel-if-known grovel-for-inner-cursor-in-THE (car (last message-form)) env)
      (let* ((message (car message-form))
	     (arglist (or (message-arglist message env the-form)
			  (operator-arglist message (cdr message-form) env))))
	(when (arglist-available-p arglist)
	  (values message-form arglist))))))

(defun plist-tail (plist)
  (loop for last = plist then next for next = (cddr last)
     when (null next) return last))

1805
(defun find-subform-with-arglist (form)
1806
1807
1808
1809
1810
1811
1812