5e1f3e5c041779335612f09f7229b4095395d8ca
[sbcl.git] / src / code / host-alieneval.lisp
1 ;;;; the part of the Alien implementation which is needed at
2 ;;;; cross-compilation time
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!ALIEN")
14
15 (/show0 "host-alieneval.lisp 15")
16 \f
17 ;;;; utility functions
18
19 (defun align-offset (offset alignment)
20   (let ((extra (rem offset alignment)))
21     (if (zerop extra) offset (+ offset (- alignment extra)))))
22
23 (defun guess-alignment (bits)
24   (cond ((null bits) nil)
25         #!-x86 ((> bits 32) 64)
26         ((> bits 16) 32)
27         ((> bits 8) 16)
28         ((> bits 1) 8)
29         (t 1)))
30 \f
31 ;;;; ALIEN-TYPE-INFO stuff
32
33 (eval-when (:compile-toplevel :execute :load-toplevel)
34
35 (defstruct (alien-type-class (:copier nil))
36   (name nil :type symbol)
37   (include nil :type (or null alien-type-class))
38   (unparse nil :type (or null function))
39   (type= nil :type (or null function))
40   (lisp-rep nil :type (or null function))
41   (alien-rep nil :type (or null function))
42   (extract-gen nil :type (or null function))
43   (deposit-gen nil :type (or null function))
44   (naturalize-gen nil :type (or null function))
45   (deport-gen nil :type (or null function))
46   ;; Cast?
47   (arg-tn nil :type (or null function))
48   (result-tn nil :type (or null function))
49   (subtypep nil :type (or null function)))
50 (def!method print-object ((type-class alien-type-class) stream)
51   (print-unreadable-object (type-class stream :type t)
52     (prin1 (alien-type-class-name type-class) stream)))
53
54 (defun alien-type-class-or-lose (name)
55   (or (gethash name *alien-type-classes*)
56       (error "no alien type class ~S" name)))
57
58 (defun create-alien-type-class-if-necessary (name include)
59   (let ((old (gethash name *alien-type-classes*))
60         (include (and include (alien-type-class-or-lose include))))
61     (if old
62         (setf (alien-type-class-include old) include)
63         (setf (gethash name *alien-type-classes*)
64               (make-alien-type-class :name name :include include)))))
65
66 (defparameter *method-slot-alist*
67   '((:unparse . alien-type-class-unparse)
68     (:type= . alien-type-class-type=)
69     (:subtypep . alien-type-class-subtypep)
70     (:lisp-rep . alien-type-class-lisp-rep)
71     (:alien-rep . alien-type-class-alien-rep)
72     (:extract-gen . alien-type-class-extract-gen)
73     (:deposit-gen . alien-type-class-deposit-gen)
74     (:naturalize-gen . alien-type-class-naturalize-gen)
75     (:deport-gen . alien-type-class-deport-gen)
76     ;; cast?
77     (:arg-tn . alien-type-class-arg-tn)
78     (:result-tn . alien-type-class-result-tn)))
79
80 (defun method-slot (method)
81   (cdr (or (assoc method *method-slot-alist*)
82            (error "no method ~S" method))))
83
84 ) ; EVAL-WHEN
85
86 ;;; We define a keyword "BOA" constructor so that we can reference the
87 ;;; slot names in init forms.
88 (def!macro def-alien-type-class ((name &key include include-args) &rest slots)
89   (let ((defstruct-name (symbolicate "ALIEN-" name "-TYPE")))
90     (multiple-value-bind (include include-defstruct overrides)
91         (etypecase include
92           (null
93            (values nil 'alien-type nil))
94           (symbol
95            (values
96             include
97             (symbolicate "ALIEN-" include "-TYPE")
98             nil))
99           (list
100            (values
101             (car include)
102             (symbolicate "ALIEN-" (car include) "-TYPE")
103             (cdr include))))
104       `(progn
105          (eval-when (:compile-toplevel :load-toplevel :execute)
106            (create-alien-type-class-if-necessary ',name ',(or include 'root)))
107          (def!struct (,defstruct-name
108                         (:include ,include-defstruct
109                                   (:class ',name)
110                                   ,@overrides)
111                         (:constructor
112                          ,(symbolicate "MAKE-" defstruct-name)
113                          (&key class bits alignment
114                                ,@(mapcar (lambda (x)
115                                            (if (atom x) x (car x)))
116                                          slots)
117                                ,@include-args)))
118            ,@slots)))))
119
120 (def!macro def-alien-type-method ((class method) lambda-list &rest body)
121   (let ((defun-name (symbolicate class "-" method "-METHOD")))
122     `(progn
123        (defun ,defun-name ,lambda-list
124          ,@body)
125        (setf (,(method-slot method) (alien-type-class-or-lose ',class))
126              #',defun-name))))
127
128 (def!macro invoke-alien-type-method (method type &rest args)
129   (let ((slot (method-slot method)))
130     (once-only ((type type))
131       `(funcall (do ((class (alien-type-class-or-lose (alien-type-class ,type))
132                             (alien-type-class-include class)))
133                     ((null class)
134                      (error "method ~S not defined for ~S"
135                             ',method (alien-type-class ,type)))
136                   (let ((fn (,slot class)))
137                     (when fn
138                       (return fn))))
139                 ,type ,@args))))
140 \f
141 ;;;; type parsing and unparsing
142
143 ;;; CMU CL used COMPILER-LET to bind *AUXILIARY-TYPE-DEFINITIONS*, and
144 ;;; COMPILER-LET is no longer supported by ANSI or SBCL. Instead, we
145 ;;; follow the suggestion in CLTL2 of using SYMBOL-MACROLET to achieve
146 ;;; a similar effect.
147 (eval-when (:compile-toplevel :load-toplevel :execute)
148   (defun auxiliary-type-definitions (env)
149     (multiple-value-bind (result expanded-p)
150         (sb!xc:macroexpand '&auxiliary-type-definitions& env)
151       (if expanded-p
152           result
153           ;; This is like having the global symbol-macro definition be
154           ;; NIL, but global symbol-macros make me vaguely queasy, so
155           ;; I do it this way instead.
156           nil))))
157
158 ;;; Process stuff in a new scope.
159 (def!macro with-auxiliary-alien-types (env &body body)
160   ``(symbol-macrolet ((&auxiliary-type-definitions&
161                        ,(append *new-auxiliary-types*
162                                 (auxiliary-type-definitions ,env))))
163       ,(let ((*new-auxiliary-types* nil))
164          ,@body)))
165
166 ;;; FIXME: Now that *NEW-AUXILIARY-TYPES* is born initialized to NIL,
167 ;;; we no longer need to make a distinction between this and
168 ;;; %PARSE-ALIEN-TYPE.
169 (defun parse-alien-type (type env)
170   (declare (type (or sb!kernel:lexenv null) env))
171   #!+sb-doc
172   "Parse the list structure TYPE as an alien type specifier and return
173    the resultant ALIEN-TYPE structure."
174   (%parse-alien-type type env))
175
176 (defun %parse-alien-type (type env)
177   (declare (type (or sb!kernel:lexenv null) env))
178   (if (consp type)
179       (let ((translator (info :alien-type :translator (car type))))
180         (unless translator
181           (error "unknown alien type: ~S" type))
182         (funcall translator type env))
183       (case (info :alien-type :kind type)
184         (:primitive
185          (let ((translator (info :alien-type :translator type)))
186            (unless translator
187              (error "no translator for primitive alien type ~S" type))
188            (funcall translator (list type) env)))
189         (:defined
190          (or (info :alien-type :definition type)
191              (error "no definition for alien type ~S" type)))
192         (:unknown
193          (error "unknown alien type: ~S" type)))))
194
195 (defun auxiliary-alien-type (kind name env)
196   (declare (type (or sb!kernel:lexenv null) env))
197   (flet ((aux-defn-matches (x)
198            (and (eq (first x) kind) (eq (second x) name))))
199     (let ((in-auxiliaries
200            (or (find-if #'aux-defn-matches *new-auxiliary-types*)
201                (find-if #'aux-defn-matches (auxiliary-type-definitions env)))))
202       (if in-auxiliaries
203           (values (third in-auxiliaries) t)
204           (ecase kind
205             (:struct
206              (info :alien-type :struct name))
207             (:union
208              (info :alien-type :union name))
209             (:enum
210              (info :alien-type :enum name)))))))
211
212 (defun (setf auxiliary-alien-type) (new-value kind name env)
213   (declare (type (or sb!kernel:lexenv null) env))
214   (flet ((aux-defn-matches (x)
215            (and (eq (first x) kind) (eq (second x) name))))
216     (when (find-if #'aux-defn-matches *new-auxiliary-types*)
217       (error "attempt to multiply define ~A ~S" kind name))
218     (when (find-if #'aux-defn-matches (auxiliary-type-definitions env))
219       (error "attempt to shadow definition of ~A ~S" kind name)))
220   (push (list kind name new-value) *new-auxiliary-types*)
221   new-value)
222
223 (defun verify-local-auxiliaries-okay ()
224   (dolist (info *new-auxiliary-types*)
225     (destructuring-bind (kind name defn) info
226       (declare (ignore defn))
227       (when (ecase kind
228               (:struct
229                (info :alien-type :struct name))
230               (:union
231                (info :alien-type :union name))
232               (:enum
233                (info :alien-type :enum name)))
234         (error "attempt to shadow definition of ~A ~S" kind name)))))
235
236 (defun unparse-alien-type (type)
237   #!+sb-doc
238   "Convert the alien-type structure TYPE back into a list specification of
239    the type."
240   (declare (type alien-type type))
241   (let ((*record-types-already-unparsed* nil))
242     (%unparse-alien-type type)))
243
244 ;;; Does all the work of UNPARSE-ALIEN-TYPE. It's separate because we
245 ;;; need to recurse inside the binding of
246 ;;; *RECORD-TYPES-ALREADY-UNPARSED*.
247 (defun %unparse-alien-type (type)
248   (invoke-alien-type-method :unparse type))
249 \f
250 ;;;; alien type defining stuff
251
252 (def!macro def-alien-type-translator (name lambda-list &body body)
253   (let ((whole (gensym "WHOLE"))
254         (env (gensym "ENV"))
255         (defun-name (symbolicate "ALIEN-" name "-TYPE-TRANSLATOR")))
256     (multiple-value-bind (body decls docs)
257         (sb!kernel:parse-defmacro lambda-list whole body name
258                                   'def-alien-type-translator
259                                   :environment env)
260       `(eval-when (:compile-toplevel :load-toplevel :execute)
261          (defun ,defun-name (,whole ,env)
262            (declare (ignorable ,env))
263            ,@decls
264            (block ,name
265              ,body))
266          (%def-alien-type-translator ',name #',defun-name ,docs)))))
267
268 (eval-when (:compile-toplevel :load-toplevel :execute)
269   (defun %def-alien-type-translator (name translator docs)
270     (declare (ignore docs))
271     (setf (info :alien-type :kind name) :primitive)
272     (setf (info :alien-type :translator name) translator)
273     (clear-info :alien-type :definition name)
274     #+nil
275     (setf (fdocumentation name 'alien-type) docs)
276     name))
277
278 (def!macro def-alien-type (name type &environment env)
279   #!+sb-doc
280   "Define the alien type NAME to be equivalent to TYPE. Name may be NIL for
281    STRUCT and UNION types, in which case the name is taken from the type
282    specifier."
283   (with-auxiliary-alien-types env
284     (let ((alien-type (parse-alien-type type env)))
285       `(eval-when (:compile-toplevel :load-toplevel :execute)
286          ,@(when *new-auxiliary-types*
287              `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
288          ,@(when name
289              `((%def-alien-type ',name ',alien-type)))))))
290
291 (eval-when (:compile-toplevel :load-toplevel :execute)
292   (defun %def-auxiliary-alien-types (types)
293     (dolist (info types)
294       (destructuring-bind (kind name defn) info
295         (macrolet ((frob (kind)
296                          `(let ((old (info :alien-type ,kind name)))
297                             (unless (or (null old) (alien-type-= old defn))
298                               (warn
299                                "redefining ~A ~S to be:~%  ~S,~%was:~%  ~S"
300                                kind name defn old))
301                             (setf (info :alien-type ,kind name) defn))))
302           (ecase kind
303             (:struct (frob :struct))
304             (:union (frob :union))
305             (:enum (frob :enum)))))))
306   (defun %def-alien-type (name new)
307     (ecase (info :alien-type :kind name)
308       (:primitive
309        (error "~S is a built-in alien type." name))
310       (:defined
311        (let ((old (info :alien-type :definition name)))
312          (unless (or (null old) (alien-type-= new old))
313            (warn "redefining ~S to be:~%  ~S,~%was~%  ~S"
314                  name
315                  (unparse-alien-type new)
316                  (unparse-alien-type old)))))
317       (:unknown))
318     (setf (info :alien-type :definition name) new)
319     (setf (info :alien-type :kind name) :defined)
320     name))
321 \f
322 ;;;; the root alien type
323
324 (eval-when (:compile-toplevel :load-toplevel :execute)
325   (create-alien-type-class-if-necessary 'root nil))
326
327 (def!struct (alien-type
328              (:make-load-form-fun sb!kernel:just-dump-it-normally)
329              (:constructor make-alien-type (&key class bits alignment)))
330   (class 'root :type symbol)
331   (bits nil :type (or null unsigned-byte))
332   (alignment (guess-alignment bits) :type (or null unsigned-byte)))
333 (def!method print-object ((type alien-type) stream)
334   (print-unreadable-object (type stream :type t)
335     (prin1 (unparse-alien-type type) stream)))
336 \f
337 ;;;; the SAP type
338
339 (def-alien-type-class (system-area-pointer))
340
341 (def-alien-type-translator system-area-pointer ()
342   (make-alien-system-area-pointer-type
343    :bits #!-alpha sb!vm:word-bits #!+alpha 64))
344
345 (def-alien-type-method (system-area-pointer :unparse) (type)
346   (declare (ignore type))
347   'system-area-pointer)
348
349 (def-alien-type-method (system-area-pointer :lisp-rep) (type)
350   (declare (ignore type))
351   'system-area-pointer)
352
353 (def-alien-type-method (system-area-pointer :alien-rep) (type)
354   (declare (ignore type))
355   'system-area-pointer)
356
357 (def-alien-type-method (system-area-pointer :naturalize-gen) (type alien)
358   (declare (ignore type))
359   alien)
360
361 (def-alien-type-method (system-area-pointer :deport-gen) (type object)
362   (declare (ignore type))
363   (/noshow "doing alien type method SYSTEM-AREA-POINTER :DEPORT-GEN" object)
364   object)
365
366 (def-alien-type-method (system-area-pointer :extract-gen) (type sap offset)
367   (declare (ignore type))
368   `(sap-ref-sap ,sap (/ ,offset sb!vm:byte-bits)))
369 \f
370 ;;;; the ALIEN-VALUE type
371
372 (def-alien-type-class (alien-value :include system-area-pointer))
373
374 (def-alien-type-method (alien-value :lisp-rep) (type)
375   (declare (ignore type))
376   nil)
377
378 (def-alien-type-method (alien-value :naturalize-gen) (type alien)
379   `(%sap-alien ,alien ',type))
380
381 (def-alien-type-method (alien-value :deport-gen) (type value)
382   (declare (ignore type))
383   (/noshow "doing alien type method ALIEN-VALUE :DEPORT-GEN" value)
384   `(alien-sap ,value))
385 \f
386 ;;; HEAP-ALIEN-INFO -- defstruct.
387 ;;;
388 ;;; Information describing a heap-allocated alien.
389 (def!struct (heap-alien-info
390              (:make-load-form-fun sb!kernel:just-dump-it-normally))
391   ;; The type of this alien.
392   (type (required-argument) :type alien-type)
393   ;; The form to evaluate to produce the SAP pointing to where in the heap
394   ;; it is.
395   (sap-form (required-argument)))
396 (def!method print-object ((info heap-alien-info) stream)
397   (print-unreadable-object (info stream :type t)
398     (funcall (formatter "~S ~S")
399              stream
400              (heap-alien-info-sap-form info)
401              (unparse-alien-type (heap-alien-info-type info)))))
402 \f
403 ;;;; Interfaces to the different methods
404
405 (defun alien-type-= (type1 type2)
406   #!+sb-doc
407   "Return T iff TYPE1 and TYPE2 describe equivalent alien types."
408   (or (eq type1 type2)
409       (and (eq (alien-type-class type1)
410                (alien-type-class type2))
411            (invoke-alien-type-method :type= type1 type2))))
412
413 (defun alien-subtype-p (type1 type2)
414   #!+sb-doc
415   "Return T iff the alien type TYPE1 is a subtype of TYPE2. Currently, the
416    only supported subtype relationships are is that any pointer type is a
417    subtype of (* t), and any array type first dimension will match
418    (array <eltype> nil ...). Otherwise, the two types have to be
419    ALIEN-TYPE-=."
420   (or (eq type1 type2)
421       (invoke-alien-type-method :subtypep type1 type2)))
422
423 (defun compute-naturalize-lambda (type)
424   `(lambda (alien ignore)
425      (declare (ignore ignore))
426      ,(invoke-alien-type-method :naturalize-gen type 'alien)))
427
428 (defun compute-deport-lambda (type)
429   (declare (type alien-type type))
430   (/noshow "entering COMPUTE-DEPORT-LAMBDA" type)
431   (multiple-value-bind (form value-type)
432       (invoke-alien-type-method :deport-gen type 'value)
433     `(lambda (value ignore)
434        (declare (type ,(or value-type
435                            (compute-lisp-rep-type type)
436                            `(alien ,type))
437                       value)
438                 (ignore ignore))
439        ,form)))
440
441 (defun compute-extract-lambda (type)
442   `(lambda (sap offset ignore)
443      (declare (type system-area-pointer sap)
444               (type unsigned-byte offset)
445               (ignore ignore))
446      (naturalize ,(invoke-alien-type-method :extract-gen type 'sap 'offset)
447                  ',type)))
448
449 (defun compute-deposit-lambda (type)
450   (declare (type alien-type type))
451   `(lambda (sap offset ignore value)
452      (declare (type system-area-pointer sap)
453               (type unsigned-byte offset)
454               (ignore ignore))
455      (let ((value (deport value ',type)))
456        ,(invoke-alien-type-method :deposit-gen type 'sap 'offset 'value)
457        ;; Note: the reason we don't just return the pre-deported value
458        ;; is because that would inhibit any (deport (naturalize ...))
459        ;; optimizations that might have otherwise happen. Re-naturalizing
460        ;; the value might cause extra consing, but is flushable, so probably
461        ;; results in better code.
462        (naturalize value ',type))))
463
464 (defun compute-lisp-rep-type (type)
465   (invoke-alien-type-method :lisp-rep type))
466
467 (defun compute-alien-rep-type (type)
468   (invoke-alien-type-method :alien-rep type))
469 \f
470 ;;;; default methods
471
472 (def-alien-type-method (root :unparse) (type)
473   `(<unknown-alien-type> ,(type-of type)))
474
475 (def-alien-type-method (root :type=) (type1 type2)
476   (declare (ignore type1 type2))
477   t)
478
479 (def-alien-type-method (root :subtypep) (type1 type2)
480   (alien-type-= type1 type2))
481
482 (def-alien-type-method (root :lisp-rep) (type)
483   (declare (ignore type))
484   nil)
485
486 (def-alien-type-method (root :alien-rep) (type)
487   (declare (ignore type))
488   '*)
489
490 (def-alien-type-method (root :naturalize-gen) (type alien)
491   (declare (ignore alien))
492   (error "cannot represent ~S typed aliens" type))
493
494 (def-alien-type-method (root :deport-gen) (type object)
495   (declare (ignore object))
496   (error "cannot represent ~S typed aliens" type))
497
498 (def-alien-type-method (root :extract-gen) (type sap offset)
499   (declare (ignore sap offset))
500   (error "cannot represent ~S typed aliens" type))
501
502 (def-alien-type-method (root :deposit-gen) (type sap offset value)
503   `(setf ,(invoke-alien-type-method :extract-gen type sap offset) ,value))
504
505 (def-alien-type-method (root :arg-tn) (type state)
506   (declare (ignore state))
507   (error "Aliens of type ~S cannot be passed as arguments to CALL-OUT."
508          (unparse-alien-type type)))
509
510 (def-alien-type-method (root :result-tn) (type state)
511   (declare (ignore state))
512   (error "Aliens of type ~S cannot be returned from CALL-OUT."
513          (unparse-alien-type type)))
514 \f
515 ;;;; the INTEGER type
516
517 (def-alien-type-class (integer)
518   (signed t :type (member t nil)))
519
520 (def-alien-type-translator signed (&optional (bits sb!vm:word-bits))
521   (make-alien-integer-type :bits bits))
522
523 (def-alien-type-translator integer (&optional (bits sb!vm:word-bits))
524   (make-alien-integer-type :bits bits))
525
526 (def-alien-type-translator unsigned (&optional (bits sb!vm:word-bits))
527   (make-alien-integer-type :bits bits :signed nil))
528
529 (def-alien-type-method (integer :unparse) (type)
530   (list (if (alien-integer-type-signed type) 'signed 'unsigned)
531         (alien-integer-type-bits type)))
532
533 (def-alien-type-method (integer :type=) (type1 type2)
534   (and (eq (alien-integer-type-signed type1)
535            (alien-integer-type-signed type2))
536        (= (alien-integer-type-bits type1)
537           (alien-integer-type-bits type2))))
538
539 (def-alien-type-method (integer :lisp-rep) (type)
540   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
541         (alien-integer-type-bits type)))
542
543 (def-alien-type-method (integer :alien-rep) (type)
544   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
545         (alien-integer-type-bits type)))
546
547 (def-alien-type-method (integer :naturalize-gen) (type alien)
548   (declare (ignore type))
549   alien)
550
551 (def-alien-type-method (integer :deport-gen) (type value)
552   (declare (ignore type))
553   value)
554
555 (def-alien-type-method (integer :extract-gen) (type sap offset)
556   (declare (type alien-integer-type type))
557   (let ((ref-fun
558          (if (alien-integer-type-signed type)
559           (case (alien-integer-type-bits type)
560             (8 'signed-sap-ref-8)
561             (16 'signed-sap-ref-16)
562             (32 'signed-sap-ref-32)
563             #!+alpha (64 'signed-sap-ref-64))
564           (case (alien-integer-type-bits type)
565             (8 'sap-ref-8)
566             (16 'sap-ref-16)
567             (32 'sap-ref-32)
568             #!+alpha (64 'sap-ref-64)))))
569     (if ref-fun
570         `(,ref-fun ,sap (/ ,offset sb!vm:byte-bits))
571         (error "cannot extract ~D bit integers"
572                (alien-integer-type-bits type)))))
573 \f
574 ;;;; the BOOLEAN type
575
576 (def-alien-type-class (boolean :include integer :include-args (signed)))
577
578 ;;; FIXME: Check to make sure that we aren't attaching user-readable
579 ;;; stuff to CL:BOOLEAN in any way which impairs ANSI compliance.
580 (def-alien-type-translator boolean (&optional (bits sb!vm:word-bits))
581   (make-alien-boolean-type :bits bits :signed nil))
582
583 (def-alien-type-method (boolean :unparse) (type)
584   `(boolean ,(alien-boolean-type-bits type)))
585
586 (def-alien-type-method (boolean :lisp-rep) (type)
587   (declare (ignore type))
588   `(member t nil))
589
590 (def-alien-type-method (boolean :naturalize-gen) (type alien)
591   (declare (ignore type))
592   `(not (zerop ,alien)))
593
594 (def-alien-type-method (boolean :deport-gen) (type value)
595   (declare (ignore type))
596   `(if ,value 1 0))
597 \f
598 ;;;; the ENUM type
599
600 (def-alien-type-class (enum :include (integer (:bits 32))
601                             :include-args (signed))
602   name          ; name of this enum (if any)
603   from          ; alist from keywords to integers.
604   to            ; alist or vector from integers to keywords.
605   kind          ; Kind of from mapping, :vector or :alist.
606   offset)       ; Offset to add to value for :vector from mapping.
607
608 (def-alien-type-translator enum (&whole
609                                  type name
610                                  &rest mappings
611                                  &environment env)
612   (cond (mappings
613          (let ((result (parse-enum name mappings)))
614            (when name
615              (multiple-value-bind (old old-p)
616                  (auxiliary-alien-type :enum name env)
617                (when old-p
618                  (unless (alien-type-= result old)
619                    (warn "redefining alien enum ~S" name))))
620              (setf (auxiliary-alien-type :enum name env) result))
621            result))
622         (name
623          (multiple-value-bind (result found)
624              (auxiliary-alien-type :enum name env)
625            (unless found
626              (error "unknown enum type: ~S" name))
627            result))
628         (t
629          (error "empty enum type: ~S" type))))
630
631 (defun parse-enum (name elements)
632   (when (null elements)
633     (error "An enumeration must contain at least one element."))
634   (let ((min nil)
635         (max nil)
636         (from-alist ())
637         (prev -1))
638     (declare (list from-alist))
639     (dolist (el elements)
640       (multiple-value-bind (sym val)
641           (if (listp el)
642               (values (first el) (second el))
643               (values el (1+ prev)))
644         (setf prev val)
645         (unless (keywordp sym)
646           (error "The enumeration element ~S is not a keyword." sym))
647         (unless (integerp val)
648           (error "The element value ~S is not an integer." val))
649         (unless (and max (> max val)) (setq max val))
650         (unless (and min (< min val)) (setq min val))
651         (when (rassoc val from-alist)
652           (error "The element value ~S is used more than once." val))
653         (when (assoc sym from-alist :test #'eq)
654           (error "The enumeration element ~S is used more than once." sym))
655         (push (cons sym val) from-alist)))
656     (let* ((signed (minusp min))
657            (min-bits (if signed
658                          (1+ (max (integer-length min)
659                                   (integer-length max)))
660                          (integer-length max))))
661       (when (> min-bits 32)
662         (error "can't represent enums needing more than 32 bits"))
663       (setf from-alist (sort from-alist #'< :key #'cdr))
664       (cond
665        ;; If range is at least 20% dense, use vector mapping. Crossover
666        ;; point solely on basis of space would be 25%. Vector mapping
667        ;; is always faster, so give the benefit of the doubt.
668        ((< 0.2 (/ (float (length from-alist)) (float (- max min))))
669         ;; If offset is small and ignorable, ignore it to save time.
670         (when (< 0 min 10) (setq min 0))
671         (let ((to (make-array (1+ (- max min)))))
672           (dolist (el from-alist)
673             (setf (svref to (- (cdr el) min)) (car el)))
674           (make-alien-enum-type :name name :signed signed
675                                 :from from-alist :to to :kind
676                                 :vector :offset (- min))))
677        (t
678         (make-alien-enum-type :name name :signed signed
679                               :from from-alist
680                               :to (mapcar #'(lambda (x) (cons (cdr x) (car x)))
681                                           from-alist)
682                               :kind :alist))))))
683
684 (def-alien-type-method (enum :unparse) (type)
685   `(enum ,(alien-enum-type-name type)
686          ,@(let ((prev -1))
687              (mapcar #'(lambda (mapping)
688                          (let ((sym (car mapping))
689                                (value (cdr mapping)))
690                            (prog1
691                                (if (= (1+ prev) value)
692                                    sym
693                                    `(,sym ,value))
694                              (setf prev value))))
695                      (alien-enum-type-from type)))))
696
697 (def-alien-type-method (enum :type=) (type1 type2)
698   (and (eq (alien-enum-type-name type1)
699            (alien-enum-type-name type2))
700        (equal (alien-enum-type-from type1)
701               (alien-enum-type-from type2))))
702
703 (def-alien-type-method (enum :lisp-rep) (type)
704   `(member ,@(mapcar #'car (alien-enum-type-from type))))
705
706 (def-alien-type-method (enum :naturalize-gen) (type alien)
707   (ecase (alien-enum-type-kind type)
708     (:vector
709      `(svref ',(alien-enum-type-to type)
710              (+ ,alien ,(alien-enum-type-offset type))))
711     (:alist
712      `(ecase ,alien
713         ,@(mapcar #'(lambda (mapping)
714                       `(,(car mapping) ,(cdr mapping)))
715                   (alien-enum-type-to type))))))
716
717 (def-alien-type-method (enum :deport-gen) (type value)
718   `(ecase ,value
719      ,@(mapcar #'(lambda (mapping)
720                    `(,(car mapping) ,(cdr mapping)))
721                (alien-enum-type-from type))))
722 \f
723 ;;;; the FLOAT types
724
725 (def-alien-type-class (float)
726   (type (required-argument) :type symbol))
727
728 (def-alien-type-method (float :unparse) (type)
729   (alien-float-type-type type))
730
731 (def-alien-type-method (float :lisp-rep) (type)
732   (alien-float-type-type type))
733
734 (def-alien-type-method (float :alien-rep) (type)
735   (alien-float-type-type type))
736
737 (def-alien-type-method (float :naturalize-gen) (type alien)
738   (declare (ignore type))
739   alien)
740
741 (def-alien-type-method (float :deport-gen) (type value)
742   (declare (ignore type))
743   value)
744
745 (def-alien-type-class (single-float :include (float (:bits 32))
746                                     :include-args (type)))
747
748 (def-alien-type-translator single-float ()
749   (make-alien-single-float-type :type 'single-float))
750
751 (def-alien-type-method (single-float :extract-gen) (type sap offset)
752   (declare (ignore type))
753   `(sap-ref-single ,sap (/ ,offset sb!vm:byte-bits)))
754
755 (def-alien-type-class (double-float :include (float (:bits 64))
756                                     :include-args (type)))
757
758 (def-alien-type-translator double-float ()
759   (make-alien-double-float-type :type 'double-float))
760
761 (def-alien-type-method (double-float :extract-gen) (type sap offset)
762   (declare (ignore type))
763   `(sap-ref-double ,sap (/ ,offset sb!vm:byte-bits)))
764
765 #!+long-float
766 (def-alien-type-class (long-float :include (float (:bits #!+x86 96
767                                                           #!+sparc 128))
768                                   :include-args (type)))
769
770 #!+long-float
771 (def-alien-type-translator long-float ()
772   (make-alien-long-float-type :type 'long-float))
773
774 #!+long-float
775 (def-alien-type-method (long-float :extract-gen) (type sap offset)
776   (declare (ignore type))
777   `(sap-ref-long ,sap (/ ,offset sb!vm:byte-bits)))
778 \f
779 ;;;; the POINTER type
780
781 (def-alien-type-class (pointer :include (alien-value (:bits
782                                                       #!-alpha sb!vm:word-bits
783                                                       #!+alpha 64)))
784   (to nil :type (or alien-type null)))
785
786 (def-alien-type-translator * (to &environment env)
787   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
788
789 (def-alien-type-method (pointer :unparse) (type)
790   (let ((to (alien-pointer-type-to type)))
791     `(* ,(if to
792              (%unparse-alien-type to)
793              t))))
794
795 (def-alien-type-method (pointer :type=) (type1 type2)
796   (let ((to1 (alien-pointer-type-to type1))
797         (to2 (alien-pointer-type-to type2)))
798     (if to1
799         (if to2
800             (alien-type-= to1 to2)
801             nil)
802         (null to2))))
803
804 (def-alien-type-method (pointer :subtypep) (type1 type2)
805   (and (alien-pointer-type-p type2)
806        (let ((to1 (alien-pointer-type-to type1))
807              (to2 (alien-pointer-type-to type2)))
808          (if to1
809              (if to2
810                  (alien-subtype-p to1 to2)
811                  t)
812              (null to2)))))
813
814 (def-alien-type-method (pointer :deport-gen) (type value)
815   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
816   (values
817    ;; FIXME: old version, highlighted a bug in xc optimization
818    `(etypecase ,value
819       (null
820        (int-sap 0))
821       (system-area-pointer
822        ,value)
823       ((alien ,type)
824        (alien-sap ,value)))
825    ;; new version, works around bug in xc optimization
826    #+nil
827    `(etypecase ,value
828       (system-area-pointer
829        ,value)
830       ((alien ,type)
831        (alien-sap ,value))
832       (null
833        (int-sap 0)))
834    `(or null system-area-pointer (alien ,type))))
835 \f
836 ;;;; the MEM-BLOCK type
837
838 (def-alien-type-class (mem-block :include alien-value))
839
840 (def-alien-type-method (mem-block :extract-gen) (type sap offset)
841   (declare (ignore type))
842   `(sap+ ,sap (/ ,offset sb!vm:byte-bits)))
843
844 (def-alien-type-method (mem-block :deposit-gen) (type sap offset value)
845   (let ((bits (alien-mem-block-type-bits type)))
846     (unless bits
847       (error "can't deposit aliens of type ~S (unknown size)" type))
848     `(sb!kernel:system-area-copy ,value 0 ,sap ,offset ',bits)))
849 \f
850 ;;;; the ARRAY type
851
852 (def-alien-type-class (array :include mem-block)
853   (element-type (required-argument) :type alien-type)
854   (dimensions (required-argument) :type list))
855
856 (def-alien-type-translator array (ele-type &rest dims &environment env)
857   (when dims
858     (unless (typep (first dims) '(or index null))
859       (error "The first dimension is not a non-negative fixnum or NIL: ~S"
860              (first dims)))
861     (let ((loser (find-if-not #'(lambda (x) (typep x 'index))
862                               (rest dims))))
863       (when loser
864         (error "A dimension is not a non-negative fixnum: ~S" loser))))
865         
866   (let ((type (parse-alien-type ele-type env)))
867     (make-alien-array-type
868      :element-type type
869      :dimensions dims
870      :alignment (alien-type-alignment type)
871      :bits (if (and (alien-type-bits type)
872                     (every #'integerp dims))
873                (* (align-offset (alien-type-bits type)
874                                 (alien-type-alignment type))
875                   (reduce #'* dims))))))
876
877 (def-alien-type-method (array :unparse) (type)
878   `(array ,(%unparse-alien-type (alien-array-type-element-type type))
879           ,@(alien-array-type-dimensions type)))
880
881 (def-alien-type-method (array :type=) (type1 type2)
882   (and (equal (alien-array-type-dimensions type1)
883               (alien-array-type-dimensions type2))
884        (alien-type-= (alien-array-type-element-type type1)
885                      (alien-array-type-element-type type2))))
886
887 (def-alien-type-method (array :subtypep) (type1 type2)
888   (and (alien-array-type-p type2)
889        (let ((dim1 (alien-array-type-dimensions type1))
890              (dim2 (alien-array-type-dimensions type2)))
891          (and (= (length dim1) (length dim2))
892               (or (and dim2
893                        (null (car dim2))
894                        (equal (cdr dim1) (cdr dim2)))
895                   (equal dim1 dim2))
896               (alien-subtype-p (alien-array-type-element-type type1)
897                                (alien-array-type-element-type type2))))))
898 \f
899 ;;;; the RECORD type
900
901 (def!struct (alien-record-field
902              (:make-load-form-fun sb!kernel:just-dump-it-normally))
903   (name (required-argument) :type symbol)
904   (type (required-argument) :type alien-type)
905   (bits nil :type (or unsigned-byte null))
906   (offset 0 :type unsigned-byte))
907 (def!method print-object ((field alien-record-field) stream)
908   (print-unreadable-object (field stream :type t)
909     (format stream
910             "~S ~S~@[:~D~]"
911             (alien-record-field-type field)
912             (alien-record-field-name field)
913             (alien-record-field-bits field))))
914
915 (def-alien-type-class (record :include mem-block)
916   (kind :struct :type (member :struct :union))
917   (name nil :type (or symbol null))
918   (fields nil :type list))
919
920 (def-alien-type-translator struct (name &rest fields &environment env)
921   (parse-alien-record-type :struct name fields env))
922
923 (def-alien-type-translator union (name &rest fields &environment env)
924   (parse-alien-record-type :union name fields env))
925
926 (defun parse-alien-record-type (kind name fields env)
927   (declare (type (or sb!kernel:lexenv null) env))
928   (cond (fields
929          (let* ((old (and name (auxiliary-alien-type kind name env)))
930                 (old-fields (and old (alien-record-type-fields old))))
931            (cond (old-fields
932                   ;; KLUDGE: We can't easily compare the new fields
933                   ;; against the old fields, since the old fields have
934                   ;; already been parsed into an internal
935                   ;; representation, so we just punt, assuming that
936                   ;; they're consistent. -- WHN 200000505
937                   #|
938                   (unless (equal fields old-fields)
939                     ;; FIXME: Perhaps this should be a warning, and we
940                     ;; should overwrite the old definition and proceed?
941                     (error "mismatch in fields for ~S~%  old ~S~%  new ~S"
942                            name old-fields fields))
943                   |#
944                   old)
945                  (t
946                   (let ((new (make-alien-record-type :name name
947                                                      :kind kind)))
948                     (when name
949                       (setf (auxiliary-alien-type kind name env) new))
950                     (parse-alien-record-fields new fields env)
951                     new)))))
952         (name
953          (or (auxiliary-alien-type kind name env)
954              (setf (auxiliary-alien-type kind name env)
955                    (make-alien-record-type :name name :kind kind))))
956         (t
957          (make-alien-record-type :kind kind))))
958
959 ;;; This is used by PARSE-ALIEN-TYPE to parse the fields of struct and
960 ;;; union types. RESULT holds the record type we are paring the fields
961 ;;; of, and FIELDS is the list of field specifications.
962 (defun parse-alien-record-fields (result fields env)
963   (declare (type alien-record-type result)
964            (type list fields))
965   (let ((total-bits 0)
966         (overall-alignment 1)
967         (parsed-fields nil))
968     (dolist (field fields)
969       (destructuring-bind (var type &optional bits) field
970         (declare (ignore bits))
971         (let* ((field-type (parse-alien-type type env))
972                (bits (alien-type-bits field-type))
973                (alignment (alien-type-alignment field-type))
974                (parsed-field
975                 (make-alien-record-field :type field-type
976                                          :name var)))
977           (push parsed-field parsed-fields)
978           (when (null bits)
979             (error "unknown size: ~S" (unparse-alien-type field-type)))
980           (when (null alignment)
981             (error "unknown alignment: ~S" (unparse-alien-type field-type)))
982           (setf overall-alignment (max overall-alignment alignment))
983           (ecase (alien-record-type-kind result)
984             (:struct
985              (let ((offset (align-offset total-bits alignment)))
986                (setf (alien-record-field-offset parsed-field) offset)
987                (setf total-bits (+ offset bits))))
988             (:union
989              (setf total-bits (max total-bits bits)))))))
990     (let ((new (nreverse parsed-fields)))
991       (setf (alien-record-type-fields result) new))
992     (setf (alien-record-type-alignment result) overall-alignment)
993     (setf (alien-record-type-bits result)
994           (align-offset total-bits overall-alignment))))
995
996 (def-alien-type-method (record :unparse) (type)
997   `(,(case (alien-record-type-kind type)
998        (:struct 'struct)
999        (:union 'union)
1000        (t '???))
1001     ,(alien-record-type-name type)
1002     ,@(unless (member type *record-types-already-unparsed* :test #'eq)
1003         (push type *record-types-already-unparsed*)
1004         (mapcar #'(lambda (field)
1005                     `(,(alien-record-field-name field)
1006                       ,(%unparse-alien-type (alien-record-field-type field))
1007                       ,@(if (alien-record-field-bits field)
1008                             (list (alien-record-field-bits field)))))
1009                 (alien-record-type-fields type)))))
1010
1011 ;;; Test the record fields. The depth is limiting in case of cyclic
1012 ;;; pointers.
1013 (defun record-fields-match (fields1 fields2 depth)
1014   (declare (type list fields1 fields2)
1015            (type (mod 64) depth))
1016   (labels ((record-type-= (type1 type2 depth)
1017              (and (eq (alien-record-type-name type1)
1018                       (alien-record-type-name type2))
1019                   (eq (alien-record-type-kind type1)
1020                       (alien-record-type-kind type2))
1021                   (= (length (alien-record-type-fields type1))
1022                      (length (alien-record-type-fields type2)))
1023                   (record-fields-match (alien-record-type-fields type1)
1024                                        (alien-record-type-fields type2)
1025                                        (1+ depth))))
1026            (pointer-type-= (type1 type2 depth)
1027              (let ((to1 (alien-pointer-type-to type1))
1028                    (to2 (alien-pointer-type-to type2)))
1029                (if to1
1030                    (if to2
1031                        (type-= to1 to2 (1+ depth))
1032                        nil)
1033                    (null to2))))
1034            (type-= (type1 type2 depth)
1035              (cond ((and (alien-pointer-type-p type1)
1036                          (alien-pointer-type-p type2))
1037                     (or (> depth 10)
1038                         (pointer-type-= type1 type2 depth)))
1039                    ((and (alien-record-type-p type1)
1040                          (alien-record-type-p type2))
1041                     (record-type-= type1 type2 depth))
1042                    (t
1043                     (alien-type-= type1 type2)))))
1044     (do ((fields1-rem fields1 (rest fields1-rem))
1045          (fields2-rem fields2 (rest fields2-rem)))
1046         ((or (eq fields1-rem fields2-rem)
1047              (endp fields1-rem) (endp fields2-rem))
1048          (eq fields1-rem fields2-rem))
1049       (let ((field1 (first fields1-rem))
1050             (field2 (first fields2-rem)))
1051         (declare (type alien-record-field field1 field2))
1052         (unless (and (eq (alien-record-field-name field1)
1053                          (alien-record-field-name field2))
1054                      (eql (alien-record-field-bits field1)
1055                           (alien-record-field-bits field2))
1056                      (eql (alien-record-field-offset field1)
1057                           (alien-record-field-offset field2))
1058                      (let ((field1 (alien-record-field-type field1))
1059                            (field2 (alien-record-field-type field2)))
1060                        (type-= field1 field2 (1+ depth))))
1061           (return nil))))))
1062
1063 (def-alien-type-method (record :type=) (type1 type2)
1064   (and (eq (alien-record-type-name type1)
1065            (alien-record-type-name type2))
1066        (eq (alien-record-type-kind type1)
1067            (alien-record-type-kind type2))
1068        (= (length (alien-record-type-fields type1))
1069           (length (alien-record-type-fields type2)))
1070        (record-fields-match (alien-record-type-fields type1)
1071                             (alien-record-type-fields type2) 0)))
1072 \f
1073 ;;;; the FUNCTION and VALUES types
1074
1075 (defvar *values-type-okay* nil)
1076
1077 (def-alien-type-class (function :include mem-block)
1078   (result-type (required-argument) :type alien-type)
1079   (arg-types (required-argument) :type list)
1080   (stub nil :type (or null function)))
1081
1082 (def-alien-type-translator function (result-type &rest arg-types
1083                                                  &environment env)
1084   (make-alien-function-type
1085    :result-type (let ((*values-type-okay* t))
1086                   (parse-alien-type result-type env))
1087    :arg-types (mapcar (lambda (arg-type) (parse-alien-type arg-type env))
1088                       arg-types)))
1089
1090 (def-alien-type-method (function :unparse) (type)
1091   `(function ,(%unparse-alien-type (alien-function-type-result-type type))
1092              ,@(mapcar #'%unparse-alien-type
1093                        (alien-function-type-arg-types type))))
1094
1095 (def-alien-type-method (function :type=) (type1 type2)
1096   (and (alien-type-= (alien-function-type-result-type type1)
1097                      (alien-function-type-result-type type2))
1098        (= (length (alien-function-type-arg-types type1))
1099           (length (alien-function-type-arg-types type2)))
1100        (every #'alien-type-=
1101               (alien-function-type-arg-types type1)
1102               (alien-function-type-arg-types type2))))
1103
1104 (def-alien-type-class (values)
1105   (values (required-argument) :type list))
1106
1107 (def-alien-type-translator values (&rest values &environment env)
1108   (unless *values-type-okay*
1109     (error "cannot use values types here"))
1110   (let ((*values-type-okay* nil))
1111     (make-alien-values-type
1112      :values (mapcar (lambda (alien-type) (parse-alien-type alien-type env))
1113                      values))))
1114
1115 (def-alien-type-method (values :unparse) (type)
1116   `(values ,@(mapcar #'%unparse-alien-type
1117                      (alien-values-type-values type))))
1118
1119 (def-alien-type-method (values :type=) (type1 type2)
1120   (and (= (length (alien-values-type-values type1))
1121           (length (alien-values-type-values type2)))
1122        (every #'alien-type-=
1123               (alien-values-type-values type1)
1124               (alien-values-type-values type2))))
1125 \f
1126 ;;;; a structure definition needed both in the target and in the
1127 ;;;; cross-compilation host
1128
1129 ;;; information about local aliens. The WITH-ALIEN macro builds one of
1130 ;;; these structures and LOCAL-ALIEN and friends communicate
1131 ;;; information about how that local alien is represented.
1132 (def!struct (local-alien-info
1133              (:make-load-form-fun sb!kernel:just-dump-it-normally)
1134              (:constructor make-local-alien-info
1135                            (&key type force-to-memory-p)))
1136   ;; the type of the local alien
1137   (type (required-argument) :type alien-type)
1138   ;; T if this local alien must be forced into memory. Using the ADDR macro
1139   ;; on a local alien will set this.
1140   (force-to-memory-p (or (alien-array-type-p type) (alien-record-type-p type))
1141                      :type (member t nil)))
1142 (def!method print-object ((info local-alien-info) stream)
1143   (print-unreadable-object (info stream :type t)
1144     (format stream
1145             "~:[~;(forced to stack) ~]~S"
1146             (local-alien-info-force-to-memory-p info)
1147             (unparse-alien-type (local-alien-info-type info)))))
1148 \f
1149 ;;;; the ADDR macro
1150
1151 (sb!kernel:defmacro-mundanely addr (expr &environment env)
1152   #!+sb-doc
1153   "Return an Alien pointer to the data addressed by Expr, which must be a call
1154    to SLOT or DEREF, or a reference to an Alien variable."
1155   (let ((form (sb!xc:macroexpand expr env)))
1156     (or (typecase form
1157           (cons
1158            (case (car form)
1159              (slot
1160               (cons '%slot-addr (cdr form)))
1161              (deref
1162               (cons '%deref-addr (cdr form)))
1163              (%heap-alien
1164               (cons '%heap-alien-addr (cdr form)))
1165              (local-alien
1166               (let ((info (let ((info-arg (second form)))
1167                             (and (consp info-arg)
1168                                  (eq (car info-arg) 'quote)
1169                                  (second info-arg)))))
1170                 (unless (local-alien-info-p info)
1171                   (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
1172                          form))
1173                 (setf (local-alien-info-force-to-memory-p info) t))
1174               (cons '%local-alien-addr (cdr form)))))
1175           (symbol
1176            (let ((kind (info :variable :kind form)))
1177              (when (eq kind :alien)
1178                `(%heap-alien-addr ',(info :variable :alien-info form))))))
1179         (error "~S is not a valid L-value." form))))
1180
1181 (/show0 "host-alieneval.lisp end of file")