0.pre7.49:
[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: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: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 (required-argument) :type alien-type)
385   ;; The form to evaluate to produce the SAP pointing to where in the heap
386   ;; it is.
387   (sap-form (required-argument)))
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:word-bits))
513   (make-alien-integer-type :bits bits))
514
515 (def-alien-type-translator integer (&optional (bits sb!vm:word-bits))
516   (make-alien-integer-type :bits bits))
517
518 (def-alien-type-translator unsigned (&optional (bits sb!vm: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: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: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 (required-argument) :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: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: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:byte-bits)))
770 \f
771 ;;;; the POINTER type
772
773 (def-alien-type-class (pointer :include (alien-value (:bits
774                                                       #!-alpha sb!vm:word-bits
775                                                       #!+alpha 64)))
776   (to nil :type (or alien-type null)))
777
778 (def-alien-type-translator * (to &environment env)
779   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
780
781 (def-alien-type-method (pointer :unparse) (type)
782   (let ((to (alien-pointer-type-to type)))
783     `(* ,(if to
784              (%unparse-alien-type to)
785              t))))
786
787 (def-alien-type-method (pointer :type=) (type1 type2)
788   (let ((to1 (alien-pointer-type-to type1))
789         (to2 (alien-pointer-type-to type2)))
790     (if to1
791         (if to2
792             (alien-type-= to1 to2)
793             nil)
794         (null to2))))
795
796 (def-alien-type-method (pointer :subtypep) (type1 type2)
797   (and (alien-pointer-type-p type2)
798        (let ((to1 (alien-pointer-type-to type1))
799              (to2 (alien-pointer-type-to type2)))
800          (if to1
801              (if to2
802                  (alien-subtype-p to1 to2)
803                  t)
804              (null to2)))))
805
806 (def-alien-type-method (pointer :deport-gen) (type value)
807   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
808   (values
809    ;; FIXME: old version, highlighted a bug in xc optimization
810    `(etypecase ,value
811       (null
812        (int-sap 0))
813       (system-area-pointer
814        ,value)
815       ((alien ,type)
816        (alien-sap ,value)))
817    ;; new version, works around bug in xc optimization
818    #+nil
819    `(etypecase ,value
820       (system-area-pointer
821        ,value)
822       ((alien ,type)
823        (alien-sap ,value))
824       (null
825        (int-sap 0)))
826    `(or null system-area-pointer (alien ,type))))
827 \f
828 ;;;; the MEM-BLOCK type
829
830 (def-alien-type-class (mem-block :include alien-value))
831
832 (def-alien-type-method (mem-block :extract-gen) (type sap offset)
833   (declare (ignore type))
834   `(sap+ ,sap (/ ,offset sb!vm:byte-bits)))
835
836 (def-alien-type-method (mem-block :deposit-gen) (type sap offset value)
837   (let ((bits (alien-mem-block-type-bits type)))
838     (unless bits
839       (error "can't deposit aliens of type ~S (unknown size)" type))
840     `(sb!kernel:system-area-copy ,value 0 ,sap ,offset ',bits)))
841 \f
842 ;;;; the ARRAY type
843
844 (def-alien-type-class (array :include mem-block)
845   (element-type (required-argument) :type alien-type)
846   (dimensions (required-argument) :type list))
847
848 (def-alien-type-translator array (ele-type &rest dims &environment env)
849
850   (when dims
851     (unless (typep (first dims) '(or index null))
852       (error "The first dimension is not a non-negative fixnum or NIL: ~S"
853              (first dims)))
854     (let ((loser (find-if-not #'(lambda (x) (typep x 'index))
855                               (rest dims))))
856       (when loser
857         (error "A dimension is not a non-negative fixnum: ~S" loser))))
858         
859   (let ((parsed-ele-type (parse-alien-type ele-type env)))
860     (make-alien-array-type
861      :element-type parsed-ele-type
862      :dimensions dims
863      :alignment (alien-type-alignment parsed-ele-type)
864      :bits (if (and (alien-type-bits parsed-ele-type)
865                     (every #'integerp dims))
866                (* (align-offset (alien-type-bits parsed-ele-type)
867                                 (alien-type-alignment parsed-ele-type))
868                   (reduce #'* dims))))))
869
870 (def-alien-type-method (array :unparse) (type)
871   `(array ,(%unparse-alien-type (alien-array-type-element-type type))
872           ,@(alien-array-type-dimensions type)))
873
874 (def-alien-type-method (array :type=) (type1 type2)
875   (and (equal (alien-array-type-dimensions type1)
876               (alien-array-type-dimensions type2))
877        (alien-type-= (alien-array-type-element-type type1)
878                      (alien-array-type-element-type type2))))
879
880 (def-alien-type-method (array :subtypep) (type1 type2)
881   (and (alien-array-type-p type2)
882        (let ((dim1 (alien-array-type-dimensions type1))
883              (dim2 (alien-array-type-dimensions type2)))
884          (and (= (length dim1) (length dim2))
885               (or (and dim2
886                        (null (car dim2))
887                        (equal (cdr dim1) (cdr dim2)))
888                   (equal dim1 dim2))
889               (alien-subtype-p (alien-array-type-element-type type1)
890                                (alien-array-type-element-type type2))))))
891 \f
892 ;;;; the RECORD type
893
894 (def!struct (alien-record-field
895              (:make-load-form-fun sb!kernel:just-dump-it-normally))
896   (name (required-argument) :type symbol)
897   (type (required-argument) :type alien-type)
898   (bits nil :type (or unsigned-byte null))
899   (offset 0 :type unsigned-byte))
900 (def!method print-object ((field alien-record-field) stream)
901   (print-unreadable-object (field stream :type t)
902     (format stream
903             "~S ~S~@[:~D~]"
904             (alien-record-field-type field)
905             (alien-record-field-name field)
906             (alien-record-field-bits field))))
907
908 (def-alien-type-class (record :include mem-block)
909   (kind :struct :type (member :struct :union))
910   (name nil :type (or symbol null))
911   (fields nil :type list))
912
913 (def-alien-type-translator struct (name &rest fields &environment env)
914   (parse-alien-record-type :struct name fields env))
915
916 (def-alien-type-translator union (name &rest fields &environment env)
917   (parse-alien-record-type :union name fields env))
918
919 (defun parse-alien-record-type (kind name fields env)
920   (declare (type (or sb!kernel:lexenv null) env))
921   (cond (fields
922          (let* ((old (and name (auxiliary-alien-type kind name env)))
923                 (old-fields (and old (alien-record-type-fields old))))
924            (cond (old-fields
925                   ;; KLUDGE: We can't easily compare the new fields
926                   ;; against the old fields, since the old fields have
927                   ;; already been parsed into an internal
928                   ;; representation, so we just punt, assuming that
929                   ;; they're consistent. -- WHN 200000505
930                   #|
931                   (unless (equal fields old-fields)
932                     ;; FIXME: Perhaps this should be a warning, and we
933                     ;; should overwrite the old definition and proceed?
934                     (error "mismatch in fields for ~S~%  old ~S~%  new ~S"
935                            name old-fields fields))
936                   |#
937                   old)
938                  (t
939                   (let ((new (make-alien-record-type :name name
940                                                      :kind kind)))
941                     (when name
942                       (setf (auxiliary-alien-type kind name env) new))
943                     (parse-alien-record-fields new fields env)
944                     new)))))
945         (name
946          (or (auxiliary-alien-type kind name env)
947              (setf (auxiliary-alien-type kind name env)
948                    (make-alien-record-type :name name :kind kind))))
949         (t
950          (make-alien-record-type :kind kind))))
951
952 ;;; This is used by PARSE-ALIEN-TYPE to parse the fields of struct and
953 ;;; union types. RESULT holds the record type we are paring the fields
954 ;;; of, and FIELDS is the list of field specifications.
955 (defun parse-alien-record-fields (result fields env)
956   (declare (type alien-record-type result)
957            (type list fields))
958   (let ((total-bits 0)
959         (overall-alignment 1)
960         (parsed-fields nil))
961     (dolist (field fields)
962       (destructuring-bind (var type &optional bits) field
963         (declare (ignore bits))
964         (let* ((field-type (parse-alien-type type env))
965                (bits (alien-type-bits field-type))
966                (alignment (alien-type-alignment field-type))
967                (parsed-field
968                 (make-alien-record-field :type field-type
969                                          :name var)))
970           (push parsed-field parsed-fields)
971           (when (null bits)
972             (error "unknown size: ~S" (unparse-alien-type field-type)))
973           (when (null alignment)
974             (error "unknown alignment: ~S" (unparse-alien-type field-type)))
975           (setf overall-alignment (max overall-alignment alignment))
976           (ecase (alien-record-type-kind result)
977             (:struct
978              (let ((offset (align-offset total-bits alignment)))
979                (setf (alien-record-field-offset parsed-field) offset)
980                (setf total-bits (+ offset bits))))
981             (:union
982              (setf total-bits (max total-bits bits)))))))
983     (let ((new (nreverse parsed-fields)))
984       (setf (alien-record-type-fields result) new))
985     (setf (alien-record-type-alignment result) overall-alignment)
986     (setf (alien-record-type-bits result)
987           (align-offset total-bits overall-alignment))))
988
989 (def-alien-type-method (record :unparse) (type)
990   `(,(case (alien-record-type-kind type)
991        (:struct 'struct)
992        (:union 'union)
993        (t '???))
994     ,(alien-record-type-name type)
995     ,@(unless (member type *record-types-already-unparsed* :test #'eq)
996         (push type *record-types-already-unparsed*)
997         (mapcar #'(lambda (field)
998                     `(,(alien-record-field-name field)
999                       ,(%unparse-alien-type (alien-record-field-type field))
1000                       ,@(if (alien-record-field-bits field)
1001                             (list (alien-record-field-bits field)))))
1002                 (alien-record-type-fields type)))))
1003
1004 ;;; Test the record fields. The depth is limiting in case of cyclic
1005 ;;; pointers.
1006 (defun record-fields-match (fields1 fields2 depth)
1007   (declare (type list fields1 fields2)
1008            (type (mod 64) depth))
1009   (labels ((record-type-= (type1 type2 depth)
1010              (and (eq (alien-record-type-name type1)
1011                       (alien-record-type-name type2))
1012                   (eq (alien-record-type-kind type1)
1013                       (alien-record-type-kind type2))
1014                   (= (length (alien-record-type-fields type1))
1015                      (length (alien-record-type-fields type2)))
1016                   (record-fields-match (alien-record-type-fields type1)
1017                                        (alien-record-type-fields type2)
1018                                        (1+ depth))))
1019            (pointer-type-= (type1 type2 depth)
1020              (let ((to1 (alien-pointer-type-to type1))
1021                    (to2 (alien-pointer-type-to type2)))
1022                (if to1
1023                    (if to2
1024                        (type-= to1 to2 (1+ depth))
1025                        nil)
1026                    (null to2))))
1027            (type-= (type1 type2 depth)
1028              (cond ((and (alien-pointer-type-p type1)
1029                          (alien-pointer-type-p type2))
1030                     (or (> depth 10)
1031                         (pointer-type-= type1 type2 depth)))
1032                    ((and (alien-record-type-p type1)
1033                          (alien-record-type-p type2))
1034                     (record-type-= type1 type2 depth))
1035                    (t
1036                     (alien-type-= type1 type2)))))
1037     (do ((fields1-rem fields1 (rest fields1-rem))
1038          (fields2-rem fields2 (rest fields2-rem)))
1039         ((or (eq fields1-rem fields2-rem)
1040              (endp fields1-rem) (endp fields2-rem))
1041          (eq fields1-rem fields2-rem))
1042       (let ((field1 (first fields1-rem))
1043             (field2 (first fields2-rem)))
1044         (declare (type alien-record-field field1 field2))
1045         (unless (and (eq (alien-record-field-name field1)
1046                          (alien-record-field-name field2))
1047                      (eql (alien-record-field-bits field1)
1048                           (alien-record-field-bits field2))
1049                      (eql (alien-record-field-offset field1)
1050                           (alien-record-field-offset field2))
1051                      (let ((field1 (alien-record-field-type field1))
1052                            (field2 (alien-record-field-type field2)))
1053                        (type-= field1 field2 (1+ depth))))
1054           (return nil))))))
1055
1056 (def-alien-type-method (record :type=) (type1 type2)
1057   (and (eq (alien-record-type-name type1)
1058            (alien-record-type-name type2))
1059        (eq (alien-record-type-kind type1)
1060            (alien-record-type-kind type2))
1061        (= (length (alien-record-type-fields type1))
1062           (length (alien-record-type-fields type2)))
1063        (record-fields-match (alien-record-type-fields type1)
1064                             (alien-record-type-fields type2) 0)))
1065 \f
1066 ;;;; the FUNCTION and VALUES types
1067
1068 (defvar *values-type-okay* nil)
1069
1070 (def-alien-type-class (function :include mem-block)
1071   (result-type (required-argument) :type alien-type)
1072   (arg-types (required-argument) :type list)
1073   (stub nil :type (or null function)))
1074
1075 (def-alien-type-translator function (result-type &rest arg-types
1076                                                  &environment env)
1077   (make-alien-function-type
1078    :result-type (let ((*values-type-okay* t))
1079                   (parse-alien-type result-type env))
1080    :arg-types (mapcar (lambda (arg-type) (parse-alien-type arg-type env))
1081                       arg-types)))
1082
1083 (def-alien-type-method (function :unparse) (type)
1084   `(function ,(%unparse-alien-type (alien-function-type-result-type type))
1085              ,@(mapcar #'%unparse-alien-type
1086                        (alien-function-type-arg-types type))))
1087
1088 (def-alien-type-method (function :type=) (type1 type2)
1089   (and (alien-type-= (alien-function-type-result-type type1)
1090                      (alien-function-type-result-type type2))
1091        (= (length (alien-function-type-arg-types type1))
1092           (length (alien-function-type-arg-types type2)))
1093        (every #'alien-type-=
1094               (alien-function-type-arg-types type1)
1095               (alien-function-type-arg-types type2))))
1096
1097 (def-alien-type-class (values)
1098   (values (required-argument) :type list))
1099
1100 (def-alien-type-translator values (&rest values &environment env)
1101   (unless *values-type-okay*
1102     (error "cannot use values types here"))
1103   (let ((*values-type-okay* nil))
1104     (make-alien-values-type
1105      :values (mapcar (lambda (alien-type) (parse-alien-type alien-type env))
1106                      values))))
1107
1108 (def-alien-type-method (values :unparse) (type)
1109   `(values ,@(mapcar #'%unparse-alien-type
1110                      (alien-values-type-values type))))
1111
1112 (def-alien-type-method (values :type=) (type1 type2)
1113   (and (= (length (alien-values-type-values type1))
1114           (length (alien-values-type-values type2)))
1115        (every #'alien-type-=
1116               (alien-values-type-values type1)
1117               (alien-values-type-values type2))))
1118 \f
1119 ;;;; a structure definition needed both in the target and in the
1120 ;;;; cross-compilation host
1121
1122 ;;; information about local aliens. The WITH-ALIEN macro builds one of
1123 ;;; these structures and LOCAL-ALIEN and friends communicate
1124 ;;; information about how that local alien is represented.
1125 (def!struct (local-alien-info
1126              (:make-load-form-fun sb!kernel:just-dump-it-normally)
1127              (:constructor make-local-alien-info
1128                            (&key type force-to-memory-p)))
1129   ;; the type of the local alien
1130   (type (required-argument) :type alien-type)
1131   ;; T if this local alien must be forced into memory. Using the ADDR macro
1132   ;; on a local alien will set this.
1133   (force-to-memory-p (or (alien-array-type-p type) (alien-record-type-p type))
1134                      :type (member t nil)))
1135 (def!method print-object ((info local-alien-info) stream)
1136   (print-unreadable-object (info stream :type t)
1137     (format stream
1138             "~:[~;(forced to stack) ~]~S"
1139             (local-alien-info-force-to-memory-p info)
1140             (unparse-alien-type (local-alien-info-type info)))))
1141 \f
1142 ;;;; the ADDR macro
1143
1144 (defmacro-mundanely addr (expr &environment env)
1145   #!+sb-doc
1146   "Return an Alien pointer to the data addressed by Expr, which must be a call
1147    to SLOT or DEREF, or a reference to an Alien variable."
1148   (let ((form (sb!xc:macroexpand expr env)))
1149     (or (typecase form
1150           (cons
1151            (case (car form)
1152              (slot
1153               (cons '%slot-addr (cdr form)))
1154              (deref
1155               (cons '%deref-addr (cdr form)))
1156              (%heap-alien
1157               (cons '%heap-alien-addr (cdr form)))
1158              (local-alien
1159               (let ((info (let ((info-arg (second form)))
1160                             (and (consp info-arg)
1161                                  (eq (car info-arg) 'quote)
1162                                  (second info-arg)))))
1163                 (unless (local-alien-info-p info)
1164                   (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
1165                          form))
1166                 (setf (local-alien-info-force-to-memory-p info) t))
1167               (cons '%local-alien-addr (cdr form)))))
1168           (symbol
1169            (let ((kind (info :variable :kind form)))
1170              (when (eq kind :alien)
1171                `(%heap-alien-addr ',(info :variable :alien-info form))))))
1172         (error "~S is not a valid L-value." form))))
1173
1174 (/show0 "host-alieneval.lisp end of file")