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