;;;; expr.lisp -- expressions (report, section 6): each read, checked and ;;;; turned into an ITEM (comp.lisp) holding the Lisp form that computes it. ;;;; ;;;; Constants are folded here, as the compiler must evaluate them ;;;; (section 4); everything else becomes Lisp over the run time's memory ;;;; operations (rt.lisp). (in-package :raz) ;;; Values of items. (defun const-item (type val &optional tok) (make-item :mode :const :type type :val val :tok tok)) (defun val-item (type form &optional tok) (make-item :mode :val :type type :form form :tok tok)) (defun const-p (item) (eq (item-mode item) :const)) (defun untyped-p (item) (member (ty-kind (item-type item)) '(:untyped-int :untyped-real))) (defun need-value (item) "ITEM, checked to be a value: not a type, a module, nor a call without one." (let ((tk (item-tok item))) (case (item-mode item) ((:const :var :val) item) (:literal (fail-tok tk "the literal's type isn't known here")) (:proc (let ((sig (obj-sig (item-obj item)))) (val-item (make-proc-type sig) (proc-handle (item-obj item)) tk))) (:case (build-case item nil)) (:type (fail-tok tk "the type ~a isn't a value" (type-name (item-type item)))) (:multi (fail-tok tk "a call with several results isn't one value")) (:none (fail-tok tk "the procedure has no result")) (:builtin (fail-tok tk "~a is a built-in procedure, not a value" (item-val item))) (:module (fail-tok tk "a module isn't a value")) (t (fail-tok tk "this isn't a value"))))) (defun const-form (item) "The Lisp value of a constant ITEM, as the compiled code holds it." (let ((ty (item-type item)) (v (item-val item))) (case (ty-kind ty) (:string (string-slice v)) (:untyped-real v) (t v)))) (defun value-form (item) "The Lisp form of ITEM's value: a scalar's value, an aggregate's address." (let ((item (need-value item))) (ecase (item-mode item) (:const (const-form item)) (:var (if (aggregate-p (item-type item)) (item-form item) `(ld ,(access-kind (item-type item)) ,(item-form item)))) (:val (item-form item)) (:literal (fail-tok (item-tok item) "the literal's type isn't known here"))))) ;;; Assignability (5.10): whether a value of ITEM can go where a TY is ;;; wanted, and the form of it there. (defun assign-error (item ty) "Nil if ITEM can be assigned to a TY, or why not." (let* ((from (item-type item)) (fk (and from (ty-kind from))) (tk (ty-kind ty))) (cond ((eq (item-mode item) :literal) (literal-error item ty)) ((and (eq (item-mode item) :proc)) (unless (and (eq tk :proc) (sig-alike-p (obj-sig (item-obj item)) (ty-sig ty))) "the procedure's signature isn't the type's")) ((eq (item-mode item) :case) (unless (and (eq tk :variant) (eq (vcase-variant (item-val item)) ty)) "the case isn't of this variant")) ((same-type-p from ty) nil) ((eq fk :untyped-int) (cond ((not (eq tk :int)) (format nil "an integer constant isn't ~a" (type-name ty))) ((not (fits-p (item-val item) ty)) (format nil "~d doesn't fit ~a" (item-val item) (type-name ty))))) ((eq fk :untyped-real) (unless (eq tk :real) (format nil "a real constant isn't ~a" (type-name ty)))) ((eq fk :nil) (unless (nil-able-p ty) (format nil "nil isn't ~a" (type-name ty)))) ((eq fk :string) (unless (or (and (eq tk :slice) (same-type-p (ty-elem ty) (basic "U8"))) (and (eq tk :ptr) (same-type-p (ptr-base ty) (basic "U8")) (not (ty-vol ty))) (and (eq tk :array) (same-type-p (ty-elem ty) (basic "U8")) (>= (ty-len ty) (ty-len from)))) (format nil "a string isn't ~a" (type-name ty)))) ((and (eq fk :ptr) (eq tk :ptr) (ty-vol ty) (not (ty-vol from)) (same-type-p (ptr-base from) (ptr-base ty))) nil) ((and (eq fk :array) (eq tk :slice) (same-type-p (ty-elem from) (ty-elem ty))) (cond ((eq (item-ro item) :export) "another module's array can't be used as a slice") ((item-vol item) "a volatile array can't be used as a slice") ((item-noaddr item) "a field of a packed record has no address"))) ((and (eq fk :int) (eq tk :int) (or (and (eq from (basic "INT")) (eq ty (basic "I64"))) (and (eq from (basic "UINT")) (eq ty (basic "U64"))))) nil) (t (format nil "~a isn't ~a" (type-name from) (type-name ty)))))) (defun coerce-item (item ty &optional (tok (item-tok item))) "The form of ITEM's value as a TY, which it must be assignable to." (unless (member (item-mode item) '(:literal :proc :case)) (need-value item)) (let ((why (assign-error item ty))) (when why (fail-tok tok "~a" why))) (when (and (item-vol item) (aggregate-p ty)) (fail-tok tok "a whole record or array can't be copied through a volatile pointer")) (let ((from (item-type item))) (cond ((eq (item-mode item) :literal) (build-literal item ty)) ((eq (item-mode item) :case) (value-form (build-case item nil))) ((eq (item-mode item) :proc) (proc-handle (item-obj item))) ((is from :untyped-real) (if (= (ty-bits ty) 32) (coerce (item-val item) 'single-float) (item-val item))) ((is from :nil) 0) ((is from :string) (let ((bytes (item-val item))) (ecase (ty-kind ty) (:slice (string-slice bytes)) (:ptr (string-address bytes)) (:array (let ((padded (make-array (ty-len ty) :element-type '(unsigned-byte 8) :initial-element 0))) (replace padded bytes) ;; a padded copy, the rest zero, to copy from (let ((a (data-alloc (ty-len ty) 1))) (data-put a padded) a)))))) ((and (is from :array) (is ty :slice)) (let ((tmp (temp ty))) `(slice ,tmp ,(item-form item) ,(ty-len from)))) (t (value-form item))))) ;;; Storing: the form that puts ITEM, as a TY, at ADDR. (defun store-form (addr ty item &optional (tok (item-tok item))) (let ((v (coerce-item item ty tok))) (if (aggregate-p ty) `(move ,addr ,v ,(ty-size ty)) `(st ,(access-kind ty) ,addr ,v)))) ;;; Literals (6.5), built once their type is known. (defun literal-error (item ty) (destructuring-bind (kind elems) (item-val item) (ecase kind (:array (cond ((not (member (ty-kind ty) '(:array :slice))) (format nil "an array literal isn't ~a" (type-name ty))) ((and (is ty :array) (/= (length elems) (ty-len ty))) (format nil "the literal has ~d elements, not ~d" (length elems) (ty-len ty))) (t (loop for e in elems thereis (assign-error e (ty-elem ty)))))) (:record (if (not (is ty :record)) (format nil "a record literal isn't ~a" (type-name ty)) (loop for (name . e) in elems for f = (find-field ty name (item-tok e)) thereis (assign-error e (field-type f))))) (:set (if (not (is ty :set)) (format nil "a set literal isn't ~a" (type-name ty)) (loop for e in elems thereis (assign-error e (ty-enum ty))))) (:empty (unless (member (ty-kind ty) '(:record :set)) (format nil "{} isn't ~a" (type-name ty))))))) (defun build-literal (item ty) "The form of the literal ITEM's value as a TY: the address of a temporary holding it, or a set's bits." (destructuring-bind (kind elems) (item-val item) (cond ((is ty :set) (let ((consts (remove-if-not #'const-p elems)) (vars (remove-if #'const-p elems))) (let ((bits (reduce #'logior (mapcar (lambda (e) (ash 1 (item-val e))) consts) :initial-value 0))) (if vars `(logior ,bits ,@(mapcar (lambda (e) `(ash 1 ,(value-form e))) vars)) bits)))) ((is ty :slice) ;; a hidden array of the procedure (6.5), and a slice of it (let* ((arr (make-array-type (max 1 (length elems)) (ty-elem ty))) (a (build-literal item (if elems arr (make-array-type 1 (ty-elem ty))))) (s (temp ty))) `(slice ,s ,a ,(length elems)))) (t (let ((tmp (temp ty)) (es (ty-size (or (ty-elem ty) ty)))) `(let ((at ,tmp)) (zero at ,(ty-size ty)) ,@(if (eq kind :array) (loop for e in elems for i from 0 collect (store-form `(+ at ,(* i es)) (ty-elem ty) e)) (let ((seen '())) (loop for (name . e) in elems for f = (find-field ty name (item-tok e)) do (when (member name seen :test #'string=) (fail-tok (item-tok e) "the field ~a is given twice" name)) (push name seen) collect (store-form `(+ at ,(field-offset f)) (field-type f) e)))) at)))))) (defun find-field (ty name tok) (let ((f (find name (ty-fields ty) :key #'field-name :test #'string=))) (unless f (fail-tok tok "~a has no field ~a" (type-name ty) name)) (unless (or (field-exported f) (eq (ty-module ty) *module*)) (fail-tok tok "the field ~a isn't exported" name)) f)) ;;; A variant's case, built by calling it (5.6): a temporary holding its ;;; tag and its fields. (defun build-case (item args) (let* ((c (item-val item)) (vty (vcase-variant c)) (fields (vcase-fields c)) (tok (item-tok item))) (when (and (null args) fields) (fail-tok tok "the case ~a needs its fields" (vcase-name c))) (unless (= (length args) (length fields)) (fail-tok tok "the case ~a has ~d fields, not ~d" (vcase-name c) (length fields) (length args))) (let ((tmp (temp vty))) (val-item vty `(let ((at ,tmp)) (zero at ,(ty-size vty)) (st :i64 at ,(vcase-index c)) ,@(loop for f in fields for a in args collect (store-form `(+ at ,(field-offset f)) (field-type f) a)) at) tok)))) ;;; Expressions, by the grammar of section 6. (defun expression () (let ((x (conjunct))) (loop while (eq (kind) :or) do (let* ((tk (next-tok)) (y (conjunct))) (setf x (logical :or x y tk)))) x)) (defun conjunct () (let ((x (relation))) (loop while (eq (kind) :and) do (let* ((tk (next-tok)) (y (relation))) (setf x (logical :and x y tk)))) x)) (defun logical (op x y tk) (dolist (i (list x y)) (unless (is (item-type (need-value i)) :bool) (fail-tok tk "~(~a~) is for BOOLs only" op))) (if (and (const-p x) (const-p y)) (const-item (basic "BOOL") (if (eq op :and) (and (item-val x) (item-val y)) (or (item-val x) (item-val y))) tk) (val-item (basic "BOOL") `(,(if (eq op :and) 'and 'or) ,(value-form x) ,(value-form y)) tk))) (defun relation () (let ((x (simple-expr))) (if (member (kind) '(:= :|#| :< :<= :> :>= :in)) (let* ((tk (next-tok)) (y (simple-expr))) (compare (tok-kind tk) x y tk)) x))) (defun simple-expr () (let ((x (if (eq (kind) :-) (let ((tk (next-tok))) (negate (term) tk)) (term)))) (loop while (member (kind) '(:+ :- :|\|| :xor)) do (let* ((tk (next-tok)) (y (term))) (setf x (arith (tok-kind tk) x y tk)))) x)) (defun term () (let ((x (factor))) (loop while (member (kind) '(:* :/ :div :mod :& :shl :shr)) do (let* ((tk (next-tok)) (y (factor))) (setf x (arith (tok-kind tk) x y tk)))) x)) (defun factor () (let ((tk (tok))) (case (kind) (:int (next-tok) (const-item (if (> (tok-val tk) (int-max (basic "I64"))) (basic "U64") *untyped-int*) (tok-val tk) tk)) (:char (next-tok) (const-item *untyped-int* (tok-val tk) tk)) (:real (next-tok) (const-item *untyped-real* (tok-val tk) tk)) (:string (next-tok) (const-item (string-type (length (tok-val tk))) (tok-val tk) tk)) (:|(| (next-tok) (prog1 (expression) (expect :|)|))) (:not (next-tok) (let ((x (need-value (factor)))) (unless (is (item-type x) :bool) (fail-tok tk "not is for BOOLs only")) (if (const-p x) (const-item (item-type x) (not (item-val x)) tk) (val-item (item-type x) `(not ,(value-form x)) tk)))) (:~ (next-tok) (let* ((x (need-value (factor))) (ty (item-type x))) (unless (member (ty-kind ty) '(:int :untyped-int)) (fail-tok tk "~~ is for integers only")) (cond ((and (const-p x) (is ty :untyped-int)) (const-item ty (lognot (item-val x)) tk)) ((const-p x) (const-item ty (wrap-int (lognot (item-val x)) ty) tk)) (t (val-item ty (wrap-form ty `(lognot ,(value-form x))) tk))))) (:|[| (next-tok) (let ((elems '())) (unless (eq (kind) :|]|) (loop (push (expression) elems) (unless (accept :|,|) (return)))) (expect :|]|) (make-item :mode :literal :val (list :array (nreverse elems)) :tok tk))) (:{ (next-tok) (brace-literal tk)) (:^ (next-tok) (let ((ty (pointer-type-rest))) (expect :|(|) ;; selectors may follow, as in ^T(x)^ (section 6) (selectors (prog1 (convert ty (expression) tk) (expect :|)|))))) (:try (next-tok) (try-item tk)) (:ident (designator)) (t (fail-here "an expression expected, not ~a" (describe-tok tk)))))) (defun brace-literal (tk) "{...}: a record literal if its first element names a field, else a set." (cond ((accept :}) (make-item :mode :literal :val (list :empty nil) :tok tk)) ((and (eq (kind) :ident) (eq (kind 1) :|:|)) (let ((fields '())) (loop (let ((ftk (tok)) (name (ident))) (expect :|:|) (let ((e (expression))) (setf (item-tok e) (or (item-tok e) ftk)) (push (cons name e) fields))) (unless (accept :|,|) (return))) (expect :}) (make-item :mode :literal :val (list :record (nreverse fields)) :tok tk))) (t (let ((elems '())) (loop (push (need-value (expression)) elems) (unless (accept :|,|) (return))) (expect :}) (setf elems (nreverse elems)) ;; the set's type is its first name's enumeration's set (6.6) (let ((enum (item-type (first elems)))) (unless (is enum :enum) (fail-tok tk "a set's elements are names of an enumeration")) (dolist (e elems) (unless (same-type-p (item-type e) enum) (fail-tok (item-tok e) "the set's elements are of two enumerations"))) (let ((item (make-item :mode :literal :val (list :set elems) :tok tk)) (sty (set-type-of enum))) (if (every #'const-p elems) (const-item sty (build-literal item sty) tk) (val-item sty (build-literal item sty) tk)))))))) (defun set-type-of (enum) "The anonymous set type of ENUM: alike wherever it is made." (make-set-type enum)) ;;; Integers and reals: the operands' common type (6.1, 6.3). (defun wrap-form (ty form) (if (ty-signed ty) `(sb-c::mask-signed-field ,(ty-bits ty) ,form) `(ldb (byte ,(ty-bits ty) 0) ,form))) (defun unify (x y tk) "The type both X and Y have, an untyped constant taking the other's." (let ((a (item-type x)) (b (item-type y))) (flet ((takes (c ty) ; constant C taking type TY (let ((why (assign-error c ty))) (when why (fail-tok tk "~a" why))))) (cond ((and (untyped-p x) (untyped-p y)) (unless (eq a b) (fail-tok tk "an integer and a real don't mix")) a) ((untyped-p x) (takes x b) b) ((untyped-p y) (takes y a) a) ((same-type-p a b) a) (t (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b))))))) (defun typed-const (item ty) "The value of constant ITEM as a TY." (let ((v (item-val item))) (if (and (is ty :real) (= (ty-bits ty) 32) (typep v 'double-float)) (coerce v 'single-float) v))) (defun check-const-int (v tk) (unless (<= (- (expt 2 63)) v (1- (expt 2 63))) (fail-tok tk "the constant ~d is beyond the I64s" v)) v) (defun arith (op x y tk) "X op Y for the adding and multiplying operators." (setf x (need-value x) y (need-value y)) (let ((a (item-type x)) (b (item-type y))) (cond ;; strings join (section 4) ((and (eq op :+) (is a :string) (is b :string) (const-p x) (const-p y)) (let ((s (concatenate '(vector (unsigned-byte 8)) (item-val x) (item-val y)))) (const-item (string-type (length s)) (coerce s '(simple-array (unsigned-byte 8) (*))) tk))) ;; pointers move by elements (6.4) ((and (is a :ptr) (member op '(:+ :-)) (member (ty-kind b) '(:int :untyped-int))) (val-item a `(ldb (byte 64 0) (,(if (eq op :+) '+ '-) ,(value-form x) (* ,(value-form y) ,(ty-size (ptr-base a))))) tk)) ((and (is a :ptr) (eq op :-) (is b :ptr)) (unless (same-type-p a b) (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b))) (val-item (basic "INT") `(values (truncate (sb-c::mask-signed-field 64 (- ,(value-form x) ,(value-form y))) ,(max 1 (ty-size (ptr-base a))))) tk)) ((member op '(:shl :shr)) (shift op x y tk)) (t (let ((ty (unify x y tk))) (case (ty-kind ty) ((:int :untyped-int) (int-arith op x y ty tk)) ((:real :untyped-real) (real-arith op x y ty tk)) (:set (set-arith op x y ty tk)) (t (fail-tok tk "~(~a~) isn't defined on ~a" op (type-name ty))))))))) (defun int-arith (op x y ty tk) (unless (member op '(:+ :- :* :div :mod :& :|\|| :xor)) (fail-tok tk "~(~a~) isn't defined on integers~@[; div divides them~]" op (eq op :/))) (let ((lisp-op (ecase op (:+ '+) (:- '-) (:* '*) (:& 'logand) (:|\|| 'logior) (:xor 'logxor) (:div 'div) (:mod 'mod)))) (if (and (const-p x) (const-p y)) (let* ((a (item-val x)) (b (item-val y)) (v (case lisp-op ((div mod) (when (= b 0) (fail-tok tk "a division by zero in a constant")) (when (and (is ty :int) (ty-signed ty) (= b -1) (= a (int-min ty))) (fail-tok tk "the smallest ~a divided by -1 in a constant" (type-name ty))) (if (eq lisp-op 'mod) (rem a b) (values (truncate a b)))) (t (funcall lisp-op a b))))) (const-item ty (if (is ty :untyped-int) (check-const-int v tk) (wrap-int v ty)) tk)) (let* ((ty (if (is ty :untyped-int) (basic "INT") ty)) (a (coerce-item x ty tk)) (b (coerce-item y ty tk))) (val-item ty (if (member lisp-op '(div mod)) `(divide ,a ,b ,(ty-bits ty) ,(ty-signed ty) ,(where tk) ,(eq lisp-op 'mod)) (wrap-form ty `(,lisp-op ,a ,b))) tk))))) (defun real-arith (op x y ty tk) (unless (member op '(:+ :- :* :/)) (fail-tok tk "~(~a~) isn't defined on reals" op)) (let ((lisp-op (ecase op (:+ '+) (:- '-) (:* '*) (:/ '/)))) (if (and (const-p x) (const-p y)) (const-item ty (funcall lisp-op (typed-const x ty) (typed-const y ty)) tk) (val-item ty `(,lisp-op ,(coerce-item x ty tk) ,(coerce-item y ty tk)) tk)))) (defun set-arith (op x y ty tk) (let ((f (case op (:+ 'logior) (:* 'logand) (:- 'logandc2) (t (fail-tok tk "~(~a~) isn't defined on sets" op))))) (if (and (const-p x) (const-p y)) (const-item ty (funcall f (item-val x) (item-val y)) tk) (val-item ty `(,f ,(value-form x) ,(value-form y)) tk)))) (defun shift (op x y tk) ;; by y modulo the width of x's type; an untyped x stays untyped (6.1) (let ((a (item-type x)) (b (item-type y))) (unless (member (ty-kind b) '(:int :untyped-int)) (fail-tok tk "a shift's count is an integer")) (unless (member (ty-kind a) '(:int :untyped-int)) (fail-tok tk "~(~a~) is for integers" op)) (when (and (is a :untyped-int) (not (const-p y))) (setf a (basic "INT"))) (cond ((and (is a :untyped-int) (const-p x)) (let ((n (item-val y))) (when (< n 0) (fail-tok tk "a negative shift of a constant")) (const-item a (check-const-int (if (eq op :shl) (ash (item-val x) (min n 64)) (ash (item-val x) (- n))) tk) tk))) ((and (const-p x) (const-p y)) (let ((n (mod (item-val y) (ty-bits a)))) (const-item a (wrap-int (ash (item-val x) (if (eq op :shl) n (- n))) a) tk))) (t (let ((n `(mod ,(value-form y) ,(ty-bits a)))) (val-item a (if (eq op :shl) (wrap-form a `(ash ,(coerce-item x a tk) ,n)) `(ash ,(coerce-item x a tk) (- ,n))) tk)))))) (defun negate (x tk) (let* ((x (need-value x)) (ty (item-type x))) (case (ty-kind ty) (:untyped-int (if (const-p x) (const-item ty (- (item-val x)) tk) (fail-tok tk "?"))) (:untyped-real (const-item ty (- (item-val x)) tk)) (:int (if (const-p x) (const-item ty (wrap-int (- (item-val x)) ty) tk) (val-item ty (wrap-form ty `(- ,(value-form x))) tk))) (:real (if (const-p x) (const-item ty (- (item-val x)) tk) (val-item ty `(- ,(value-form x)) tk))) (t (fail-tok tk "- isn't defined on ~a" (type-name ty)))))) ;;; Relations. (defun sequence-parts (item) "For an array, a slice or a string: the forms of its first element's address and its length, and its element type." (let ((ty (item-type item))) (ecase (ty-kind ty) (:string (values (string-address (item-val item)) (length (item-val item)) (basic "U8"))) (:array (values (value-form item) (ty-len ty) (ty-elem ty))) (:slice (let ((s (var-sym "S"))) (values `(ld :u64 ,s) `(ld :i64 (+ ,s 8)) (ty-elem ty) s (value-form item))))))) (defun compare (op x y tk) (when (eq op :in) (return-from compare (membership x y tk))) ;; a literal or nil takes the other side's type (when (eq (item-mode x) :literal) (rotatef x y) (setf op (case op (:< :>) (:> :<) (:<= :>=) (:>= :<=) (t op)))) (setf x (need-value x)) (when (eq (item-mode y) :literal) (setf y (val-item (item-type x) (coerce-item y (item-type x) tk) tk))) (setf y (need-value y)) (let ((a (item-type x)) (b (item-type y)) (bool (basic "BOOL"))) (cond ((and (member (ty-kind a) '(:array :slice :string)) (member (ty-kind b) '(:array :slice :string))) (sequence-compare op x y tk)) ((or (is a :nil) (is b :nil)) (let ((other (if (is a :nil) b a))) (unless (or (nil-able-p other) (is other :nil)) (fail-tok tk "nil isn't ~a" (type-name other))) (unless (member op '(:= :|#|)) (fail-tok tk "~(~a~) doesn't compare nil" op)) (val-item bool `(,(if (eq op :=) '= '/=) ,(value-form x) ,(value-form y)) tk))) (t (let* ((ty (unify x y tk)) (k (ty-kind ty))) (unless (member k '(:int :untyped-int :real :untyped-real :bool :enum :set :ptr :proc :error)) (fail-tok tk "~a doesn't compare" (type-name ty))) (when (and (member k '(:bool :proc :error)) (not (member op '(:= :|#|)))) (fail-tok tk "~a compares with = and # only" (type-name ty))) (when (and (eq k :set) (member op '(:< :>))) (fail-tok tk "sets compare with =, #, <= and >=")) (let ((f (if (eq k :set) (ecase op (:= '=) (:|#| '/=) (:<= 'subset) (:>= 'superset)) (ecase op (:= (if (eq k :bool) 'eq '=)) (:|#| (if (eq k :bool) 'neq '/=)) (:< '<) (:<= '<=) (:> '>) (:>= '>=))))) (if (and (const-p x) (const-p y)) (const-item bool (funcall f (typed-const x ty) (typed-const y ty)) tk) (val-item bool `(,f ,(coerce-item x ty tk) ,(coerce-item y ty tk)) tk)))))))) (defun neq (a b) (not (eq a b))) (defun subset (a b) (= 0 (logandc2 a b))) (defun superset (a b) (= 0 (logandc2 b a))) (defun sequence-compare (op x y tk) ;; equal lengths and equal elements, for elements that compare by bytes (6.5) (unless (member op '(:= :|#|)) (fail-tok tk "arrays and strings compare with = and # only")) (multiple-value-bind (pa la ea sa fa) (sequence-parts x) (multiple-value-bind (pb lb eb sb fb) (sequence-parts y) (unless (same-type-p ea eb) (fail-tok tk "the two sides' elements are of two types")) (unless (bytewise-comparable-p ea) (fail-tok tk "arrays of ~a don't compare" (type-name ea))) (when (or (item-vol x) (item-vol y)) (fail-tok tk "a volatile array doesn't compare")) (let ((form `(let* (,@(when sa `((,sa ,fa))) ,@(when sb `((,sb ,fb))) (la ,la) (lb ,lb)) (and (= la lb) (bytes-equal ,pa ,pb (* la ,(ty-size ea))))))) (val-item (basic "BOOL") (if (eq op :=) form `(not ,form)) tk))))) (defun membership (x y tk) (setf x (need-value x) y (need-value y)) (unless (and (is (item-type y) :set) (same-type-p (item-type x) (ty-enum (item-type y)))) (fail-tok tk "in takes a name of an enumeration and a set of it")) (if (and (const-p x) (const-p y)) (const-item (basic "BOOL") (logbitp (item-val x) (item-val y)) tk) (val-item (basic "BOOL") `(logbitp ,(value-form x) ,(value-form y)) tk))) ;;; Designators: a name and its selectors (section 6). (defun qualified-obj () "The object a QualIdent names, a module's export if it starts with a module." (let* ((tk (tok)) (name (ident)) (obj (lookup name))) (unless obj (fail-tok tk "~a isn't declared" name)) (if (eq (obj-kind obj) :module) (progn (expect :|.|) (let* ((mtk (tok)) (member (ident)) (m (import-module (obj-val obj) tk)) (o (gethash member (module-exports m)))) (unless o (fail-tok mtk "~a has no export ~a" (obj-name obj) member)) (values o mtk))) (values obj tk)))) (defun obj-item (obj tk) "The item of a name." (ecase (obj-kind obj) (:const (if (aggregate-p (obj-type obj)) (if (is (obj-type obj) :string) (const-item (obj-type obj) (obj-val obj) tk) (make-item :mode :var :type (obj-type obj) :form (obj-val obj) :ro :const :tok tk)) (const-item (obj-type obj) (obj-val obj) tk))) (:type (make-item :mode :type :type (obj-type obj) :tok tk)) (:var (make-item :mode :var :type (obj-type obj) :form (var-address obj) :tok tk :ro (when (and (obj-module obj) (not (eq (obj-module obj) *module*))) :export))) (:proc (make-item :mode :proc :obj obj :tok tk)) (:builtin (make-item :mode :builtin :val (obj-name obj) :tok tk)) (:case (make-item :mode :case :val (obj-val obj) :type (vcase-variant (obj-val obj)) :tok tk)))) (defun var-address (obj) (let ((w (obj-where obj))) (ecase (first w) (:global (second w)) (:local `(+ fp ,(second w))) (:var-param `(ld :u64 (+ fp ,(second w)))) (:at (second w)) (:extern `(sb-sys:find-foreign-symbol-address ,(second w)))))) (defun designator () (multiple-value-bind (obj tk) (qualified-obj) (selectors (obj-item obj tk)))) (defun selectors (item) (loop (let ((tk (tok))) (case (kind) (:|.| (next-tok) (setf item (select-field item (ident) tk))) (:^ (next-tok) (setf item (dereference item tk))) (:|[| (next-tok) (setf item (index item tk))) (:|(| (setf item (call item tk))) (t (return item)))))) (defun select-field (item name tk) (let* ((item (need-value item)) (ty (item-type item))) (case (ty-kind ty) (:record (let ((f (find-field ty name tk))) (make-item :mode :var :type (field-type f) :tok tk :form `(+ ,(value-form item) ,(field-offset f)) :ro (or (item-ro item) (and (eq (item-mode item) :val) :value)) :vol (item-vol item) :noaddr (or (item-noaddr item) (and (ty-packed ty) (> (ty-align (field-type f)) 1)))))) (:ptr (fail-tok tk "a pointer's fields are p^.~a" name)) (:variant (fail-tok tk "a variant's fields are read by match")) (t (fail-tok tk "~a has no fields" (type-name ty)))))) (defun dereference (item tk) (let* ((item (need-value item)) (ty (item-type item))) (unless (is ty :ptr) (fail-tok tk "^ follows a pointer, not ~a" (type-name ty))) (make-item :mode :var :type (ptr-base ty) :form (value-form item) :vol (ty-vol ty) :tok tk))) (defun integer-operand (tk what) "An expression of any integer type (6.1): the form of its value." (let ((x (need-value (expression)))) (unless (member (ty-kind (item-type x)) '(:int :untyped-int)) (fail-tok tk "~a is an integer, not ~a" what (type-name (item-type x)))) (value-form x))) (defun index (item tk) "a[i] or a[lo..hi]; the `[` is read." (let* ((item (need-value item)) (ty (item-type item)) (check (not (module-check-off *module*)))) (when (is ty :string) ;; a string constant is indexed and sliced as an array of U8 (setf ty (make-array-type (ty-len ty) (basic "U8")) item (make-item :mode :var :type ty :form (string-address (item-val item)) :ro :string :tok tk))) (unless (member (ty-kind ty) '(:array :slice :ptr)) (fail-tok tk "~a can't be indexed" (type-name ty))) (when (and (is ty :ptr) (is (ptr-base ty) :array)) (fail-tok tk "a pointer to an array is indexed as p^[i]")) (let* ((elem (if (is ty :ptr) (ptr-base ty) (ty-elem ty))) (size (ty-size elem)) (base (var-sym "A")) (len (var-sym "N")) (lo (integer-operand tk "an index"))) (multiple-value-bind (base-form len-form) (ecase (ty-kind ty) (:array (values (value-form item) (ty-len ty))) (:slice (values `(ld :u64 ,(value-form item)) `(ld :i64 (+ ,(value-form item) 8)))) (:ptr (values (value-form item) nil))) (if (accept :..) (let ((hi (integer-operand tk "a slice's bound")) (h (var-sym "H")) (l (var-sym "L")) (sty (make-slice-type elem))) (expect :|]|) (when (is ty :array) (case (item-ro item) (:export (fail-tok tk "another module's array can't be sliced"))) (when (item-vol item) (fail-tok tk "a volatile array can't be sliced"))) (when (and (item-noaddr item) (> (ty-align elem) 1)) (fail-tok tk "a field of a packed record has no address to slice")) (val-item sty `(let* ((,base ,(if (is ty :slice) (value-form item) base-form)) (,l ,lo) (,h ,hi) ,@(when (is ty :slice) `((,len (ld :i64 (+ ,base 8))) (,base (ld :u64 ,base))))) ,(when (or check (is ty :ptr)) `(check-slice ,l ,h ,(cond ((is ty :ptr) nil) ((is ty :slice) len) (t len-form)) ,(where tk))) (slice ,(temp sty) (ldb (byte 64 0) (+ ,base (* ,l ,size))) (- ,h ,l))) tk)) (progn (expect :|]|) (make-item :mode :var :type elem :tok tk :form (cond ((is ty :ptr) `(ldb (byte 64 0) (+ ,base-form (* ,lo ,size)))) ((is ty :slice) `(let ((,base ,(value-form item))) (+ (ld :u64 ,base) (* ,(if check `(check-index ,lo (ld :i64 (+ ,base 8)) ,(where tk)) lo) ,size)))) ((and (integerp lo) (not (< -1 lo len-form))) ;; a constant index out of an array would stop the program (fail-tok tk "index ~d is out of range for a length of ~d" lo len-form)) (t `(+ ,base-form (* ,(if check `(check-index ,lo ,len-form ,(where tk)) lo) ,size)))) :ro (if (is ty :array) (item-ro item) nil) :vol (and (is ty :array) (item-vol item)) :noaddr (and (is ty :array) (item-noaddr item))))))))) ;;; Conversions (6.7). (defun convert (ty x tk) (let* ((x (need-value x)) (from (item-type x)) (fk (ty-kind from)) (tk2 (ty-kind ty))) (flet ((bad () (fail-tok tk "~a doesn't convert to ~a" (type-name from) (type-name ty))) (result (const form) (if (const-p x) (const-item ty const tk) (val-item ty form tk)))) (let ((v (unless (const-p x) (value-form x))) (c (when (const-p x) (item-val x)))) (case tk2 (:int (case fk ((:int :untyped-int) (result (and c (wrap-int c ty)) (wrap-form ty v))) ((:real :untyped-real) (result (and c (real-to-int c (ty-bits ty) (ty-signed ty))) `(real-to-int ,v ,(ty-bits ty) ,(ty-signed ty)))) ((:enum :set) (result c v)) ((:ptr :proc) (unless (member (ty-name ty) '("INT" "UINT") :test #'equal) (bad)) (val-item ty (if (ty-signed ty) `(sb-c::mask-signed-field 64 ,v) v) tk)) (t (bad)))) (:real (let ((lisp-ty (if (= (ty-bits ty) 32) 'single-float 'double-float))) (case fk ((:int :untyped-int :real :untyped-real) (result (and c (coerce c lisp-ty)) `(coerce ,v ',lisp-ty))) (t (bad))))) (:enum (unless (member fk '(:int :untyped-int)) (if (same-type-p from ty) (return-from convert x) (bad))) (let ((n (length (ty-names ty)))) (when (and c (not (< -1 c n))) (fail-tok tk "~d is no position of the enumeration" c)) (result c `(check-enum ,v ,n ,(where tk))))) (:set (unless (member fk '(:int :untyped-int)) (if (same-type-p from ty) (return-from convert x) (bad))) (result (and c (ldb (byte (* 8 (ty-size ty)) 0) c)) `(ldb (byte ,(* 8 (ty-size ty)) 0) ,v))) ((:ptr :proc) (cond ((member fk '(:ptr :proc)) (val-item ty (value-form x) tk)) ((or (eq fk :untyped-int) (and (eq fk :int) (member (ty-name from) '("INT" "UINT") :test #'equal))) (val-item ty `(ldb (byte 64 0) ,(value-form x)) tk)) ((eq fk :nil) (val-item ty 0 tk)) (t (bad)))) (:bool (if (eq fk :bool) x (bad))) (t (bad))))))) ;;; Calls (section 8): of procedures, procedure values, built-ins, ;;; conversions and variants' cases. (defun call (item tk) "ITEM applied to the arguments that follow, `(` and all." (case (item-mode item) (:type (next-tok) (prog1 (convert (item-type item) (expression) tk) (expect :|)|))) (:builtin (next-tok) (builtin (item-val item) tk)) (:case (next-tok) (let ((args (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))))) (expect :|)|) (when (null args) (fail-tok tk "() after a case without fields")) (build-case item args))) (:proc (call-proc (item-obj item) nil tk)) (t (let ((v (need-value item))) (unless (is (item-type v) :proc) (fail-tok tk "~a isn't a procedure" (type-name (item-type v)))) (call-proc nil v tk))))) (defun read-args () "The arguments in parentheses, if there are parentheses." (when (accept :|(|) (prog1 (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))) (expect :|)|)))) (defun arg-forms (sig args tk) "The forms passing ARGS to the parameters of SIG." (let ((params (sig-params sig))) (when (or (< (length args) (length params)) (and (> (length args) (length params)) (not (sig-varargs sig)))) (fail-tok tk "~d arguments for ~d parameters" (length args) (length params))) (loop for a in args for i from 0 for p = (nth i params) collect (cond ((null p) (vararg-form a)) ((third p) (var-arg-form a (second p))) (t (coerce-item a (second p) (item-tok a))))))) (defun var-arg-form (a ty) "A `var` argument: the address of a variable of exactly the type." (let ((tk (item-tok a))) (unless (eq (item-mode a) :var) (fail-tok tk "a var parameter takes a variable")) (check-writable a tk "passed as a var argument") (when (item-vol a) (fail-tok tk "a volatile variable isn't passed as a var argument")) (when (item-noaddr a) (fail-tok tk "a field of a packed record has no address")) (unless (same-type-p (item-type a) ty) (fail-tok tk "a var parameter of ~a takes a variable of it, not ~a" (type-name ty) (type-name (item-type a)))) (item-form a))) (defun check-writable (a tk what) (case (item-ro a) (:export (fail-tok tk "another module's variable can't be ~a" what)) (:const (fail-tok tk "a constant can't be ~a" what)) (:string (fail-tok tk "a string's bytes can't be ~a" what)) (:value (fail-tok tk "a part of a value can't be ~a" what)))) (defun vararg-form (a) "An argument past an extern's parameters (section 9): as C takes it." (let* ((a (need-value a)) (ty (item-type a)) (tk (item-tok a))) (case (ty-kind ty) (:untyped-int (list 'sb-alien:long (item-val a))) (:untyped-real (list 'double-float (item-val a))) (:string (list 'sb-alien:unsigned-long (string-address (item-val a)))) (:real (when (= (ty-bits ty) 32) (fail-tok tk "C takes no F32 past the parameters: F64(x)")) (list 'double-float (value-form a))) ((:int :bool :ptr :proc) (list (alien-type ty) (c-value-form ty (value-form a)))) (t (fail-tok tk "~a doesn't go to C" (type-name ty)))))) (defun alien-type (ty) (ecase (ty-kind ty) (:int `(,(if (ty-signed ty) 'sb-alien:signed 'sb-alien:unsigned) ,(ty-bits ty))) (:bool '(sb-alien:unsigned 8)) (:real (if (= (ty-bits ty) 32) 'single-float 'double-float)) ((:ptr :proc :error) 'sb-alien:unsigned-long))) (defun c-value-form (ty form) "FORM's value as C takes it: a BOOL as 0 or 1, a procedure as the address of a C function that calls it." (case (ty-kind ty) (:bool `(if ,form 1 0)) (:proc (callback-form (ty-sig ty) form)) (t form))) (defun callback-form (sig form) "The address of a C function calling the procedure value FORM, made by SBCL the first time that value goes to C (section 9)." (let* ((params (sig-params sig)) (result (first (sig-results sig))) (args (loop for p in params collect (var-sym "A")))) `(c-callback ,form (lambda (fn) (sb-alien::alien-sap (sb-alien::alien-lambda ,(if result (alien-type result) 'sb-alien:void) ,(loop for a in args for p in params collect (list a (alien-type (second p)))) (in-raz-thread ,(let ((call `(funcall fn ,@(loop for a in args for p in params collect (if (is (second p) :bool) `(/= 0 ,a) a))))) (cond ((null result) `(progn ,call (values))) ((is result :bool) `(if ,call 1 0)) (t call)))))))))) (defun call-proc (obj value tk) "A call of procedure OBJ, or of the procedure VALUE: an item of its results." (let* ((sig (if obj (obj-sig obj) (ty-sig (item-type value)))) (fn (when value (value-form value))) (args (read-args)) (forms (arg-forms sig args tk)) (results (sig-results sig)) (dests (loop for r in results when (aggregate-p r) collect (temp r))) (form (cond ((and obj (sig-varargs sig)) (extern-call-form obj sig forms)) (obj `(,(obj-sym obj) ,@forms ,@dests)) (t `(funcall (proc-fn ,fn) ,@forms ,@dests))))) (let ((item (cond ((null results) (make-item :mode :none :form form :tok tk)) ((null (rest results)) (val-item (first results) form tk)) (t (make-item :mode :multi :type results :form form :tok tk))))) (setf (item-obj item) (list :call results)) item))) (defun extern-call-form (obj sig forms) "A call of a C procedure with `...`: the arguments past its parameters as VARARG-FORM made them, (alien-type form)." (let* ((params (sig-params sig)) (n (length params)) (r (first (sig-results sig)))) (c-result-form r `(sb-alien:alien-funcall (sb-alien:extern-alien ,(obj-extern obj) (function ,(if r (alien-type r) 'sb-alien:void) ,@(mapcar (lambda (p) (alien-type (second p))) params) ,@(mapcar #'first (nthcdr n forms)))) ,@(loop for p in params for f in forms collect (c-value-form (second p) f)) ,@(mapcar #'second (nthcdr n forms)))))) (defun c-result-form (ty form) (cond ((null ty) `(progn ,form (values))) ((is ty :bool) `(/= 0 ,form)) (t form))) ;;; try (7.8): the call's error looked at; if it isn't nil, the procedure ;;; returns it at once. (defun try-item (tk) (when (and *proc* (proc-in-defer *proc*)) (fail-tok tk "try can't leave a deferred statement")) (let* ((item (designator)) (item (if (eq (item-mode item) :proc) (call-proc (item-obj item) nil tk) item)) (call (item-obj item))) (unless (and (consp call) (eq (first call) :call)) (fail-tok tk "try is applied to a call of a procedure")) (let ((results (second call))) (unless (and results (is (car (last results)) :error)) (fail-tok tk "try needs a procedure whose last result is an ERROR")) (unless (and *proc* (proc-results *proc*) (is (car (last (proc-results *proc*))) :error)) (fail-tok tk "try stands in a procedure whose last result is an ERROR")) (let* ((vals (butlast results)) (syms (loop repeat (length vals) collect (var-sym "V"))) (e (var-sym "E")) (form `(multiple-value-bind (,@syms ,e) ,(item-form item) (unless (= ,e 0) ,(return-zeros-form e)) (values ,@syms)))) (cond ((null vals) (make-item :mode :none :form form :tok tk)) ((null (rest vals)) (val-item (first vals) form tk)) (t (make-item :mode :multi :type vals :form form :tok tk))))))) ;;; The built-in procedures (6.8); the `(` is read. (defun builtin-args () (prog1 (unless (eq (kind) :|)|) (loop collect (expression) while (accept :|,|))) (expect :|)|))) (defun builtin (name tk) "The item of a call of the built-in procedure NAME, marked as a call so that it may stand as a statement." (let ((item (builtin-call name tk))) (unless (item-obj item) (setf (item-obj item) (list :builtin))) item)) (defun builtin-call (name tk) (flet ((arity (args n &optional (m n)) (unless (<= n (length args) m) (fail-tok tk "~a takes ~d arguments, not ~d" name n (length args))) args)) (cond ((string= name "SIZE") (let ((ty (parse-type))) (expect :|)|) (const-item *untyped-int* (ty-size ty) tk))) (t (let ((args (builtin-args))) (macrolet ((arg (i) `(nth ,i args))) (cond ((string= name "ADR") (arity args 1) (let ((x (arg 0))) (unless (eq (item-mode x) :var) (fail-tok tk "ADR takes a variable")) ;; a string's bytes have an address, as a ^U8 made from it does (5.10) (unless (eq (item-ro x) :string) (check-writable x tk "given to ADR")) (when (item-noaddr x) (fail-tok tk "a field of a packed record has no address")) (val-item (make-ptr-type (item-type x) (item-vol x)) (item-form x) tk))) ((string= name "LEN") (arity args 1) (let* ((x (need-value (arg 0))) (ty (item-type x))) (case (ty-kind ty) (:array (const-item *untyped-int* (ty-len ty) tk)) (:string (const-item *untyped-int* (ty-len ty) tk)) (:slice (val-item (basic "INT") `(ld :i64 (+ ,(value-form x) 8)) tk)) (t (fail-tok tk "LEN takes an array, a slice or a string, not ~a" (type-name ty)))))) ((string= name "MSG") (arity args 1) (val-item (make-slice-type (basic "U8")) `(let ((e ,(coerce-item (arg 0) (basic "ERROR")))) (if (= e 0) ,(string-slice #()) e)) tk)) ((string= name "NEW") (arity args 2) (new-form (arg 0) (arg 1) tk)) ((string= name "COPY") (arity args 2) (copy-form (arg 0) (arg 1) tk)) ((member name '("INC" "DEC") :test #'string=) (arity args 1 2) (inc-form name args tk)) ((string= name "FENCE") (arity args 0) (make-item :mode :none :form '(sb-thread:barrier (:memory)) :tok tk)) ((member name '("CAS" "XCHG" "XADD") :test #'string=) (atomic name args tk)) ((string= name "SYSCALL") (arity args 1 7) (val-item (basic "INT") `(syscall ,@(loop for a in args collect (let* ((a (need-value a)) (ty (item-type a))) (unless (or (member (ty-kind ty) '(:int :untyped-int :ptr))) (fail-tok tk "SYSCALL takes integers and pointers")) (value-form a)))) tk)) ((string= name "ARGC") (arity args 0) (val-item (basic "INT") '(argc) tk)) ((string= name "ARGV") (arity args 0) (val-item (make-ptr-type (make-ptr-type (basic "U8") nil) nil) '(argv) tk)) (t (fail-tok tk "~a isn't a built-in procedure" name))))))))) (defun writable-var (x tk what) (unless (eq (item-mode x) :var) (fail-tok tk "~a takes a variable" what)) (check-writable x tk (format nil "changed by ~a" what)) x) (defun inc-form (name args tk) (let* ((v (writable-var (first args) tk name)) (ty (item-type v)) (a (var-sym "A"))) (unless (is ty :int) (fail-tok tk "~a takes an integer variable" name)) (let ((k (if (second args) (exact-form (second args) ty tk "the step") 1))) (make-item :mode :none :tok tk :form `(let ((,a ,(item-form v))) (st ,(access-kind ty) ,a ,(wrap-form ty `(,(if (string= name "INC") '+ '-) (ld ,(access-kind ty) ,a) ,k)))))))) (defun new-form (p a tk) ;; a^.alloc(a, SIZE(T), alignment), zeroed if not nil (let* ((p (writable-var p tk "NEW")) (ty (item-type p))) (unless (is ty :ptr) (fail-tok tk "NEW takes a pointer variable")) (let* ((alloc-ty (allocator-type tk)) (af (coerce-item a (make-ptr-type alloc-ty nil))) (base (ptr-base ty))) (make-item :mode :none :tok tk :form `(let* ((pa ,(item-form p)) (al ,af) (r (funcall (proc-fn (ld :u64 al)) al ,(ty-size base) ,(ty-align base)))) (unless (= r 0) (zero r ,(ty-size base))) (st :u64 pa r)))))) (defun allocator-type (tk) (let* ((m (gethash "Mem" *modules*)) (o (and m (gethash "Allocator" (module-exports m))))) (unless o (fail-tok tk "NEW needs the library's Mem.Allocator, which no module imports")) (obj-type o))) (defun copy-form (d s tk) ;; the elements of s to the start of d, as one block (6.8) (let ((d (need-value d)) (s (need-value s))) (dolist (x (list d s)) (unless (member (ty-kind (item-type x)) '(:array :slice :string)) (fail-tok tk "COPY takes arrays and slices"))) (when (and (is (item-type d) :array) (not (eq (item-mode d) :var))) (fail-tok tk "COPY's first is a variable")) (when (is (item-type d) :array) (check-writable d tk "changed by COPY")) (when (is (item-type d) :string) (fail-tok tk "COPY can't write a string")) (multiple-value-bind (pd ld ed sd fd) (sequence-parts d) (multiple-value-bind (ps ls es ss fs) (sequence-parts s) (unless (same-type-p ed es) (fail-tok tk "COPY's two sides' elements are of two types")) (make-item :mode :none :tok tk :form `(let* (,@(when sd `((,sd ,fd))) ,@(when ss `((,ss ,fs))) (ld ,ld) (ls ,ls)) ,(unless (module-check-off *module*) `(check-copy ls ld ,(where tk))) (move ,pd ,ps (* ls ,(ty-size ed))))))))) (defun atomic (name args tk) (let* ((n (if (string= name "CAS") 3 2))) (unless (= (length args) n) (fail-tok tk "~a takes ~d arguments" name n)) (let* ((p (need-value (first args))) (pty (item-type p))) (unless (is pty :ptr) (fail-tok tk "~a takes a pointer" name)) (let* ((ty (ptr-base pty)) (k (ty-kind ty))) (unless (or (member (ty-name ty) '("INT" "UINT") :test #'equal) (and (eq k :ptr) (not (string= name "XADD")))) (fail-tok tk "~a works on ~:[INT, UINT and pointers~;INT and UINT~]" name (string= name "XADD"))) (let ((signed (and (is ty :int) (ty-signed ty))) (rest (mapcar (lambda (a) (coerce-item a ty)) (rest args)))) (if (string= name "CAS") (val-item (basic "BOOL") `(cas ,(value-form p) ,@rest ,signed) tk) (val-item ty `(,(if (string= name "XCHG") 'xchg 'xadd) ,(value-form p) ,@rest ,signed) tk)))))))