Debian Codegraph @

src/cmp/cmputil.lsp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; indent-tabs-mode: nil; Package: C -*-
2 ;;;; vim: set filetype=lisp tabstop=8 shiftwidth=2 expandtab:
3
4 ;;;;
5 ;;;; CMPUTIL -- Miscellaneous Functions.
6
7 ;;;; Copyright (c) 1984, Taiichi Yuasa and Masami Hagiya.
8 ;;;; Copyright (c) 1990, Giuseppe Attardi.
9 ;;;;
10 ;;;; See file 'LICENSE' for the copyright details.
11
12 (in-package "COMPILER")
13
14 ;; Return a namestring for a path that is sufficiently
15 ;; unambiguous (hopefully) for the C compiler (and associates)
16 ;; to decipher.
17 (defun brief-namestring (path)
18 ;; In Windows we cannot use enough-namestring in the compiler
19 ;; because it breaks down when using paths such as
20 ;; c:/docume~1/juanjo/locals~1/temp/foo.tmp. enough-namestring would
21 ;; return /docume~1/juanjo/locals~1/temp/foo.tmp which is not found
22 (when (wild-pathname-p path)
23 (error "Cannot coerce ~A to a physical filename~%" path))
24 #+windows
25 (namestring (si:coerce-to-file-pathname path))
26 #-windows
27 (enough-namestring (si:coerce-to-file-pathname path)))
28
29 (defun normalize-build-target-name (target)
30 (ecase target
31 ((:shared-library :dll :standalone-shared-library :standalone-dll) :shared-library)
32 ((:static-library :lib :standalone-static-library :standalone-lib) :static-library)
33 ((:fasl :fasb) :fasl)
34 (:program :program)))
35
36 (defun innermost-non-expanded-form (form)
37 (when (listp form)
38 (loop with output = nil
39 for f in form
40 do (cond ((eq f 'macroexpand)
41 (setf output nil))
42 ((null output)
43 (setf output f)))
44 finally (return output))))
45
46 (defun do-compilation-unit (closure &key override)
47 (cond (override
48 (let* ((*active-protection* nil))
49 (do-compilation-unit closure)))
50 ((null *active-protection*)
51 (let* ((*active-protection* t)
52 (*pending-actions* nil))
53 (unwind-protect (do-compilation-unit closure)
54 (loop for action in *pending-actions*
55 do (funcall action)))))
56 (t
57 (funcall closure))))
58
59 (defmacro with-compilation-unit ((&rest options) &body body)
60 `(do-compilation-unit #'(lambda () ,@body) ,@options))
61
62 (defmacro with-compiler-env ((compiler-conditions) &body body)
63 `(let ((*compiler-conditions* nil))
64 (declare (special *compiler-conditions*))
65 (restart-case
66 (handler-bind ((compiler-note #'handle-compiler-note)
67 (warning #'handle-compiler-warning)
68 (compiler-internal-error #'handle-compiler-internal-error)
69 (compiler-error #'handle-compiler-error)
70 (serious-condition #'handle-compiler-internal-error))
71 (mp:with-lock (mp:+load-compile-lock+)
72 (let ,+init-env-form+
73 (with-compilation-unit ()
74 ,@body))))
75 (abort ()))
76 (setf ,compiler-conditions *compiler-conditions*)))
77
78 (defun safe-list-length (l)
79 ;; Computes the length of a proper list or returns NIL if it
80 ;; is a circular list or terminates with a non-NIL atom.
81 (declare (optimize (speed 3) (safety 0)))
82 (loop with slow = l
83 with fast = l
84 with flag = t
85 for l of-type fixnum from 0
86 do (cond ((null fast)
87 (return l))
88 ((not (consp fast))
89 (return nil))
90 (flag
91 (setf flag nil
92 fast (cdr (ext:truly-the cons fast))))
93 ((eq slow fast)
94 (return nil))
95 (t
96 (setf flag t
97 slow (cdr (ext:truly-the cons slow))
98 fast (cdr (ext:truly-the cons fast)))))
99 finally (return l)))
100
101 (defun check-args-number (operator args &optional (min 0) (max most-positive-fixnum))
102 (let ((l (safe-list-length args)))
103 (when (null l)
104 (let ((*print-circle* t))
105 (cmperr "Improper or circular list passed to ~A~%~A" operator args)))
106 (when (< l min)
107 (too-few-args operator min l))
108 (when (and max (> l max))
109 (too-many-args operator max l))))
110
111 (defun print-current-form ()
112 (when *compile-print*
113 (let ((*print-length* 2)
114 (*print-level* 2))
115 (format t "~&;;; Compiling ~s.~%"
116 (innermost-non-expanded-form *current-toplevel-form*))))
117 nil)
118
119 (defun cmpprogress (&rest args)
120 (when *compile-verbose*
121 (apply #'format t args)))
122
123 (defun cmp-eval (form &optional (env *cmp-env*))
124 (handler-case (si:eval-with-env form env nil t :execute)
125 (serious-condition (c)
126 (when *compiler-break-enable*
127 (invoke-debugger c))
128 (cmperr "The form ~s was not evaluated successfully.~%Error detected:~%~A"
129 form c)
130 nil)))
131
132 (defun cmp-expand-macro (fd form &optional (env *cmp-env*))
133 (handler-case
134 (let ((new-form (funcall *macroexpand-hook* fd form env)))
135 (values new-form (not (eql new-form form))))
136 (serious-condition (c)
137 (when *compiler-break-enable*
138 (invoke-debugger c))
139 (cmperr "The macro form ~s was not expanded successfully.~%Error detected:~%~A"
140 form c)
141 (values nil nil))))
142
143 (defun cmp-expand-compiler-macro (fd fname args &optional (env *cmp-env*))
144 (handler-case
145 (cmp-expand-macro fd (list* fname args) env)
146 (serious-condition (c)
147 (do-cmpwarn 'compiler-macro-expansion-failed
148 :format-control "The expansion of the compiler macro~%~T~A~%was aborted because of a serious condition~%~A" :format-arguments (list fname c))
149 (values nil nil))))
150
151 (defun lisp-to-c-name (obj)
152 "Translate Lisp object prin1 representation to valid C identifier name"
153 (and obj
154 (map 'string
155 #'(lambda (c)
156 (let ((cc (char-code c)))
157 (if (or (<= #.(char-code #\a) cc #.(char-code #\z))
158 (<= #.(char-code #\0) cc #.(char-code #\9)))
159 c #\_)))
160 (string-downcase (prin1-to-string obj)))))
161
162 (defun collect-lines (stream)
163 (loop for line = (read-line stream nil nil)
164 while line
165 collect line))
166
167 (defmacro define-compiler-macro* (name lambda-list &body body)
168 "A version of define-compiler-macro that helps avoiding incorrect
169 evaluation order and double evaluation.
170
171 Example: A naive (simplified) definition of the compiler macro for
172 make-array could look as follows
173
174 (define-compiler-macro make-array (&whole form dimensions &key (element-type t) ...)
175 (let ((dimensions-type (guess-array-dimensions-type dimensions)))
176 (if (and (listp dimensions-type)
177 (null (rest dimensions-type))
178 (integerp (first dimensions-type)))
179 `(si::make-vector ,element-type ,(first dimensions-type) ...)
180 `(si::make-pure-array ,element-type ,dimensions ...))))
181
182 However this has several problems: first element-type and dimensions
183 are evaluated in the wrong order and second the compiler macro will
184 not accept perfectly valid forms like
185
186 (let ((etype :element-type))
187 (make-array 10 etype 'character))
188
189 A correct version could be implemented using define-compiler-macro* as
190 follows
191
192 (define-compiler-macro make-array (&whole form dimensions &key (element-type t) ...)
193 (let ((dimensions-type (guess-array-dimensions-type dimensions)))
194 (if (and (listp dimensions-type)
195 (null (rest dimensions-type))
196 (integerp (first dimensions-type)))
197 `(si::make-vector ,%element-type ,(first dimensions-type) ...)
198 `(si::make-pure-array ,%element-type ,%dimensions ...))))
199
200 which would expand (make-array dim :element-type 'character) to
201
202 (let ((#:dimensions dim)
203 (#:element-type 'character))
204 (si::make-pure-array #:element-type #:dimensions))
205
206 Note that dimensions and element-type are evaluated in the correct
207 order. In the case of (let ((etype :element-type))
208 (make-array 10 etype 'character))
209 the corrected version using define-compiler-macro* will simply
210 decline to produce an expansion. On the other hand, for
211 (make-array 10 :element-type 'character), the corrected version would
212 expand to
213
214 (let ((#:dimensions 10)
215 (#:element-type 'character))
216 (si::make-vector #:element-type 10))
217
218
219 How it works:
220
221 For each argument two let bindings are established: one for the
222 variable holding the actual argument and one for a symbol (prefixed
223 with %) which will be bound to the value that the argument evaluates
224 to. In the compiler macro expansion, the % prefixed symbols are
225 evaluated in the order in which the corresponding arguments are given
226 to the compiler macro.
227
228 This allows the compiler-macro to look at the actual form provided for
229 the arguments and also use these values produced by these forms in the
230 final expansion.
231
232 Keyword arguments are handled specially: we try to match keywords in
233 the list of arguments to the compiler macro to the corresponding &key
234 arguments, but if we a non-keyword form in place where we expect a
235 keyword argument, the compiler-macro declines to provide an expansion.
236 "
237 ;; General info: parsing happens in three steps. In the first pass,
238 ;; the keyword arguments given to the compiler-macro are matched.
239 ;; Then the body of the compiler macro is evaluated. In the second
240 ;; pass, let bindings are constructed in the correct order for all
241 ;; arguments given to the compiler macro. In the third pass, let
242 ;; bindings for default initforms of arguments not given to the
243 ;; compiler-macro are constructed.
244 (ext:with-unique-names (;; local vars
245 given-keyword given-arg some-keyword-found output
246 all-found-keywords
247 ;; bindings-for-expansion: these bindings
248 ;; are active around the expansion returned
249 ;; by the compiler macro
250 bindings-for-expansion)
251 (let* ((whole (gensym)) ; symbol for &whole compiler-macro argument
252 (new-lambda-list (list whole '&whole)) ; lambda-list after we have stripped out &key, collected in reverse order
253 aux-setf-forms ; forms for &aux vars
254 parse-forms-pass1 parse-forms-pass2 parse-forms-pass3 ; lists of parse-forms generated below
255 keyword-parse-forms-pass2
256 ;; bindings-for-body: these bindings are active around the
257 ;; body of the compiler macro
258 (bindings-for-body (list all-found-keywords bindings-for-expansion)))
259 ;; lambda-list handling:
260 ;; 1. extract &whole and &environment
261 (when (eq (first lambda-list) '&whole)
262 (push `(,(second lambda-list) ,whole) bindings-for-body)
263 (setf lambda-list (cddr lambda-list)))
264 (ext:when-let ((env (member '&environment lambda-list)))
265 (push '&environment new-lambda-list)
266 (push (second env) new-lambda-list)
267 (setq lambda-list (nconc (ldiff lambda-list env) (cddr env))))
268 ;; 2. parse the remaining lambda-list
269 (multiple-value-bind (reqs opts rest key-flag keywords allow-other-keys auxs)
270 (si:process-lambda-list lambda-list 'si:macro)
271 (when (and rest (or key-flag allow-other-keys))
272 (error "define-compiler-macro* can't deal with lambda-lists with both &key and &rest arguments"))
273 ;; utility functions
274 (labels ((prefix-symbol (s)
275 (intern (concatenate 'string "%" (symbol-name s))))
276 (pass1-parse ()
277 (when key-flag
278 `(progn
279 (unless (zerop (mod (length ,rest) 2))
280 (return-from ,name ,whole))
281 (loop for ,given-keyword in ,rest by #'cddr
282 for ,given-arg in (rest ,rest) by #'cddr
283 for ,some-keyword-found = nil
284 do (when (or (not (keywordp ,given-keyword))
285 (eq ,given-keyword :allow-other-keys))
286 (return-from ,name ,whole))
287 ,@parse-forms-pass1
288 (when (not ,some-keyword-found)
289 (if ,allow-other-keys
290 (push
291 ;; &allow-other-keys: we still
292 ;; have to evaluate the argument
293 `(list ,(gensym) ,,given-arg)
294 ,bindings-for-expansion)
295 (return-from ,name ,whole)))))))
296 (handle-required-parameter (symbol)
297 (let ((%symbol (prefix-symbol symbol)))
298 (push `(,%symbol (gensym)) bindings-for-body)
299 (push symbol new-lambda-list)
300 (push `(push (list ,%symbol ,symbol) ,bindings-for-expansion)
301 parse-forms-pass2)))
302 (handle-optional-parameter (opt-spec)
303 (let* ((symbol (first opt-spec))
304 (init (second opt-spec))
305 (supplied-p (or (third opt-spec) (gensym)))
306 (%symbol (prefix-symbol symbol)))
307 (push `(,%symbol (gensym)) bindings-for-body)
308 (push `(,symbol ,init ,supplied-p) new-lambda-list)
309 (push `(when ,supplied-p
310 (push (list ,%symbol ,symbol) ,bindings-for-expansion))
311 parse-forms-pass2)
312 (push `(unless ,supplied-p
313 (push (list ,%symbol ,symbol) ,bindings-for-expansion))
314 parse-forms-pass3)))
315 (handle-keyword-parameter (key-spec)
316 (let* ((keyword (first key-spec))
317 (symbol (second key-spec))
318 (init (third key-spec))
319 (supplied-p (or (fourth key-spec) (gensym)))
320 (%symbol (prefix-symbol symbol)))
321 (push `(,%symbol (gensym)) bindings-for-body)
322 (push `(,symbol ,init) bindings-for-body)
323 (push `(,supplied-p nil) bindings-for-body)
324 (push `(when (and (eq ,given-keyword ,keyword)
325 (not ,supplied-p))
326 (setf ,some-keyword-found t)
327 (setf ,symbol ,given-arg)
328 (setf ,supplied-p t)
329 (push ,keyword ,all-found-keywords))
330 parse-forms-pass1)
331 (push `(when (eq ,given-keyword ,keyword)
332 (push (list ,%symbol ,symbol) ,bindings-for-expansion))
333 keyword-parse-forms-pass2)
334 (push `(unless ,supplied-p
335 (push (list ,%symbol ,symbol) ,bindings-for-expansion))
336 parse-forms-pass3))))
337 ;; 3. required, optional and rest parameters are simply
338 ;; copied to the new lambda-list
339 (mapcar #'handle-required-parameter (rest reqs))
340 (when (> (first opts) 0)
341 (push '&optional new-lambda-list)
342 (loop for o on (rest opts) by #'cdddr
343 do (handle-optional-parameter o)))
344 (when rest
345 (let ((%rest (prefix-symbol rest)))
346 (push `(,%rest (gensym)) bindings-for-body)
347 (push `(push (list ,%rest ,rest) ,bindings-for-expansion)
348 parse-forms-pass2)
349 (push '&rest new-lambda-list)
350 (push rest new-lambda-list)))
351 ;; 4. keyword parameters: first put all remaining parameters
352 ;; in a rest argument, then parse keywords from this rest
353 ;; argument
354 (when (or key-flag allow-other-keys)
355 (unless rest
356 (setf rest (gensym))
357 (push '&rest new-lambda-list)
358 (push rest new-lambda-list))
359 (loop for key-spec on (rest keywords) by #'cddddr
360 do (handle-keyword-parameter key-spec))
361 (push `(loop for ,given-keyword in (nreverse ,all-found-keywords)
362 do ,@keyword-parse-forms-pass2)
363 parse-forms-pass2))
364 ;; 5. &aux vars: these are simply set to their initforms after
365 ;; parsing of keywords has finished
366 (loop for a on (rest auxs) by #'cddr
367 do (push (first a) bindings-for-body)
368 (push `(setf ,(first a) ,(second a)) aux-setf-forms))
369 ;; 6. Finally, we are ready to create the compiler-macro definition
370 `(define-compiler-macro ,name ,(nreverse new-lambda-list)
371 (let* ,(nreverse bindings-for-body)
372 ;; parse arguments
373 ,(pass1-parse)
374 ,@aux-setf-forms
375 ;; evaluate the body of the compiler-macro
376 (let ((,output (block ,name (locally ,@body))))
377 (if (eq ,output ,whole)
378 ,whole
379 (progn
380 ,@(nreverse parse-forms-pass2)
381 ,@(nreverse parse-forms-pass3)
382 ;; create bindings for the arguments passed to the compiler-macro
383 `(let ,(nreverse ,bindings-for-expansion)
384 ,,output)))))))))))
385
386 (defun equal-with-circularity (x y)
387 "A version of equal which does not run into an infinite loop when
388 comparing circular objects."
389 ;; x0 and y0 hold pointers to previous list elements. By stepping
390 ;; through x0 and y0 only at every other invocation of
391 ;; equal-recursive, we will eventually call equal-recursive with all
392 ;; possible combinations of x and x0 respectively y and y0. The
393 ;; integer path-spec records whether we have recursively descended
394 ;; into car or cdr slots of the list structure depending on whether
395 ;; its bits are zero or one. The integer n tells us which bit of
396 ;; path-spec we have to check in order to determine whether we have
397 ;; to follow a car or cdr slot in x0 respectively y0 to follow the
398 ;; same path that lead us to x respectively y.
399 ;;
400 ;; Optimization note: the algorithm is optimized for common cases:
401 ;; it runs in linear time for non-circular lists, does not overflow
402 ;; the stack for large lists (due to the cdr cases descending
403 ;; recursively in the tail position) and does not create large
404 ;; path-spec integers for circular lists of the form #1=(a1 ... an .
405 ;; #1#) (due to the zero-bit being used to record a descent into the
406 ;; cdr slot).
407 (labels ((equal-recursive (x y x0 y0 switch path-spec n)
408 (declare (optimize (safety 0)) (ext:check-stack-overflow)
409 (fixnum n) ; INV: the number of elements is a fixnum
410 (type integer path-spec))
411 (cond ((or (not (consp x)) (not (consp y)))
412 (equal x y))
413 ((eq x y)
414 t)
415 ((and (eq x x0) (eq y y0))
416 t)
417 ((or (eq x x0) (eq y y0))
418 nil)
419 ;; INV: The compiler will perform tail call elimination here
420 ((= n -1)
421 (and (equal-recursive (car x) (car y) x y nil 1 0)
422 (equal-recursive (cdr x) (cdr y) x y nil 0 0)))
423 (switch
424 (let* ((mask (ash 1 n))
425 (x0 (if (zerop (logand path-spec mask)) (cdr x0) (car x0)))
426 (y0 (if (zerop (logand path-spec mask)) (cdr y0) (car y0))))
427 (and (equal-recursive (car x) (car y) x0 y0 nil (logior (ash (logandc2 path-spec mask) 1) 1) n)
428 (equal-recursive (cdr x) (cdr y) x0 y0 nil (ash (logandc2 path-spec mask) 1) n))))
429 (t
430 (and (equal-recursive (car x) (car y) x0 y0 t (logior (ash path-spec 1) 1) (the fixnum (1+ n)))
431 (equal-recursive (cdr x) (cdr y) x0 y0 t (ash path-spec 1) (the fixnum (1+ n))))))))
432 (equal-recursive x y nil nil t 0 -1)))
433
434 (defun type-specifier= (x y)
435 "Compares two type specifiers for syntactic equality."
436 ;; This function only checks if the arguments have the same name
437 ;; (and arguments in case of compound type specifiers) but not if
438 ;; they are aliases of each other. For example (OR REAL COMPLEX) and
439 ;; NUMBER are considered different by this function but are of
440 ;; course semantically equivalent.
441 ;;
442 ;; Note that type specifiers cannot be compared with EQUAL since in
443 ;; eql and member types the arguments have to compared using EQL.
444 (if (and (consp x) (consp y))
445 (if (and (member (first x) '(eql member))
446 (member (first y) '(eql member)))
447 (every #'eql x y)
448 (and (type-specifier= (car x) (car y))
449 (type-specifier= (cdr x) (cdr y))))
450 (eql x y)))
451
452 ;; ----------------------------------------------------------------------
453 ;; CACHED FUNCTIONS
454 ;;
455 (defmacro defun-cached (name lambda-list test &body body)
456 (let* ((cache-name (intern (concatenate 'string "*" (string name) "-CACHE*")
457 (symbol-package name)))
458 (reset-name (intern (concatenate 'string (string name) "-EMPTY-CACHE")
459 (symbol-package name)))
460 (hash-function (case test
461 (EQ 'SI::HASH-EQ)
462 (EQL 'SI::HASH-EQL)
463 ((EQUAL EQUAL-WITH-CIRCULARITY TYPE-SPECIFIER=) 'SI::HASH-EQUAL)
464 (t (setf test 'EQUALP) 'SI::HASH-EQUALP))))
465 `(progn
466 (defvar ,cache-name
467 (make-array 1024 :element-type t :adjustable nil))
468 (defun ,reset-name ()
469 (setf ,cache-name
470 (make-array 1024 :element-type t :adjustable nil)))
471 (defun ,name ,lambda-list
472 (flet ((,name ,lambda-list ,@body))
473 (let* ((hash (logand (,hash-function ,@lambda-list) 1023))
474 (cache ,cache-name)
475 (elt (aref cache hash)))
476 (declare (type (integer 0 1023) hash)
477 (type (array t (*)) cache))
478 (if (and elt ,@(loop for arg in lambda-list
479 collect `(,test (pop (ext:truly-the cons elt)) ,arg)))
480 (first (ext:truly-the cons elt))
481 (let ((output (,name ,@lambda-list)))
482 (setf (aref ,cache-name hash) (list ,@lambda-list output))
483 output))))))))
484
485 (defun same-fname-p (name1 name2)
486 (equal name1 name2))
487
488 (defun emptyp (item)
489 (etypecase item
490 (list (null item))
491 (vector (zerop (length item)))
492 (hash-table (zerop (hash-table-count item)))))