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