utility.lisp 15.5 KB
Newer Older
1
2
3
;;;; -------------------------------------------------------------------------
;;;; General Purpose Utilities for ASDF

4
5
(asdf/package:define-package :asdf/utility
  (:recycle :asdf/utility :asdf)
6
  (:use :common-lisp :asdf/package :asdf/compatibility)
7
  #+gcl<2.7 (:shadowing-import-from :asdf/compatibility #:with-standard-io-syntax)
8
  (:export
9
10
11
   ;; magic helper to define debugging functions:
   #:asdf-debug #:load-asdf-debug-utility #:*asdf-debug-utility*
   #:undefine-function #:undefine-functions #:defun* #:defgeneric* ;; (un)defining functions
12
   #:if-let ;; basic flow control
13
   #:while-collecting #:appendf #:length=n-p #:remove-plist-keys #:remove-plist-key ;; lists and plists
14
15
16
   #:emptyp ;; sequences
   #:first-char #:last-char #:split-string ;; strings
   #:string-prefix-p #:string-enclosed-p #:string-suffix-p
17
   #:find-class* ;; CLOS
18
19
   #:stamp< #:stamps< #:stamp*< #:stamp<= ;; stamps
   #:earlier-stamp #:stamps-earliest #:earliest-stamp
20
21
   #:later-stamp #:stamps-latest #:latest-stamp #:latest-stamp-f
   #:list-to-hash-set ;; hash-table
22
23
   #:ensure-function #:sub-object ;; functions
   #:call-function #:call-functions #:register-hook-function
24
25
   #:match-condition-p #:match-any-condition-p ;; conditions
   #:call-with-muffled-conditions #:with-muffled-conditions
26
   #:load-string #:load-stream
27
   #:parse-version #:unparse-version #:version-compatible-p)) ;; version
28
29
(in-package :asdf/utility)

30
31
32
33
34
;;;; Defining functions in a way compatible with hot-upgrade:
;; DEFUN* and DEFGENERIC* use FMAKUNBOUND to delete any previous fdefinition,
;; thus replacing the function without warning or error
;; even if the signature and/or generic-ness of the function has changed.
;; For a generic function, this invalidates any previous DEFMETHOD.
35
36
37
(eval-when (:load-toplevel :compile-toplevel :execute)
  (defun undefine-function (function-spec)
    (cond
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
38
      ((symbolp function-spec)
39
       #+(and clisp (or))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
40
41
42
43
44
       (let ((f (and (fboundp function-spec) (fdefinition function-spec))))
         (when (typep f 'clos:standard-generic-function)
           (loop :for m :in (clos:generic-function-methods f)
                 :do (remove-method f m))))
       (fmakunbound function-spec))
45
46
47
48
49
50
51
      ((and (consp function-spec) (eq (car function-spec) 'setf)
            (consp (cdr function-spec)) (null (cddr function-spec)))
       #-(or gcl<2.7) (fmakunbound function-spec))
      (t (error "bad function spec ~S" function-spec))))
  (defun undefine-functions (function-spec-list)
    (map () 'undefine-function function-spec-list)))

52
53
54
55
(macrolet
    ((defdef (def* def)
       `(defmacro ,def* (name formals &rest rest)
          `(progn
56
57
58
59
60
61
             ;; undefining the previous function is the portable way
             ;; of overriding any incompatible previous gf, but somehow
             ;; this causes CLISP to fail to see COMPONENT-NAME methods after ugprade
             ;; so instead, for CLISP we delete-package* in package.lisp
             ;; any time the API changes.
             #-clisp
62
             (undefine-function ',name)
63
             #-gcl ; gcl 2.7.0 notinline functions lose secondary return values :-(
64
65
             ,@(when (and #+ecl (symbolp name)) ; fails for setf functions on ecl
                 `((declaim (notinline ,name))))
66
67
68
69
             (,',def ,name ,formals ,@rest)))))
  (defdef defgeneric* defgeneric)
  (defdef defun* defun))

70
71
72

;;; Magic debugging help. See contrib/debug.lisp
(defvar *asdf-debug-utility*
73
  '(ignore-errors (merge-pathnames "cl/asdf/contrib/debug.lisp" (user-homedir-pathname)))
74
75
  "form that evaluates to the pathname to your favorite debugging utilities")

76
(defmacro asdf-debug (&rest keys)
77
  `(eval-when (:compile-toplevel :load-toplevel :execute)
78
     (load-asdf-debug-utility ,@keys)))
79

80
(defun* load-asdf-debug-utility (&key package utility-file)
81
82
83
84
85
86
87
88
89
90
  (let* ((*package* (if package (find-package package) *package*))
         (keyword (read-from-string
                   (format nil ":DBG-~:@(~A~)" (package-name *package*)))))
    (unless (member keyword *features*)
      (let* ((utility-file (or utility-file *asdf-debug-utility*))
             (file (ignore-errors (probe-file (eval utility-file)))))
        (if file (load file)
            (error "Failed to locate debug utility file: ~S" utility-file))))))


91
;;; Flow control
92
93
94
95
96
97
98
99
100
101
(defmacro if-let (bindings &body (then-form &optional else-form)) ;; from alexandria
  ;; bindings can be (var form) or ((var1 form1) ...)
  (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings)))
                           (list bindings)
                           bindings))
         (variables (mapcar #'car binding-list)))
    `(let ,binding-list
       (if (and ,@variables)
           ,then-form
           ,else-form))))
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

;;; List manipulation
(defmacro while-collecting ((&rest collectors) &body body)
  "COLLECTORS should be a list of names for collections.  A collector
defines a function that, when applied to an argument inside BODY, will
add its argument to the corresponding collection.  Returns multiple values,
a list for each collection, in order.
   E.g.,
\(while-collecting \(foo bar\)
           \(dolist \(x '\(\(a 1\) \(b 2\) \(c 3\)\)\)
             \(foo \(first x\)\)
             \(bar \(second x\)\)\)\)
Returns two values: \(A B C\) and \(1 2 3\)."
  (let ((vars (mapcar #'(lambda (x) (gensym (symbol-name x))) collectors))
        (initial-values (mapcar (constantly nil) collectors)))
    `(let ,(mapcar #'list vars initial-values)
       (flet ,(mapcar #'(lambda (c v) `(,c (x) (push x ,v) (values))) collectors vars)
         ,@body
         (values ,@(mapcar #'(lambda (v) `(reverse ,v)) vars))))))

(define-modify-macro appendf (&rest args)
  append "Append onto list") ;; only to be used on short lists.

(defun* length=n-p (x n) ;is it that (= (length x) n) ?
  (check-type n (integer 0 *))
  (loop
    :for l = x :then (cdr l)
    :for i :downfrom n :do
    (cond
      ((zerop i) (return (null l)))
      ((not (consp l)) (return nil)))))

134
;;; remove a key from a plist, i.e. for keyword argument cleanup
135
(defun* remove-plist-key (key plist)
136
137
  "Remove a single key from a plist"
  (loop :for (k v) :on plist :by #'cddr
138
139
140
    :unless (eq k key)
    :append (list k v)))

141
(defun* remove-plist-keys (keys plist)
142
143
144
145
146
147
  "Remove a list of keys from a plist"
  (loop :for (k v) :on plist :by #'cddr
    :unless (member k keys)
    :append (list k v)))


148
;;; Sequences
149
(defun* emptyp (x)
150
151
152
  "Predicate that is true for an empty sequence"
  (or (null x) (and (vectorp x) (zerop (length x)))))

153

154
;;; Strings
155

156
157
158
159
160
161
162
163
164
165
166
167
(defun* first-char (s)
  (and (stringp s) (plusp (length s)) (char s 0)))

(defun* last-char (s)
  (and (stringp s) (plusp (length s)) (char s (1- (length s)))))

(defun* split-string (string &key max (separator '(#\Space #\Tab)))
  "Split STRING into a list of components separated by
any of the characters in the sequence SEPARATOR.
If MAX is specified, then no more than max(1,MAX) components will be returned,
starting the separation from the end, e.g. when called with arguments
 \"a.b.c.d.e\" :max 3 :separator \".\" it will return (\"a.b.c\" \"d\" \"e\")."
168
  (block ()
169
170
    (let ((list nil) (words 0) (end (length string)))
      (flet ((separatorp (char) (find char separator))
171
             (done () (return (cons (subseq string 0 end) list))))
172
173
174
175
176
177
178
179
180
181
        (loop
          :for start = (if (and max (>= words (1- max)))
                           (done)
                           (position-if #'separatorp string :end end :from-end t)) :do
          (when (null start)
            (done))
          (push (subseq string (1+ start) end) list)
          (incf words)
          (setf end start))))))

182
(defun* string-prefix-p (prefix string)
183
184
185
186
187
188
189
  "Does STRING begin with PREFIX?"
  (let* ((x (string prefix))
         (y (string string))
         (lx (length x))
         (ly (length y)))
    (and (<= lx ly) (string= x y :end2 lx))))

190
(defun* string-suffix-p (string suffix)
191
192
193
194
195
196
197
  "Does STRING end with SUFFIX?"
  (let* ((x (string string))
         (y (string suffix))
         (lx (length x))
         (ly (length y)))
    (and (<= ly lx) (string= x y :start1 (- lx ly)))))

198
(defun* string-enclosed-p (prefix string suffix)
199
200
201
202
  "Does STRING begin with PREFIX and end with SUFFIX?"
  (and (string-prefix-p prefix string)
       (string-suffix-p string suffix)))

203
204
205
206
207
208
209
210

;;; CLOS
(defun* find-class* (x &optional (errorp t) environment)
  (etypecase x
    ((or standard-class built-in-class) x)
    #+gcl<2.7 (keyword nil)
    (symbol (find-class x errorp environment))))

211
212
213

;;; stamps: a REAL or boolean where NIL=-infinity, T=+infinity
(deftype stamp () '(or real boolean))
214
215
216
217
218
219
220
221
(defun* stamp< (x y)
  (etypecase x
    (null (and y t))
    ((eql t) nil)
    (real (etypecase y
            (null nil)
            ((eql t) t)
            (real (< x y))))))
222
223
(defun* stamps< (list) (loop :for y :in list :for x = nil :then y :always (stamp< x y)))
(defun* stamp*< (&rest list) (stamps< list))
224
225
226
227
228
229
230
231
232
(defun* stamp<= (x y) (not (stamp< y x)))
(defun* earlier-stamp (x y) (if (stamp< x y) x y))
(defun* stamps-earliest (list) (reduce 'earlier-stamp list :initial-value t))
(defun* earliest-stamp (&rest list) (stamps-earliest list))
(defun* later-stamp (x y) (if (stamp< x y) y x))
(defun* stamps-latest (list) (reduce 'later-stamp list :initial-value nil))
(defun* latest-stamp (&rest list) (stamps-latest list))
(define-modify-macro latest-stamp-f (&rest stamps) latest-stamp)

233

234
235
236
237
;;; Hash-tables
(defun* list-to-hash-set (list &aux (h (make-hash-table :test 'equal)))
  (dolist (x list h) (setf (gethash x h) t)))

238

239
;;; Function designators
240
(defun* ensure-function (fun &key (package :cl))
241
242
243
244
245
246
247
248
249
250
  "Coerce the object FUN into a function.

If FUN is a FUNCTION, return it.
If the FUN is a non-sequence literal constant, return constantly that,
i.e. for a boolean keyword character number or pathname.
Otherwise if FUN is a non-literally constant symbol, return its FDEFINITION.
If FUN is a CONS, return the function that applies its CAR
to the appended list of the rest of its CDR and the arguments.
If FUN is a string, READ a form from it in the specified PACKAGE (default: CL)
and EVAL that in a (FUNCTION ...) context."
251
  (etypecase fun
252
    (function fun)
253
    ((or boolean keyword character number pathname) (constantly fun))
254
    ((or function symbol) fun)
255
    (cons #'(lambda (&rest args) (apply (car fun) (append (cdr fun) args))))
256
257
    (string (eval `(function ,(with-standard-io-syntax
                                (let ((*package* (find-package package)))
258
                                  (read-from-string fun))))))))
259

260
261
262
263
264
265
266
267
268
269
(defun* sub-object (object path)
  "Given an OBJECT and a PATH, list of successive accessors,
call each accessor on the result of the previous calls.
An accessor may be an integer, meaning a call to ELT,
a function or symbol, meaning itself,
or a list of a function and arguments, interpreted as per ENSURE-FUNCTION.
As a degenerate case, the PATH may be an atom of a single such accessor
instead of a list."
  (flet ((access (object accessor)
           (etypecase accessor
270
             (integer (elt object accessor))
271
272
273
274
275
276
277
             ((or function symbol) (funcall accessor object))
             (cons (funcall (ensure-function accessor) object)))))
    (if (listp path)
        (dolist (accessor path object)
          (setf object (access object accessor)))
        (access object path))))

278
279
(defun* call-function (function-spec &rest arguments)
  (apply (ensure-function function-spec) arguments))
280
281

(defun* call-functions (function-specs)
282
  (map () 'call-function function-specs))
283

284
(defun* register-hook-function (variable hook &optional (call-now-p t))
285
  (pushnew hook (symbol-value variable))
286
  (when call-now-p (call-function hook)))
287

288
289

;;; Version handling
290
291
292
293
294
295
296
297
298
299
300
301
(defun* unparse-version (version-list)
  (format nil "~{~D~^.~}" version-list))

(defun* parse-version (version-string &optional on-error)
  "Parse a VERSION-STRING as a series of natural integers separated by dots.
Return a (non-null) list of integers if the string is valid;
otherwise return NIL.

When invalid, ON-ERROR is called as per CALL-FUNCTION before to return NIL,
with format arguments explaining why the version is invalid.
ON-ERROR is also called if the version is not canonical
in that it doesn't print back to itself, but the list is returned anyway."
302
  (block nil
303
304
   (unless (stringp version-string)
     (call-function on-error "~S: ~S is not a string" 'parse-version version-string)
305
     (return))
306
   (unless (loop :for prev = nil :then c :for c :across version-string
307
308
309
310
                 :always (or (digit-char-p c)
                             (and (eql c #\.) prev (not (eql prev #\.))))
                 :finally (return (and c (digit-char-p c))))
     (call-function on-error "~S: ~S doesn't follow asdf version numbering convention"
311
                    'parse-version version-string)
312
     (return))
313
314
315
316
317
318
   (let* ((version-list
            (mapcar #'parse-integer (split-string version-string :separator ".")))
          (normalized-version (unparse-version version-list)))
     (unless (equal version-string normalized-version)
       (call-function on-error "~S: ~S contains leading zeros" 'parse-version version-string))
     version-list)))
319

320

321
322
323
324
325
(defun* version-compatible-p (provided-version required-version)
  "Is the provided version a compatible substitution for the required-version?
If major versions differ, it's not compatible.
If they are equal, then any later version is compatible,
with later being determined by a lexicographical comparison of minor numbers."
326
327
  (let ((x (parse-version provided-version 'warn))
        (y (parse-version required-version 'warn)))
328
329
330
331
332
333
334
335
336
    (labels ((bigger (x y)
               (cond ((not y) t)
                     ((not x) nil)
                     ((> (car x) (car y)) t)
                     ((= (car x) (car y))
                      (bigger (cdr x) (cdr y))))))
      (and x y (= (car x) (car y))
           (or (not (cdr y)) (bigger (cdr x) (cdr y)))))))

337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

;;; Condition control

(defvar *uninteresting-conditions* nil
  "Uninteresting conditions, as per MATCH-CONDITION-P")

(defparameter +simple-condition-format-control-slot+
  #+abcl 'system::format-control
  #+allegro 'excl::format-control
  #+clisp 'system::$format-control
  #+clozure 'ccl::format-control
  #+ecl 'si::format-control
  #+(or cmu scl) 'conditions::format-control
  #+(or gcl lispworks) 'conditions::format-string
  #+sbcl 'sb-kernel:format-control
352
  #-(or abcl allegro clisp clozure cmu ecl gcl lispworks sbcl scl) nil
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
  "Name of the slot for FORMAT-CONTROL in simple-condition")

(defun* match-condition-p (x condition)
  "Compare received CONDITION to some pattern X:
a symbol naming a condition class,
a simple vector of length 2, arguments to find-symbol* with result as above,
or a string describing the format-control of a simple-condition."
  (etypecase x
    (symbol (typep condition x))
    ((simple-vector 2) (typep condition (find-symbol* (svref x 0) (svref x 1) nil)))
    (function (funcall x condition))
    (string (and (typep condition 'simple-condition)
                 ;; On SBCL, it's always set and the check triggers a warning
                 #+(or allegro clozure cmu lispworks scl)
		 (slot-boundp condition +simple-condition-format-control-slot+)
                 (ignore-errors (equal (simple-condition-format-control condition) x))))))

(defun* match-any-condition-p (condition conditions)
  "match CONDITION against any of the patterns of CONDITIONS supplied"
  (loop :for x :in conditions :thereis (match-condition-p x condition)))

(defun* call-with-muffled-conditions (thunk conditions)
  (handler-bind ((t #'(lambda (c) (when (match-any-condition-p c conditions)
                                    (muffle-warning c)))))
    (funcall thunk)))

(defmacro with-muffled-uninteresting-conditions ((conditions) &body body)
  `(call-with-muffled-uninteresting-conditions #'(lambda () ,@body) ,conditions))