random-int-form.lsp 117 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
;-*- Mode:     Lisp -*-
;;;; Author:   Paul Dietz
;;;; Created:  Wed Sep 10 18:03:52 2003
;;;; Contains: Simple randon form generator/tester

(in-package :cl-test)

(compile-and-load "random-aux.lsp")

;;;
;;; This file contains a routine for generating random legal Common Lisp functions
;;; for differential testing.
;;;
;;; To run the random tests by themselves, start a lisp in the ansi-tests directory
;;; and do the following:
;;;   (load "gclload1.lsp")
;;;   (compile-and-load "random-int-form.lsp")
;;;   (in-package :cl-test)
;;;   (let ((*random-state* (make-random-state t)))
;;;      (test-random-integer-forms 100 4 10000)) ;; or other parameters
;;;
;;; If a test breaks during testing the variables *optimized-fn-src*,
;;; *unoptimized-fn-src*, and *int-form-vals* can be used to get the source
;;; of the optimized/unoptimized lambda forms being compiled, and the arguments
;;; on which they are called.
;;;
;;; If a difference is found between optimized/unoptimized functions the forms,
;;; values, and results are collected.  A list of all these discrepancies is returned
;;; after testing finishes (assuming nothing breaks).
;;;
31 32 33 34 35
;;; The variable *compile-unoptimized-form* controls whether the low optimization
;;; form is compiled, or if a form funcalling it is EVALed.  The latter is often
;;; faster, and may find more problems since an interpreter and compiler may evaluate
;;; forms in very different ways.
;;;
36 37 38
;;; The rctest/ subdirectory contains fragments of a more OO random form generator
;;; that will eventually replace this preliminary effort.
;;;
39 40 41
;;; The file misc.lsp contains tests that were mostly for bugs found by this
;;; random tester in various Common Lisp implementations.
;;;
42

43
(declaim (special *optimized-fn-src* *unoptimized-fn-src* *int-form-vals*
pfdietz's avatar
pfdietz committed
44 45 46
                  *opt-result* *unopt-result* $x $y $z
                  *compile-unoptimized-form*
                  *make-random-integer-form-cdf*))
47

48 49 50 51 52
;;; Little functions used to run collected tests.
;;; (f i) runs the ith collected optimized test
;;; (g i) runs the ith collected unoptimized test
;;; (p i) prints the ith test (forms, input values, and other information)

53
(defun f (i) (let ((plist (elt $y i)))
pfdietz's avatar
pfdietz committed
54 55
               (apply (compile nil (getf plist :optimized-lambda-form))
                      (getf plist :vals))))
56 57

(defun g (i) (let ((plist (elt $y i)))
pfdietz's avatar
pfdietz committed
58 59 60 61 62
               (if *compile-unoptimized-form*
                   (apply (compile nil (getf plist :unoptimized-lambda-form))
                          (getf plist :vals))
                 (apply (the function (eval `(function ,(getf plist :unoptimized-lambda-form))))
                        (getf plist :vals)))))
63

64 65
(defun p (i) (write (elt $y i) :pretty t :escape t) (values))

66 67
(defun load-failures (&key (pathname "failures.lsp"))
  (length (setq $y (with-open-file (s pathname :direction :input)
pfdietz's avatar
pfdietz committed
68 69
                                   (loop for x = (read s nil)
                                         while x collect x)))))
70

71 72 73 74 75
(defun tn (n &optional (size 100))
  (length (setq $y (prune-results (setq $x (test-random-integer-forms size 2 n))))))

(declaim (special *s1* *s2* *s3* *s4* *s5* *s6* *s7* *s8* *s9*))

76 77 78
(defparameter *random-special-vars*
  #(*s1* *s2* *s3* *s4* *s5* *s6* *s7* *s8* *s9*))

79 80
(defparameter *loop-random-int-form-period* 2000)

81 82 83 84 85 86
(defmacro cl-handler-bind (&rest args)
  `(cl:handler-bind ,@args))

(defmacro cl-handler-case (&rest args)
  `(cl:handler-case ,@args))

pfdietz's avatar
pfdietz committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
(eval-when
 (:compile-toplevel :load-toplevel :execute)
 (defun cumulate (vec)
   (loop for i from 1 below (length vec)
         do (incf (aref vec i) (aref vec (1- i))))
   vec))

(defparameter *default-make-random-integer-form-cdf*
  (cumulate (copy-seq #(10 5 40 4 5 4 2 2 10 1 1 #-armedbead 1 #-armedbear 1
                       #-allegro 5 5 5 #-(or gcl ecl armedbear) 2
                       2 #-(or cmu allegro poplog) 5 4 30
                       4 20 3 2 2 1 1 5 30 #-poplog 5
                       #-(or allegro poplog) 10
                       50 4 4 10 20 10 10 3
                       20 5 #-(or armedbear) 20
                       2 2 2))))

(defparameter *make-random-integer-form-cdf*
  (copy-seq *default-make-random-integer-form-cdf*))

(eval-when
 (:compile-toplevel :load-toplevel :execute)
 (defmacro with-random-integer-form-params (&body forms)
   (let ((len (gensym "LEN"))
         (vec (gensym "VEC")))
     `(let* ((,len (length *default-make-random-integer-form-cdf*))
             (,vec (make-array ,len)))
        (loop for i from 0 below ,len do (setf (aref ,vec i)
sds's avatar
sds committed
115 116
                                               (1+ (min (random 100)
                                                        (random 100)))))
pfdietz's avatar
pfdietz committed
117 118 119 120
        (setq ,vec (cumulate ,vec))
        (let ((*make-random-integer-form-cdf* ,vec))
          ,@forms)))))

121 122 123
;;; Run the random tester, collecting failures into the special
;;; variable $y.

124 125 126 127 128 129 130 131
(defun loop-random-int-forms (&optional (size 200) (nvars 3))
  (unless (boundp '$x) (setq $x nil))
  (unless (boundp '$y) (setq $y nil))
  (loop
   for i from 1
   do
   (format t "~6D | " i)
   (finish-output *standard-output*)
132
   (let ((x (test-random-integer-forms
pfdietz's avatar
pfdietz committed
133 134
             size nvars *loop-random-int-form-period*
             :index (* (1- i) *loop-random-int-form-period*))))
135 136 137
     (when x
       (setq $x (append $x x))
       (setq x (prune-results x))
138
       (terpri) (print x) (finish-output *standard-output*)
139 140
       (setq $y (append $y x)))
     (terpri))))
141 142

(defvar *random-int-form-blocks* nil)
143
(defvar *random-int-form-catch-tags* nil)
144
(defvar *go-tags* nil)
145

146
(defvar *random-vals-list-bound* 10)
147

148 149 150
(defvar *max-compile-time* 0)
(defvar *max-compile-term* nil)

151 152
(defvar *print-immediately* nil)

153
(defvar *compile-unoptimized-form*
154 155
  #+(or allegro sbcl) t
  #-(or allegro sbcl) nil)
156

157 158 159 160 161 162
(declaim (special *vars*))

(defstruct var-desc
  (name nil :type symbol)
  (type t))

163
(defun test-random-integer-forms
164
  (size nvars n
pfdietz's avatar
pfdietz committed
165 166 167 168 169 170
        &key ((:random-state *random-state*) (make-random-state t))
        (file-prefix "b")
        (index 0)
        (random-size nil)
        (random-nvars nil)
        )
171 172 173 174 175 176 177 178 179

  "Generate random integer forms of size SIZE with NVARS variables.
   Do this N times, returning all those on which a discrepancy
   is found between optimized and nonoptimize, notinlined code."

  (assert (integerp nvars))
  (assert (<= 1 nvars 26))
  (assert (and (integerp n) (plusp n)))
  (assert (and (integerp n) (plusp size)))
180

181
  (loop for i from 1 to n
pfdietz's avatar
pfdietz committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        do (when (= (mod i 100) 0)
              ;; #+sbcl (print "Do gc...")
              ;; #+sbcl (sb-ext::gc :full t)
              ;; #+lispworks-personal-edition (cl-user::normal-gc)
              (prin1 i) (princ " ") (finish-output *standard-output*))
         nconc (let ((result (test-random-integer-form
                              (if random-size (1+ (random size)) size)
                              (if random-nvars (1+ (random nvars)) nvars)
                              :index (+ index i)
                              :file-prefix file-prefix)))
                 (when result
                   (let ((*print-readably* nil))
                     (format t "~%~A~%" (format nil "~S" (car result)))
                     (finish-output *standard-output*)))
                 result)))
197 198

(defun test-random-integer-form
199 200
  (size nvars &key (index 0) (file-prefix "b"))
  (let* ((vars (subseq '(a b c d e f g h i j k l m
pfdietz's avatar
pfdietz committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                           n o p q r s u v w x y z) 0 nvars))
         (var-ranges (mapcar #'make-random-integer-range vars))
         (var-types (mapcar #'(lambda (range)
                                (let ((lo (car range))
                                      (hi (cadr range)))
                                  (assert (>= hi lo))
                                  `(integer ,lo ,hi)))
                            var-ranges))
         (form (let ((*vars* (loop for v in vars
                                   for tp in var-types
                                   collect (make-var-desc :name v
                                                          :type tp)))
                     (*random-int-form-blocks* nil)
                     (*random-int-form-catch-tags* nil)
                     (*go-tags* nil)
                     )
                 (with-random-integer-form-params
                  (make-random-integer-form (1+ (random size))))))
         (vals-list
          (loop repeat *random-vals-list-bound*
                collect
                (mapcar #'(lambda (range)
                            (let ((lo (car range))
                                  (hi (cadr range)))
                              (random-from-interval (1+ hi) lo)))
                        var-ranges)))
         (opt-decls-1 (make-random-optimize-settings))
         (opt-decls-2 (make-random-optimize-settings)))
229
    (when *print-immediately*
230 231
      (with-open-file
       (s (format nil "~A~A.lsp" file-prefix index)
pfdietz's avatar
pfdietz committed
232
          :direction :output :if-exists :error)
233
       (print `(defparameter *x*
pfdietz's avatar
pfdietz committed
234 235 236 237 238 239 240
                 '(:vars ,vars
                      :var-types ,var-types
                      :vals-list ,vals-list
                      :decls1 ,opt-decls-1
                      :decls2 ,opt-decls-2
                      :form ,form))
              s)
241 242 243
       (print '(load "c.lsp") s)
       (finish-output s))
       ;; (cl-user::gc)
sds's avatar
sds committed
244
       ;; (make-list 1000000)
245 246 247 248
      )
    (test-int-form form vars var-types vals-list opt-decls-1 opt-decls-2)))

(defun make-random-optimize-settings ()
249
  (loop for settings = (list*
pfdietz's avatar
pfdietz committed
250 251 252 253 254 255 256 257 258
                        (list 'speed (random 4))
                        #+sbcl '(sb-c:insert-step-conditions 0)
                        (loop for s in '(space safety debug compilation-speed)
                              for n = (random 4)
                              collect (list s n)))
        while
        #+allegro (subsetp '((speed 3) (safety 0)) settings :test 'equal)
        #-allegro nil
        finally (return (random-permute settings))))
259 260 261 262 263 264 265

(defun fn-symbols-in-form (form)
  "Return a list of the distinct standardized lisp function
   symbols occuring ing FORM.  These are used to generate a NOTINLINE
   declaration for the unoptimized form."
  (intersection
   (remove-duplicates (fn-symbols-in-form* form) :test #'eq)
266
   *cl-function-or-accessor-symbols*))
267 268 269 270

(defun fn-symbols-in-form* (form)
  (when (consp form)
    (if (symbolp (car form))
pfdietz's avatar
pfdietz committed
271
        (cons (car form) (mapcan #'fn-symbols-in-form* (cdr form)))
272 273
      (mapcan #'fn-symbols-in-form* form))))

274 275
(defun fn-arg-name (fn-name arg-index)
  (intern (concatenate 'string
pfdietz's avatar
pfdietz committed
276 277
                       (subseq (symbol-name fn-name) 1)
                       (format nil "-~D" arg-index))
sds's avatar
sds committed
278
          (symbol-package fn-name)))
279

280
(declaim (special *flet-names*))
281 282
(defparameter *flet-names* nil)

283

pfdietz's avatar
pfdietz committed
284

285 286 287
(defun random-var-desc ()
  (loop
   (let* ((pos (random (length *vars*)))
pfdietz's avatar
pfdietz committed
288
          (desc (elt *vars* pos)))
289
     (when (= pos (position (var-desc-name desc) (the list *vars*)
pfdietz's avatar
pfdietz committed
290
                            :key #'var-desc-name))
291 292
       (return desc)))))

293 294 295 296 297 298 299
(defun is-zero-rank-integer-array-type (type)
  "This function was introduced because of a bug in ACL 6.2"
  ; (subtypep type '(array integer 0))
  (and (consp type)
       (eq (car type) 'array)
       (cddr type)
       (or (eq (cadr type) '*)
pfdietz's avatar
pfdietz committed
300
           (subtypep (cadr type) 'integer))
301
       (or (eql (caddr type) 0)
pfdietz's avatar
pfdietz committed
302
           (null (caddr type)))))
303

304 305
(defun make-random-integer-form (size)
  "Generate a random legal lisp form of size SIZE (roughly)."
pfdietz's avatar
pfdietz committed
306

307
  (if (<= size 1)
308
      ;; Leaf node -- generate a variable, constant, or flet function call
309 310 311
      (loop
       when
       (rcase
pfdietz's avatar
pfdietz committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        (10 (make-random-integer))
        (9 (if *vars*
               (let* ((desc (random-var-desc))
                      (type (var-desc-type desc))
                      (name (var-desc-name desc)))
                 (cond
                  ((subtypep type 'integer) name)
                  (; (subtypep type '(array integer 0))
                   (is-zero-rank-integer-array-type type)
                   `(aref ,name))
                  ((subtypep type '(cons integer integer))
                   (rcase (1 `(car ,name))
                          (1 `(cdr ,name))))
                  (t nil)))
             nil))
        (1 (if *go-tags* `(go ,(random-from-seq *go-tags*)) nil))
        (2 (if *flet-names*
               (let* ((flet-entry (random-from-seq *flet-names*))
                      (flet-name (car flet-entry))
                      (flet-minargs (cadr flet-entry))
                      (flet-maxargs (caddr flet-entry))
                      (nargs (random-from-interval (1+ flet-maxargs) flet-minargs))
                      (args (loop repeat nargs
                                  collect (make-random-integer-form 1))))
                 `(,flet-name ,@args))
             nil)))
338
       return it)
339
    ;; (> size 1)
pfdietz's avatar
pfdietz committed
340
    (rselect *make-random-integer-form-cdf*
341

342
     ;; flet call
pfdietz's avatar
pfdietz committed
343 344
     (make-random-integer-flet-call-form size)
     (make-random-aref-form size)
345
     ;; Unary ops
pfdietz's avatar
pfdietz committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
     (let ((op (random-from-seq '(- abs signum 1+ 1- conjugate
                                     rational rationalize
                                     numerator denominator
                                     identity progn floor
                                     ;; #-(or armedbear)
                                     ignore-errors
                                     cl:handler-case
                                     restart-case
                                     ceiling truncate round realpart imagpart
                                     integer-length logcount values
                                     locally))))
        `(,op ,(make-random-integer-form (1- size))))

     (make-random-integer-unwind-protect-form size)
     (make-random-integer-mapping-form size)
361

362
     ;; prog1, multiple-value-prog1
pfdietz's avatar
pfdietz committed
363 364 365 366 367
     (let* ((op (random-from-seq #(prog1 multiple-value-prog1)))
            (nforms (random 4))
            (sizes (random-partition (1- size) (1+ nforms)))
            (args (mapcar #'make-random-integer-form sizes)))
       `(,op ,@args))
368 369

     ;; prog2
pfdietz's avatar
pfdietz committed
370 371 372 373
     (let* ((nforms (random 4))
            (sizes (random-partition (1- size) (+ nforms 2)))
            (args (mapcar #'make-random-integer-form sizes)))
       `(prog2 ,@args))
sds's avatar
sds committed
374

pfdietz's avatar
pfdietz committed
375
     `(isqrt (abs ,(make-random-integer-form (- size 2))))
376

pfdietz's avatar
pfdietz committed
377
     `(the integer ,(make-random-integer-form (1- size)))
sds's avatar
sds committed
378

pfdietz's avatar
pfdietz committed
379 380
     `(cl:handler-bind nil ,(make-random-integer-form (1- size)))
     `(restart-bind nil ,(make-random-integer-form (1- size)))
pfdietz's avatar
pfdietz committed
381
     #-armedbear
pfdietz's avatar
pfdietz committed
382
     `(macrolet () ,(make-random-integer-form (1- size)))
pfdietz's avatar
pfdietz committed
383
     #-armedbear
pfdietz's avatar
pfdietz committed
384
     `(symbol-macrolet () ,(make-random-integer-form (1- size)))
385

386 387
     ;; dotimes
     #-allegro
pfdietz's avatar
pfdietz committed
388 389 390 391 392 393 394 395 396
     (let* ((var (random-from-seq #(iv1 iv2 iv3 iv4)))
            (count (random 4))
            (sizes (random-partition (1- size) 2))
            (body (let ((*vars* (cons (make-var-desc :name var :type nil)
                                      *vars*)))
                    (make-random-integer-form (first sizes))))
            (ret-form (make-random-integer-form (second sizes))))
       (unless (consp body) (setq body `(progn ,body)))
       `(dotimes (,var ,count ,ret-form) ,body))
397 398

     ;; loop
pfdietz's avatar
pfdietz committed
399
     (make-random-loop-form (1- size))
400

pfdietz's avatar
pfdietz committed
401
     (make-random-count-form size)
402

403
     #-(or gcl ecl armedbear)
404
     ;; load-time-value
pfdietz's avatar
pfdietz committed
405 406 407 408 409 410 411 412 413 414
     (let ((arg (let ((*flet-names* nil)
                      (*vars* nil)
                      (*random-int-form-blocks* nil)
                      (*random-int-form-catch-tags* nil)
                      (*go-tags* nil))
                  (make-random-integer-form (1- size)))))
       (rcase
        (4 `(load-time-value ,arg t))
        (2 `(load-time-value ,arg))
        (2 `(load-time-value ,arg nil))))
415

416
     ;; eval
pfdietz's avatar
pfdietz committed
417
     (make-random-integer-eval-form size)
sds's avatar
sds committed
418

419
     #-(or cmu allegro poplog)
pfdietz's avatar
pfdietz committed
420 421 422 423 424
     (destructuring-bind (s1 s2)
        (random-partition (- size 2) 2)
        `(ash ,(make-random-integer-form s1)
              (min ,(random 100)
                   ,(make-random-integer-form s2))))
sds's avatar
sds committed
425

426
     ;; binary floor, ceiling, truncate, round
pfdietz's avatar
pfdietz committed
427 428 429 430 431 432 433 434 435
     (let ((op (random-from-seq #(floor ceiling truncate round mod rem)))
           (op2 (random-from-seq #(max min))))
       (destructuring-bind (s1 s2)
          (random-partition (- size 2) 2)
          `(,op  ,(make-random-integer-form s1)
                 (,op2  ,(if (eq op2 'max)
                             (1+ (random 100))
                           (- (1+ (random 100))))
                        ,(make-random-integer-form s2)))))
sds's avatar
sds committed
436

437
     ;; Binary op
pfdietz's avatar
pfdietz committed
438
     (let* ((op (random-from-seq
pfdietz's avatar
pfdietz committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
                  '(+ - *  logand min max gcd
                      lcm
                      #-:allegro
                      logandc1
                      logandc2 logeqv logior lognand lognor
                      #-:allegro
                      logorc1
                      logorc2
                      logxor
                      ))))
        (destructuring-bind (leftsize rightsize)
            (random-partition (1- size) 2)
          (let ((e1 (make-random-integer-form leftsize))
                (e2 (make-random-integer-form rightsize)))
            `(,op ,e1 ,e2))))
454

455
     ;; boole
pfdietz's avatar
pfdietz committed
456 457 458 459 460 461 462 463 464
     (let* ((op (random-from-seq
                  #(boole-1 boole-2 boole-and boole-andc1 boole-andc2
                    boole-c1 boole-c2 boole-clr boole-eqv boole-ior boole-nand
                    boole-nor boole-orc1 boole-orc2 boole-set boole-xor))))
        (destructuring-bind (leftsize rightsize)
            (random-partition (- size 2) 2)
          (let ((e1 (make-random-integer-form leftsize))
                (e2 (make-random-integer-form rightsize)))
            `(boole ,op ,e1 ,e2))))
465

466
     ;; n-ary ops
pfdietz's avatar
pfdietz committed
467 468 469 470 471 472 473
     (let* ((op (random-from-seq #(+ - * logand min max
                                      logior values lcm gcd logxor)))
             (nmax (case op ((* lcm gcd) 4) (t (1+ (random 40)))))
             (nargs (1+ (min (random nmax) (random nmax))))
             (sizes (random-partition (1- size) nargs))
             (args (mapcar #'make-random-integer-form sizes)))
        `(,op ,@args))
474 475

     ;; expt
pfdietz's avatar
pfdietz committed
476
     `(expt ,(make-random-integer-form (1- size)) ,(random 3))
477 478

     ;; coerce
pfdietz's avatar
pfdietz committed
479
     `(coerce ,(make-random-integer-form (1- size)) 'integer)
sds's avatar
sds committed
480

481
     ;; complex (degenerate case)
pfdietz's avatar
pfdietz committed
482
     `(complex ,(make-random-integer-form (1- size)) 0)
483 484

     ;; quotient (degenerate cases)
pfdietz's avatar
pfdietz committed
485 486
     `(/ ,(make-random-integer-form (1- size)) 1)
     `(/ ,(make-random-integer-form (1- size)) -1)
487 488

     ;; tagbody
pfdietz's avatar
pfdietz committed
489
     (make-random-tagbody-and-progn size)
490

491
     ;; conditionals
pfdietz's avatar
pfdietz committed
492 493 494 495 496 497 498
     (let* ((cond-size (random (max 1 (floor size 2))))
            (then-size (random (- size cond-size)))
            (else-size (- size 1 cond-size then-size))
            (pred (make-random-pred-form cond-size))
            (then-part (make-random-integer-form then-size))
            (else-part (make-random-integer-form else-size)))
       `(if ,pred ,then-part ,else-part))
499
     #-poplog
500
      (destructuring-bind (s1 s2 s3) (random-partition (1- size) 3)
pfdietz's avatar
pfdietz committed
501 502 503 504
        `(,(random-from-seq '(deposit-field dpb))
          ,(make-random-integer-form s1)
          ,(make-random-byte-spec-form s2)
          ,(make-random-integer-form s3)))
505

506
     #-(or allegro poplog)
507
      (destructuring-bind (s1 s2) (random-partition (1- size) 2)
pfdietz's avatar
pfdietz committed
508 509 510
          `(,(random-from-seq '(ldb mask-field))
            ,(make-random-byte-spec-form s1)
            ,(make-random-integer-form s2)))
511

pfdietz's avatar
pfdietz committed
512
     (make-random-integer-binding-form size)
513 514

     ;; progv
pfdietz's avatar
pfdietz committed
515
     (make-random-integer-progv-form size)
sds's avatar
sds committed
516

pfdietz's avatar
pfdietz committed
517
     `(let () ,(make-random-integer-form (1- size)))
518

519
      (let* ((name (random-from-seq #(b1 b2 b3 b4 b5 b6 b7 b8)))
pfdietz's avatar
pfdietz committed
520 521
             (*random-int-form-blocks* (adjoin name *random-int-form-blocks*)))
        `(block ,name ,(make-random-integer-form (1- size))))
522 523

      (let* ((tag (list 'quote (random-from-seq #(ct1 ct2 ct2 ct4 ct5 ct6 ct7 ct8))))
pfdietz's avatar
pfdietz committed
524 525
             (*random-int-form-catch-tags* (cons tag *random-int-form-catch-tags*)))
        `(catch ,tag ,(make-random-integer-form (1- size))))
sds's avatar
sds committed
526

pfdietz's avatar
pfdietz committed
527 528
      ;; setq and similar
      (make-random-integer-setq-form size)
529

pfdietz's avatar
pfdietz committed
530
      (make-random-integer-case-form size)
531

532
      (if *random-int-form-blocks*
pfdietz's avatar
pfdietz committed
533 534 535 536 537
          (let ((name (random-from-seq *random-int-form-blocks*))
                (form (make-random-integer-form (1- size))))
            `(return-from ,name ,form))
        ;; No blocks -- try again
        (make-random-integer-form size))
538

539
      (if *random-int-form-catch-tags*
pfdietz's avatar
pfdietz committed
540 541 542 543 544
          (let ((tag (random-from-seq *random-int-form-catch-tags*))
                (form (make-random-integer-form (1- size))))
            `(throw ,tag ,form))
        ;; No catch tags -- try again
        (make-random-integer-form size))
545

546
      (if *random-int-form-blocks*
pfdietz's avatar
pfdietz committed
547 548 549 550 551 552 553 554
          (destructuring-bind (s1 s2 s3) (random-partition (1- size) 3)
            (let ((name (random-from-seq *random-int-form-blocks*))
                  (pred (make-random-pred-form s1))
                  (then (make-random-integer-form s2))
                  (else (make-random-integer-form s3)))
              `(if ,pred (return-from ,name ,then) ,else)))
        ;; No blocks -- try again
        (make-random-integer-form size))
555

556
     #-(or armedbear)
pfdietz's avatar
pfdietz committed
557
     (make-random-flet-form size)
558 559

      (let* ((nbits (1+ (min (random 20) (random 20))))
pfdietz's avatar
pfdietz committed
560 561 562
             (bvec (coerce (loop repeat nbits collect (random 2)) 'simple-bit-vector))
             (op (random-from-seq #(bit sbit))))
        `(,op ,bvec (min ,(1- nbits) (max 0 ,(make-random-integer-form (- size 3 nbits))))))
563 564

      (let* ((nvals (1+ (min (random 20) (random 20))))
pfdietz's avatar
pfdietz committed
565 566 567 568
             (lim (ash 1 (+ 3 (random 40))))
             (vec (coerce (loop repeat nvals collect (random lim)) 'simple-vector))
             (op (random-from-seq #(aref svref elt))))
        `(,op ,vec (min ,(1- nvals) (max 0 ,(make-random-integer-form (- size 3 nvals))))))
569 570

      (let* ((nvals (1+ (min (random 20) (random 20))))
pfdietz's avatar
pfdietz committed
571 572 573 574
             (lim (ash 1 (+ 3 (random 40))))
             (vals (loop repeat nvals collect (random lim)))
             (op 'elt))
        `(,op ',vals (min ,(1- nvals) (max 0 ,(make-random-integer-form (- size 3 nvals))))))
575 576 577

     )))

578 579 580 581
(defun make-random-aref-form (size)
  (or
   (when *vars*
     (let* ((desc (random-var-desc))
pfdietz's avatar
pfdietz committed
582 583
            (type (var-desc-type desc))
            (name (var-desc-name desc)))
584
       (cond
pfdietz's avatar
pfdietz committed
585 586 587 588 589 590 591 592 593 594 595 596
        ((null type) nil)
        ((subtypep type '(array integer (*)))
         `(aref ,name (min ,(1- (first (third type)))
                           (max 0 ,(make-random-integer-form (- size 2))))))
        ((subtypep type '(array integer (* *)))
         (destructuring-bind (s1 s2) (random-partition (max 2 (- size 2)) 2)
           `(aref ,name
                  (min ,(1- (first (third type)))
                       (max 0 ,(make-random-integer-form s1)))
                  (min ,(1- (second (third type)))
                       (max 0 ,(make-random-integer-form s2))))))
        (t nil))))
597 598
   (make-random-integer-form size)))

599 600 601 602
(defun make-random-count-form (size)
  (destructuring-bind (s1 s2)
      (random-partition (1- size) 2)
    (let ((arg1 (make-random-integer-form s1))
pfdietz's avatar
pfdietz committed
603
          (arg2-args (loop repeat s2 collect (make-random-integer))))
604
      (let ((op 'count)
pfdietz's avatar
pfdietz committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618
            (test (random-from-seq #(eql = /= < > <= >=)))
            (arg2 (rcase
                   (1 (make-array (list s2) :initial-contents arg2-args))
                   (1
                    (let* ((mask (1- (ash 1 (1+ (random 32))))))
                      (make-array (list s2)
                                  :initial-contents
                                  (mapcar #'(lambda (x) (logand x mask)) arg2-args)
                                  :element-type `(integer 0 ,mask))))
                   (1 `(quote ,arg2-args)))))
        `(,op ,arg1 ,arg2 ,@(rcase
                                    (2 nil)
                                    (1 (list :test `(quote ,test)))
                                    (1 (list :test-not `(quote ,test)))))))))
619

620 621 622
(defun make-random-integer-flet-call-form (size)
  (if *flet-names*
      (let* ((flet-entry (random-from-seq *flet-names*))
pfdietz's avatar
pfdietz committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
             (flet-name (car flet-entry))
             (flet-minargs (cadr flet-entry))
             (flet-maxargs (caddr flet-entry))
             (nargs (random-from-interval (1+ flet-maxargs) flet-minargs))
             )
        (cond
         ((> nargs 0)
          (let* ((arg-sizes (random-partition (1- size) nargs))
                 (args (mapcar #'make-random-integer-form arg-sizes)))
            (rcase
             (1 `(,flet-name ,@args))
             (1 `(multiple-value-call #',flet-name (values ,@args)))
             (1 `(funcall (function ,flet-name) ,@args))
             (1 (let ((r (random (1+ (length args)))))
                  `(apply (function ,flet-name)
                          ,@(subseq args 0 r)
                          (list ,@(subseq args r))))))))
         (t (make-random-integer-form size))))
641 642 643 644
    (make-random-integer-form size)))

(defun make-random-integer-unwind-protect-form (size)
  (let* ((op 'unwind-protect)
pfdietz's avatar
pfdietz committed
645 646 647 648 649 650 651 652 653 654 655
         (nforms (random 4))
         (sizes (random-partition (1- size) (1+ nforms)))
         (arg (make-random-integer-form (first sizes)))
         (unwind-forms
          ;; We have to be careful not to generate code that will
          ;; illegally transfer control to a dead location
          (let ((*flet-names* nil)
                (*go-tags* nil)
                (*random-int-form-blocks* nil)
                (*random-int-form-catch-tags* nil))
            (mapcar #'make-random-integer-form (rest sizes)))))
656 657 658 659
    `(,op ,arg ,@unwind-forms)))

(defun make-random-integer-eval-form (size)
  (flet ((%arg (size)
pfdietz's avatar
pfdietz committed
660 661 662 663 664 665 666 667
               (let ((*flet-names* nil)
                     (*vars* (remove-if-not #'(lambda (s)
                                                (find (var-desc-name s)
                                                      *random-special-vars*))
                                            *vars*))
                     (*random-int-form-blocks* nil)
                     (*go-tags* nil))
                 (make-random-integer-form size))))
668 669 670
    (rcase
     (2 `(eval ',(%arg (1- size))))
     (2 (let* ((nargs (1+ (random 4)))
pfdietz's avatar
pfdietz committed
671 672 673
               (sizes (random-partition (1- size) nargs))
               (args (mapcar #'%arg sizes)))
          `(eval (values ,@args))))
674 675
     )))

676 677 678 679
(defun make-random-type-for-var (var e1)
  (let (desc)
    (values
     (cond
680
      ((and (find var *random-special-vars*)
pfdietz's avatar
pfdietz committed
681
            (setq desc (find var *vars* :key #'var-desc-name)))
682 683
       (var-desc-type desc))
      (t (rcase
pfdietz's avatar
pfdietz committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
          (4 '(integer * *))
          (1 (setq e1 `(make-array nil :initial-element ,e1
                                   ,@(rcase (1 nil) (1 '(:adjustable t)))))
             '(array integer nil))
          (1 (let ((size (1+ (random 10))))
               (setq e1 `(make-array '(,size):initial-element ,e1
                                     ,@(rcase (1 nil) (1 '(:adjustable t)))))
               `(array integer (,size))))
          #|
          (1 (let ((size1 (1+ (random 10)))
                   (size2 (1+ (random 10))))
               (setq e1 `(make-array '(,size1 ,size2):initial-element ,e1
                                     ,@(rcase (1 nil) (1 '(:adjustable t)))))
               `(array integer (,size1 ,size2))))
          |#
          (1 (setq e1 `(cons ,e1 ,(make-random-integer-form 1)))
             '(cons integer integer))
          (1 (setq e1 `(cons ,(make-random-integer-form 1) ,e1))
             '(cons integer integer)))))
703 704
     e1)))

pfdietz's avatar
pfdietz committed
705 706 707 708 709 710
(defun random2 (n)
  (min (random n) (random n)))

(defun random-from-seq2 (seq)
  (elt seq (random2 (length seq))))

711 712
(defun make-random-integer-binding-form (size)
  (destructuring-bind (s1 s2) (random-partition (1- size) 2)
pfdietz's avatar
pfdietz committed
713
    (let* ((var (random-from-seq2 (rcase
pfdietz's avatar
pfdietz committed
714 715 716 717 718 719 720 721 722 723 724 725
                                   (2 #(v1 v2 v3 v4 v5 v6 v7 v8 v9 v10))
                                   #-ecl (2 *random-special-vars*)
                                   )))
           (e1 (make-random-integer-form s1))
           (type (multiple-value-bind (type2 e)
                     (make-random-type-for-var var e1)
                   (setq e1 e)
                   type2))
           (e2 (let ((*vars* (cons (make-var-desc :name var :type type)
                                   *vars*)))
                 (make-random-integer-form s2)))
           (op (random-from-seq #(let let*))))
726 727
      ;; for now, avoid shadowing
      (if (member var *vars* :key #'var-desc-name)
pfdietz's avatar
pfdietz committed
728 729 730 731 732 733 734
          (make-random-integer-form size)
        (rcase
         (8 `(,op ((,var ,e1))
                  ,@(rcase (1 `((declare (dynamic-extent ,var))))
                           (3 nil))
                  ,e2))
         (2 `(multiple-value-bind (,var) ,e1 ,e2)))))))
735 736 737

(defun make-random-integer-progv-form (size)
  (let* ((num-vars (random 4))
pfdietz's avatar
pfdietz committed
738 739
         (possible-vars *random-special-vars*)
         (vars nil))
740
    (loop repeat num-vars
pfdietz's avatar
pfdietz committed
741 742 743
          do (loop for r = (elt possible-vars (random (length possible-vars)))
                   while (member r vars)
                   finally (push r vars)))
744
    (setq vars (remove-if #'(lambda (var) (let ((desc (find var *vars* :key #'var-desc-name)))
pfdietz's avatar
pfdietz committed
745 746 747
                                            (and desc (not (subtypep (var-desc-type desc) 'integer)))))
                          vars)
          num-vars (length vars))
748
    (if (null vars)
pfdietz's avatar
pfdietz committed
749
        `(progv nil nil ,(make-random-integer-form (1- size)))
750
      (destructuring-bind (s1 s2) (random-partition (1- size) 2)
pfdietz's avatar
pfdietz committed
751 752 753 754 755 756 757
        (let* ((var-sizes (random-partition s1 num-vars))
               (var-forms (mapcar #'make-random-integer-form var-sizes))
               (*vars* (append (loop for v in vars collect
                                     (make-var-desc :name v :type '(integer * *)))
                               *vars*))
               (body-form (make-random-integer-form s2)))
          `(progv ',vars (list ,@var-forms) ,body-form))))))
758

759
(defun make-random-integer-mapping-form (size)
760 761
  ;; reduce
  (let ((keyargs nil)
pfdietz's avatar
pfdietz committed
762 763
        (nargs (1+ (random (min 10 (max 1 size)))))
        (sequence-op (random-from-seq '(vector list))))
764 765 766 767
    (when (coin 2) (setq keyargs '(:from-end t)))
    (cond
     ((coin 2)
      (let ((start (random nargs)))
pfdietz's avatar
pfdietz committed
768 769 770 771
        (setq keyargs `(:start ,start ,@keyargs))
        (when (coin 2)
          (let ((end (+ start 1 (random (- nargs start)))))
            (setq keyargs `(:end ,end ,@keyargs))))))
772 773
     (t
      (when (coin 2)
pfdietz's avatar
pfdietz committed
774 775
        (let ((end (1+ (random nargs))))
          (setq keyargs `(:end ,end ,@keyargs))))))
776 777 778
    (rcase
     (1
      (let ((sizes (random-partition (1- size) nargs))
pfdietz's avatar
pfdietz committed
779 780 781 782 783 784
            (op (random-from-seq #(+ - * logand logxor logior max min))))
        `(reduce ,(rcase (1 `(function ,op))
                         (1 `(quote ,op)))
                 (,sequence-op
                  ,@(mapcar #'make-random-integer-form sizes))
                 ,@keyargs)))
785
     #-(or armedbear)
sds's avatar
sds committed
786
     (1
787
      (destructuring-bind (size1 size2) (random-partition (1- size) 2)
pfdietz's avatar
pfdietz committed
788 789 790 791 792 793 794 795 796 797 798 799 800
        (let* ((vars '(lmv1 lmv2 lmv3 lmv4 lmv5 lmv6))
               (var1 (random-from-seq vars))
               (var2 (random-from-seq (remove var1 vars)))
               (form (let ((*vars* (list*
                                    (make-var-desc :name var1 :type '(integer * *))
                                    (make-var-desc :name var2 :type '(integer * *))
                                    *vars*)))
                       (make-random-integer-form size1)))
               (sizes (random-partition size2 nargs))
               (args (mapcar #'make-random-integer-form sizes)))
          `(reduce (function (lambda (,var1 ,var2) ,form))
                   (,sequence-op ,@args)
                   ,@keyargs)))))))
801

802 803 804
(defun make-random-integer-setq-form (size)
  (if *vars*
      (let* ((vdesc (random-from-seq *vars*))
pfdietz's avatar
pfdietz committed
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
             (var (var-desc-name vdesc))
             (type (var-desc-type vdesc))
             (op (random-from-seq #(setq setf shiftf))))
        (cond
         ((subtypep '(integer * *) type)
          (assert (not (member var '(lv1 lv2 lv3 lv4 lv5 lv6 lv7 lv8))))
          (rcase
           (1 (when (find var *random-special-vars*)
                (setq op (random-from-seq #(setf shiftf))
                      var `(symbol-value ',var))))
           (1 (setq op 'multiple-value-setq)
              (setq var (list var)))
           (5 (setf op (random-from-seq #(setq setf shiftf incf decf)))))
          `(,op ,var ,(make-random-integer-form (1- size))))
         ((and (consp type)
               (eq (car type) 'integer)
               (integerp (second type))
               (integerp (third type)))
          (assert (not (member var '(lv1 lv2 lv3 lv4 lv5 lv6 lv7 lv8))))
          (rcase
           (1 (when (find var *random-special-vars*)
                (setq op (random-from-seq #(setf shiftf))
                      var `(symbol-value ',var))))
           (1 (setq op 'multiple-value-setq)
              (setq var (list var)))
           (5 nil))
          `(,op ,var ,(random-from-interval (1+ (third type)) (second type))))
         ((and type (is-zero-rank-integer-array-type type)) ; (subtypep type '(array integer nil))
          (assert (not (member var '(lv1 lv2 lv3 lv4 lv5 lv6 lv7 lv8))))
          (when (eq op 'setq)
            (setq op (random-from-seq #(setf shiftf))))
          `(,op (aref ,var) ,(make-random-integer-form (- size 2))))
         ((and type (subtypep type '(array integer (*))))
          (when (eq op 'setq)
            (setq op (random-from-seq #(setf shiftf))))
          (destructuring-bind (s1 s2) (random-partition (max 2 (- size 2)) 2)
            `(,op (aref ,var (min ,(1- (first (third type)))
                                  (max 0
                                       ,(make-random-integer-form s1))))
                  ,(make-random-integer-form s2))))
         ((and type (subtypep type '(array integer (* *))))
          (when (eq op 'setq)
            (setq op (random-from-seq #(setf shiftf))))
          (destructuring-bind (s1 s2 s3) (random-partition (max 3 (- size 3)) 3)
            `(,op (aref ,var
                        (min ,(1- (first (third type)))
                             (max 0
                                  ,(make-random-integer-form s1)))
                        (min ,(1- (second (third type)))
                             (max 0
                                  ,(make-random-integer-form s2))))
                  ,(make-random-integer-form s3))))
         ;; Abort -- can't assign
         (t (make-random-integer-form size))))
859 860 861
    (make-random-integer-form size)))


862
(defun make-random-integer-case-form (size)
863 864
  (let ((ncases (1+ (random 10))))
    (if (< (+ size size) (+ ncases 2))
pfdietz's avatar
pfdietz committed
865 866
        ;; Too small, give up
        (make-random-integer-form size)
867
      (let* ((sizes (random-partition (1- size) (+ ncases 2)))
pfdietz's avatar
pfdietz committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
             (bound (ash 1 (+ 2 (random 16))))
             (lower-bound (if (coin 3) 0 (- bound)))
             (upper-bound (if (and (< lower-bound 0) (coin 3))
                              1
                            (1+ bound)))
             (cases
              (loop
               for case-size in (cddr sizes)
               for vals = (loop repeat (1+ (min (random 10) (random 10)))
                                collect (random-from-interval
                                         upper-bound lower-bound))
               for result = (make-random-integer-form case-size)
               repeat ncases
               collect `(,vals ,result)))
             (expr (make-random-integer-form (first sizes))))
        `(case ,expr
           ,@cases
           (t ,(make-random-integer-form (second sizes))))))))
886

887
(defun make-random-flet-form (size)
888 889
  "Generate random flet, labels forms, for now with no arguments
   and a single binding per form."
890
  (let ((fname (random-from-seq #(%f1 %f2 %f3 %f4 %f5 %f6 %f7 %f8 %f9 %f10
pfdietz's avatar
pfdietz committed
891
                                  %f11 %f12 %f13 %f14 %f15 %f16 %f17 %f18))))
892
    (if (assoc fname *flet-names*)
pfdietz's avatar
pfdietz committed
893 894
        ;; Fail if the name is in use
        (make-random-integer-form size)
895
      (let* ((op (random-from-seq #(flet labels)))
pfdietz's avatar
pfdietz committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
             (minargs (random 4))
             (maxargs #+:allegro minargs
                      #-:allegro
                      (rcase
                       (1 minargs)
                       (1 (+ minargs (random 4)))))
             (keyarg-p (coin 2))
             (keyarg-n (if keyarg-p (random 3) 0))
             (arg-names (loop for i from 1 to maxargs
                              collect (fn-arg-name fname i)))
             (key-arg-names (loop for i from 1 to keyarg-n
                                  collect (intern (format nil "KEY~A" i)
                                                  (find-package "CL-TEST"))))
             (allow-other-keys (and keyarg-p (coin 3)))
             )
        (let* ((sizes (random-partition (1- size) (+ 2 keyarg-n (- maxargs minargs))))
               (s1 (car sizes))
               (s2 (cadr sizes))
               (opt-sizes (cddr sizes)))
          (let* ((form1
                  ;; Allow return-from of the flet/labels function
                  (let ((*random-int-form-blocks*
                         (cons fname *random-int-form-blocks*))
                        (*vars* (nconc (loop for var in (append arg-names key-arg-names)
                                             collect (make-var-desc :name var
                                                                    :type '(integer * *)))
                                       *vars*)))
                    (make-random-integer-form s1)))
                 (form2 (let ((*flet-names* (cons (list fname minargs maxargs keyarg-p)
                                                  *flet-names*)))
                          (make-random-integer-form s2)))
                 (opt-forms (mapcar #'make-random-integer-form opt-sizes)
                            ))
            (if opt-forms
                `(,op ((,fname (,@(subseq arg-names 0 minargs)
                                  &optional
                                  ,@(mapcar #'list
                                            (subseq arg-names minargs)
                                            opt-forms)
                                  ,@(when keyarg-p
                                      (append '(&key)
                                              (mapcar #'list
                                                      key-arg-names
                                                      (subseq opt-forms (- maxargs minargs)))
                                              (when allow-other-keys '(&allow-other-keys))
                                              )))
                               ,form1))
                      ,form2)
              `(,op ((,fname (,@arg-names
                              ,@(when keyarg-p
                                  (append '(&key)
                                          (mapcar #'list
                                                  key-arg-names
                                                  opt-forms )
                                          (when allow-other-keys '(&allow-other-keys))
                                          )))
                             ,form1))
                    ,form2))))))))
954

955 956
(defun make-random-tagbody (size)
  (let* ((num-forms (random 6))
pfdietz's avatar
pfdietz committed
957
         (tags nil))
958
    (loop for i below num-forms
pfdietz's avatar
pfdietz committed
959 960 961 962 963 964
          do (loop for tag = (rcase
                              #-allegro (1 (random 8))
                              (1 (random-from-seq #(tag1 tag2 tag3 tag4
                                                         tag5 tag6 tag7 tag8))))
                   while (member tag tags)
                   finally (push tag tags)))
965 966
    (assert (= (length (remove-duplicates tags)) (length tags)))
    (let* ((*go-tags* (set-difference *go-tags* tags))
pfdietz's avatar
pfdietz committed
967 968 969 970 971 972 973
           (sizes (if (> num-forms 0) (random-partition (1- size) num-forms) nil))
           (forms
            (loop for tag-list on tags
                  for i below num-forms
                  for size in sizes
                  collect (let ((*go-tags* (append tag-list *go-tags*)))
                            (make-random-integer-form size)))))
974
      `(tagbody ,@(loop for tag in tags
pfdietz's avatar
pfdietz committed
975 976 977
                        for form in forms
                        when (atom form) do (setq form `(progn ,form))
                        append `(,form ,tag))))))
978 979 980

(defun make-random-tagbody-and-progn (size)
  (let* ((final-size (random (max 1 (floor size 5))))
pfdietz's avatar
pfdietz committed
981
         (tagbody-size (- size final-size)))
982
    (let ((final-form (make-random-integer-form final-size))
pfdietz's avatar
pfdietz committed
983
          (tagbody-form (make-random-tagbody tagbody-size)))
984
      `(progn ,tagbody-form ,final-form))))
985

986
(defun make-random-pred-form (size)
987
  "Make a random form whose value is to be used as a generalized boolean."
988
  (if (<= size 1)
989
      (rcase
pfdietz's avatar
pfdietz committed
990 991 992 993 994
        (1 (if (coin) t nil))
        (2
         `(,(random-from-seq '(< <= = > >= /= eql equal))
           ,(make-random-integer-form size)
           ,(make-random-integer-form size))))
995 996
    (rcase
      (1 (if (coin) t nil))
997
      (3 `(not ,(make-random-pred-form (1- size))))
998
      (12 (destructuring-bind (leftsize rightsize)
pfdietz's avatar
pfdietz committed
999 1000 1001 1002
             (random-partition (1- size) 2)
           `(,(random-from-seq '(and or))
             ,(make-random-pred-form leftsize)
             ,(make-random-pred-form rightsize))))
1003
      (1 (let* ((nsizes (+ 1 (random 3)))
pfdietz's avatar
pfdietz committed
1004 1005 1006 1007
                (sizes (random-partition (1- size) nsizes)))
           `(,(random-from-seq (if (= nsizes 2) #(< <= > >= = /= eql equal)
                                 #(< <= > >= = /=)))
             ,@(mapcar #'make-random-integer-form sizes))))
1008
      (3 (let* ((cond-size (random (max 1 (floor size 2))))
pfdietz's avatar
pfdietz committed
1009 1010 1011 1012 1013 1014
                (then-size (random (- size cond-size)))
                (else-size (- size 1 cond-size then-size))
                (pred (make-random-pred-form cond-size))
                (then-part (make-random-pred-form then-size))
                (else-part (make-random-pred-form else-size)))
           `(if ,pred ,then-part ,else-part)))
1015
      #-poplog
1016
      (1 (destructuring-bind (s1 s2)
pfdietz's avatar
pfdietz committed
1017 1018 1019
             (random-partition (1- size) 2)
           `(ldb-test ,(make-random-byte-spec-form s1)
                      ,(make-random-integer-form s2))))
1020
      (2 (let ((form (make-random-integer-form (1- size)))
pfdietz's avatar
pfdietz committed
1021 1022
               (op (random-from-seq #(evenp oddp minusp plusp zerop))))
           `(,op ,form)))
1023
      (2 (destructuring-bind (s1 s2)
pfdietz's avatar
pfdietz committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
             (random-partition (1- size) 2)
           (let ((arg1 (make-random-integer-form s1))
                 (arg2-args (loop repeat s2 collect (make-random-integer))))
             (let ((op (random-from-seq #(find position)))
                   (test (random-from-seq #(eql = /= < > <= >=)))
                   (arg2 (rcase
                          (1 (make-array (list s2) :initial-contents arg2-args))
                          (1
                           (let* ((mask (1- (ash 1 (1+ (random 32))))))
                             (make-array (list s2)
                                         :initial-contents
                                         (mapcar #'(lambda (x) (logand x mask)) arg2-args)
                                        :element-type `(integer 0 ,mask))))
                          (1 `(quote ,arg2-args)))))
               `(,op ,arg1 ,arg2 ,@(rcase
                                    (2 nil)
                                    (1 (list :test `(quote ,test)))
                                    (1 (list :test-not `(quote ,test)))))))))
sds's avatar
sds committed
1042

1043
      (1 (let ((index (random (1+ (random *maximum-random-int-bits*))))
pfdietz's avatar
pfdietz committed
1044 1045
               (form (make-random-integer-form (1- size))))
           `(logbitp ,index ,form)))
1046 1047
      (1 ;; typep form
       (let ((subform (make-random-integer-form (- size 2)))
pfdietz's avatar
pfdietz committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
             (type
              (rcase
               (1 `(real ,@(make-random-integer-range)))
               (1 `(rational ,@(make-random-integer-range)))
               (1 `(rational ,(+ 1/2 (make-random-integer))))
               (1 `(rational * ,(+ 1/2 (make-random-integer))))
               (1 `(integer ,@(make-random-integer-range)))
               (1 `(integer ,(make-random-integer)))
               (1 `(integer * ,(make-random-integer)))
               (1 'fixnum)
               (1 'bignum)
               (1 `(integer)))))
         `(typep ,subform ',type)))
1061 1062
      )))

1063 1064 1065 1066
(defun make-random-loop-form (size)
  (if (<= size 2)
      (make-random-integer-form size)
    (let* ((var (random-from-seq #(lv1 lv2 lv3 lv4)))
pfdietz's avatar
pfdietz committed
1067 1068 1069
           (count (random 4))
           (*vars* (cons (make-var-desc :name var :type nil)
                         *vars*)))
1070 1071 1072 1073 1074
      (rcase
       (1 `(loop for ,var below ,count count ,(make-random-pred-form (- size 2))))
       (1 `(loop for ,var below ,count sum ,(make-random-integer-form (- size 2))))
       ))))

1075 1076
(defun make-random-byte-spec-form (size)
  (declare (ignore size))
1077
  (let* ((pform (random 33))
pfdietz's avatar
pfdietz committed
1078
         (sform (1+ (random 33))))
1079
    `(byte ,sform ,pform)))
1080

1081 1082 1083 1084 1085 1086
(defgeneric make-random-element-of-type (type)
  (:documentation "Create a random element of a lisp type."))

(defgeneric make-random-element-of-compound-type (type-op type-args)
  (:documentation "Create a random element of type `(,TYPE-OP ,@TYPE-ARGS)")
  (:method ((type-op (eql 'or)) type-args)
sds's avatar
sds committed
1087 1088
           (assert type-args)
           (make-random-element-of-type (random-from-seq type-args)))
1089
  (:method ((type-op (eql 'and)) type-args)
sds's avatar
sds committed
1090 1091 1092 1093 1094 1095 1096
           (assert type-args)
           (loop for x = (make-random-element-of-type (car type-args))
             repeat 100
             when (typep x (cons 'and (cdr type-args)))
             return x
             finally (error "Cannot generate random element of ~A"
                            (cons type-op type-args))))
1097
  (:method ((type-op (eql 'not)) type-args)
sds's avatar
sds committed
1098 1099
           (assert (eql (length type-args) 1))
           (make-random-element-of-type `(and t (not ,(car type-args)))))
1100
  (:method ((type-op (eql 'integer)) type-args)
sds's avatar
sds committed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
           (let ((lo (let ((lo (car type-args)))
                       (cond
                        ((consp lo) (1+ (car lo)))
                        ((eq lo nil) '*)
                        (t lo))))
                 (hi (let ((hi (cadr type-args)))
                       (cond
                        ((consp hi) (1- (car hi)))
                        ((eq hi nil) '*)
                        (t hi)))))
             (if (eq lo '*)
                 (if (eq hi '*)
                     (let ((x (ash 1 (random *maximum-random-int-bits*))))
                       (random-from-interval x (- x)))
                   (random-from-interval (1+ hi)
                                         (- hi (random (ash 1 *maximum-random-int-bits*)))))

               (if (eq hi '*)
                   (random-from-interval (+ lo (random (ash 1 *maximum-random-int-bits*)) 1)
                                         lo)
                 ;; May generalize the next case to increase odds
                 ;; of certain integers (near 0, near endpoints, near
                 ;; powers of 2...)
                 (random-from-interval (1+ hi) lo)))))
1125
  (:method ((type-op (eql 'rational)) type-args)
sds's avatar
sds committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
           (let ((type (cons type-op type-args)))
             (or
              (let ((r (make-random-element-of-type 'rational)))
                (and (typep r type) r))
              (let ((lo (car type-args))
                    (hi (cadr type-args))
                    lo= hi=)
                (cond
                 ((consp lo) nil)
                 ((member lo '(* nil))
                  (setq lo nil)
                  (setq lo= nil))
                 (t
                  (assert (typep lo 'rational))
                  (setq lo= t)))
                (cond
                 ((consp hi) nil)
                 ((member hi '(* nil))
                  (setq hi nil)
                  (setq hi= nil))
                 (t
                  (assert (typep hi 'rational))
                  (setq hi= t)))
                (assert (or (null lo) (null hi) (<= lo hi)))
                (assert (or (null lo) (null hi) (< lo hi) (and lo= hi=)))
                (cond
                 ((null lo)
                  (cond
                   ((null hi) (make-random-rational))
                   (hi= (- hi (make-random-nonnegative-rational)))
                   (t (- hi (make-random-positive-rational)))))
                 ((null hi)
                  (cond
                   (lo= (+ lo (make-random-nonnegative-rational)))
                   (t (+ lo (make-random-positive-rational)))))
                 (t
                  (+ lo (make-random-bounded-rational (- hi lo) lo= hi=))))))))

1164
  (:method ((type-op (eql 'ratio)) type-args)
sds's avatar
sds committed
1165 1166 1167 1168 1169 1170
           (let ((r 0))
             (loop
              do (setq r (make-random-element-of-compound-type 'rational type-args))
              while (integerp r))
             r))

1171
  (:method ((type-op (eql 'real)) type-args)
sds's avatar
sds committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
           (rcase
            (1 (let ((lo (and (numberp (car type-args))
                              (rational (car type-args))))
                     (hi (and (numberp (cadr type-args))
                              (rational (cadr type-args)))))
                 (make-random-element-of-compound-type 'rational
                                                       `(,(or lo '*)
                                                         ,(or hi '*)))))
            (1 (make-random-element-of-compound-type 'float
                                                     `(,(or (car type-args) '*)
                                                       ,(or (cadr type-args) '*))))))

1184
  (:method ((type-op (eql 'float)) type-args)
sds's avatar
sds committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
           (let* ((new-type-op (random-from-seq #(single-float double-float long-float short-float)))
                  (lo (car type-args))
                  (hi (cadr type-args))
                  (most-neg (most-negative-float new-type-op))
                  (most-pos (most-positive-float new-type-op)))
             (cond
              ((or (and (realp lo) (< lo most-neg))
                   (and (realp hi) (> hi most-pos)))
               ;; try again
               (make-random-element-of-compound-type type-op type-args))
              (t
               (when (and (realp lo) (not (typep lo new-type-op)))
                 (cond
                  ((< lo most-neg) (setq lo '*))
                  (t (setq lo (coerce lo new-type-op)))))
               (when (and (realp hi) (not (typep hi new-type-op)))
                 (cond
                  ((> hi most-pos) (setq hi '*))
                  (t (setq hi (coerce hi new-type-op)))))
               (make-random-element-of-compound-type new-type-op `(,(or lo '*) ,(or hi '*)))))))

1206
  (:method ((type-op (eql 'short-float)) type-args)
sds's avatar
sds committed
1207 1208
           (assert (<= (length type-args) 2))
           (apply #'make-random-element-of-float-type type-op type-args))
1209
  (:method ((type-op (eql 'single-float)) type-args)
sds's avatar
sds committed
1210 1211
           (assert (<= (length type-args) 2))
           (apply #'make-random-element-of-float-type type-op type-args))
1212
  (:method ((type-op (eql 'double-float)) type-args)
sds's avatar
sds committed
1213 1214
           (assert (<= (length type-args) 2))
           (apply #'make-random-element-of-float-type type-op type-args))
1215
  (:method ((type-op (eql 'long-float)) type-args)
sds's avatar
sds committed
1216 1217 1218
           (assert (<= (length type-args) 2))
           (apply #'make-random-element-of-float-type type-op type-args))

1219
  (:method ((type-op (eql 'mod)) type-args)
sds's avatar
sds committed
1220 1221 1222 1223 1224
           (let ((modulus (second type-args)))
             (assert (integerp modulus))
             (assert (plusp modulus))
             (make-random-element-of-compound-type 'integer `(0 (,modulus)))))

1225
  (:method ((type-op (eql 'unsigned-byte)) type-args)
sds's avatar
sds committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
           (assert (<= (length type-args) 1))
           (if (null type-args)
               (make-random-element-of-type '(integer 0 *))
             (let ((bits (first type-args)))
               (if (eq bits '*)
                   (make-random-element-of-type '(integer 0 *))
                 (progn
                   (assert (and (integerp bits) (>= bits 1)))
                   (make-random-element-of-type
                    `(integer 0 ,(1- (ash 1 bits)))))))))

1237
  (:method ((type-op (eql 'signed-byte)) type-args)
sds's avatar
sds committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
           (assert (<= (length type-args) 1))
           (if (null type-args)
               (make-random-element-of-type 'integer)
             (let ((bits (car type-args)))
               (if (eq bits'*)
                   (make-random-element-of-type 'integer)
                 (progn
                   (assert (and (integerp bits) (>= bits 1)))
                   (make-random-element-of-type
                    `(integer ,(- (ash 1 (1- bits))) ,(1- (ash 1 (1- bits))))))))))
1248 1249

  (:method ((type-op (eql 'eql)) type-args)
sds's avatar
sds committed
1250 1251
           (assert (= (length type-args) 1))
           (car type-args))
1252 1253

  (:method ((type-op (eql 'member)) type-args)
sds's avatar
sds committed
1254 1255 1256
           (assert type-args)
           (random-from-seq type-args))

1257
  (:method ((type-op (eql 'vector)) type-args)
sds's avatar
sds committed
1258 1259 1260 1261 1262
           (assert (<= (length type-args) 2))
           (let ((etype-spec (if type-args (car type-args) '*))
                 (size-spec (if (cdr type-args) (cadr type-args) '*)))
             (make-random-vector etype-spec size-spec)))

1263
  (:method ((type-op (eql 'aimple-vector)) type-args)
sds's avatar
sds committed
1264 1265 1266 1267
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-vector t size-spec :simple t)))

1268
  (:method ((type-op (eql 'array)) type-args)
sds's avatar
sds committed
1269 1270 1271 1272 1273
           (assert (<= (length type-args) 2))
           (let ((etype-spec (if type-args (car type-args) '*))
                 (size-spec (if (cdr type-args) (cadr type-args) '*)))
             (make-random-array etype-spec size-spec)))

1274
  (:method ((type-op (eql 'simple-array)) type-args)
sds's avatar
sds committed
1275 1276 1277 1278
           (assert (<= (length type-args) 2))
           (let ((etype-spec (if type-args (car type-args) '*))
                 (size-spec (if (cdr type-args) (cadr type-args) '*)))
             (make-random-array etype-spec size-spec :simple t)))
1279 1280

  (:method ((type-op (eql 'string)) type-args)
sds's avatar
sds committed
1281 1282 1283
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-string size-spec)))
1284 1285

  (:method ((type-op (eql 'simple-string)) type-args)
sds's avatar
sds committed
1286 1287 1288 1289
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-string size-spec :simple t)))

1290
  (:method ((type-op (eql 'base-string)) type-args)
sds's avatar
sds committed
1291 1292 1293 1294
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-vector 'base-char size-spec)))

1295
  (:method ((type-op (eql 'simple-base-string)) type-args)
sds's avatar
sds committed
1296 1297 1298 1299
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-vector 'base-char size-spec :simple t)))

1300
  (:method ((type-op (eql 'bit-vector)) type-args)
sds's avatar
sds committed
1301 1302 1303 1304
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-vector 'bit size-spec)))

1305
  (:method ((type-op (eql 'simple-bit-vector)) type-args)
sds's avatar
sds committed
1306 1307 1308 1309
           (assert (<= (length type-args) 1))
           (let ((size-spec (if type-args (car type-args) '*)))
             (make-random-vector 'bit size-spec :simple t)))

1310
  (:method ((type-op (eql 'cons)) type-args)
sds's avatar
sds committed
1311 1312 1313 1314
           (assert (<= (length type-args) 2))
           (cons (make-random-element-of-type (if type-args (car type-args) t))
                 (make-random-element-of-type (if (cdr type-args) (cadr type-args) t))))

1315
  (:method ((type-op (eql 'complex)) type-args)
sds's avatar
sds committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
           (cond
            ((null type-args)
             (make-random-element-of-type 'complex))
            (t
             (assert (null (cdr type-args)))
             (let ((etype (car type-args)))
               (loop for v1 = (make-random-element-of-type etype)
                     for v2 = (make-random-element-of-type etype)
                     for c = (complex v1 v2)
                     when (typep c (cons 'complex type-args))
                     return c)))))
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  )

(defmethod make-random-element-of-type ((type cons))
  (make-random-element-of-compound-type (car type) (cdr type)))

(defun make-random-element-of-float-type (type-op &optional lo hi)
  (let (lo= hi=)
    (cond
     ((consp lo) nil)
     ((member lo '(* nil))
      (setq lo (most-negative-float type-op))
      (setq lo= t))
     (t
      (assert (typep lo type-op))
      (setq lo= t)))
    (cond
     ((consp hi) nil)
     ((member hi '(* nil))
      (setq hi (most-positive-float type-op))
      (setq hi= t))
     (t
      (assert (typep hi type-op))
      (setq hi= t)))
    (assert (<= lo hi))
    (assert (or (< lo hi) (and lo= hi=)))
    (let ((limit 100000))
      (cond
       ((or (<= hi 0)
sds's avatar
sds committed
1355 1356 1357 1358
            (>= lo 0)
            (and (<= (- limit) hi limit) (<= (- limit) lo limit)))
        (loop for x = (+ (random (- hi lo)) lo)
              do (when (or lo= (/= x lo)) (return x))))
1359
       (t
sds's avatar
sds committed
1360 1361 1362 1363
        (rcase
         (1 (random (min hi (float limit hi))))
         (1 (- (random (min (float limit lo) (- lo)))))))))))

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
#|
(defmethod make-random-element-of-type ((type cons))
  (let ((type-op (first type)))
    (ecase type-op
      (or
       (assert (cdr type))
       (make-random-element-of-type (random-from-seq (cdr type))))
      (and
       (assert (cdr type))
       (loop for x = (make-random-element-of-type (cadr type))
sds's avatar
sds committed
1374 1375 1376 1377
             repeat 100
             when (typep x (cons 'and (cddr type)))
             return x
             finally (error "Cannot generate random element of ~A" type)))
1378 1379 1380 1381 1382 1383
      (not
       (assert (cdr type))
       (assert (not (cddr type)))
       (make-random-element-of-type `(and t ,type)))
      (integer
       (let ((lo (let ((lo (cadr type)))
sds's avatar
sds committed
1384 1385 1386 1387 1388 1389 1390 1391 1392
                   (cond
                    ((consp lo) (1+ (car lo)))
                    ((eq lo nil) '*)
                    (t lo))))
             (hi (let ((hi (caddr type)))
                   (cond
                    ((consp hi) (1- (car hi)))
                    ((eq hi nil) '*)
                    (t hi)))))
pfdietz's avatar
pfdietz committed
1393 1394 1395 1396 1397 1398
         (if (eq lo '*)
             (if (eq hi '*)
                 (let ((x (ash 1 (random *maximum-random-int-bits*))))
                   (random-from-interval x (- x)))
               (random-from-interval (1+ hi)
                                     (- hi (random (ash 1 *maximum-random-int-bits*)))))
sds's avatar
sds committed
1399

pfdietz's avatar
pfdietz committed
1400 1401 1402 1403 1404 1405 1406
           (if (eq hi '*)
               (random-from-interval (+ lo (random (ash 1 *maximum-random-int-bits*)) 1)
                                     lo)
             ;; May generalize the next case to increase odds
             ;; of certain integers (near 0, near endpoints, near
             ;; powers of 2...)
             (random-from-interval (1+ hi) lo)))))
sds's avatar
sds committed
1407

1408 1409
      (rational
       (or
sds's avatar
sds committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        (let ((r (make-random-element-of-type 'rational)))
          (and (typep r type) r))
        (let ((lo (cadr type))
              (hi (caddr type))
              lo= hi=)
          (cond
           ((consp lo) nil)
           ((member lo '(* nil))
            (setq lo nil)
            (setq lo= nil))
           (t
            (assert (typep lo 'rational))
            (setq lo= t)))
          (cond
           ((consp hi) nil)
           ((member hi '(* nil))
            (setq hi nil)
            (setq hi= nil))
           (t
            (assert (typep hi 'rational))
            (setq hi= t)))
          (assert (or (null lo) (null hi) (<= lo hi)))
          (assert (or (null lo) (null hi) (< lo hi) (and lo= hi=)))
          (cond
           ((null lo)
            (cond
             ((null hi) (make-random-rational))
             (hi= (- hi (make-random-nonnegative-rational)))
             (t (- hi (make-random-positive-rational)))))
           ((null hi)
            (cond
             (lo= (+ lo (make-random-nonnegative-rational)))
             (t (+ lo (make-random-positive-rational)))))
           (t
            (+ lo (make-random-bounded-rational (- hi lo) lo= hi=)))))))

1446 1447
      (ratio
       (let ((r 0))
sds's avatar
sds committed
1448 1449 1450 1451 1452
         (loop
          do (setq r (make-random-element-of-type `(rational ,@(cdr type))))
          while (integerp r))
         r))

1453 1454
      (real
       (rcase
sds's avatar
sds committed
1455 1456 1457 1458 1459 1460 1461 1462 1463
        (1 (let ((lo (and (numberp (cadr type))
                          (rational (cadr type))))
                 (hi (and (numberp (caddr type))
                          (rational (caddr type)))))
             (make-random-element-of-type `(rational ,(or lo '*)
                                                     ,(or hi '*)))))
        (1 (make-random-element-of-type `(float ,(or (cadr type) '*)
                                                ,(or (caddr type) '*))))))

1464 1465
      ((float)
       (let* ((new-type-op (random-from-seq #(single-float double-float
sds's avatar
sds committed
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
                                                           long-float short-float)))
              (lo (cadr type))
              (hi (caddr type))
              (most-neg (most-negative-float new-type-op))
              (most-pos (most-positive-float new-type-op)))
         (cond
          ((or (and (realp lo) (< lo most-neg))
               (and (realp hi) (> hi most-pos)))
           ;; try again
           (make-random-element-of-type type))
          (t
           (when (and (realp lo) (not (typep lo new-type-op)))
             (cond
              ((< lo most-neg) (setq lo '*))
              (t (setq lo (coerce lo new-type-op)))))
           (when (and (realp hi) (not (typep hi new-type-op)))
             (cond
              ((> hi most-pos) (setq hi '*))
              (t (setq hi (coerce hi new-type-op)))))
           (make-random-element-of-type
            `(,new-type-op ,(or lo '*) ,(or hi '*)))))))

1488 1489
      ((single-float double-float long-float short-float)
       (let ((lo (cadr type))
sds's avatar
sds committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
             (hi (caddr type))
             lo= hi=)
         (cond
          ((consp lo) nil)
          ((member lo '(* nil))
           (setq lo (most-negative-float type-op))
           (setq lo= t))
          (t
           (assert (typep lo type-op))
           (setq lo= t)))
         (cond
          ((consp hi) nil)
          ((member hi '(* nil))
           (setq hi (most-positive-float type-op))
           (setq hi= t))
          (t
           (assert (typep hi type-op))
           (setq hi= t)))
         (assert (<= lo hi))
         (assert (or (< lo hi) (and lo= hi=)))
         (let ((limit 100000))
           (cond
            ((or (<= hi 0)
                 (>= lo 0)
                 (and (<= (- limit) hi limit) (<= (- limit) lo limit)))
             (loop for x = (+ (random (- hi lo)) lo)
                   do (when (or lo= (/= x lo)) (return x))))
            (t
             (rcase
              (1 (random (min hi (float limit hi))))
              (1 (- (random (min (float limit lo) (- lo)))))))))))

1522 1523
      (mod
       (let ((modulus (second type)))
sds's avatar
sds committed
1524 1525 1526
         (assert (and (integerp modulus)
                      (plusp modulus)))
         (make-random-element-of-type `(integer 0 (,modulus)))))
1527 1528
      (unsigned-byte
       (if (null (cdr type))
pfdietz's avatar
pfdietz committed
1529
           (make-random-element-of-type '(integer 0 *))
sds's avatar
sds committed
1530 1531 1532 1533 1534 1535 1536
         (let ((bits (second type)))
           (if (eq bits'*)
               (make-random-element-of-type '(integer 0 *))
             (progn
               (assert (and (integerp bits) (>= bits 1)))
               (make-random-element-of-type
                `(integer 0 ,(1- (ash 1 bits)))))))))
1537 1538
      (signed-byte
       (if (null (cdr type))
pfdietz's avatar
pfdietz committed
1539
           (make-random-element-of-type 'integer)
sds's avatar
sds committed
1540 1541 1542 1543 1544 1545 1546
         (let ((bits (second type)))
           (if (eq bits'*)
               (make-random-element-of-type 'integer)
             (progn
               (assert (and (integerp bits) (>= bits 1)))
               (make-random-element-of-type
                `(integer ,(- (ash 1 (1- bits))) ,(1- (ash 1 (1- bits))))))))))
1547 1548 1549 1550 1551 1552 1553 1554
      (eql
       (assert (= (length type) 2))
       (cadr type))
      (member
       (assert (cdr type))
       (random-from-seq (cdr type)))
      ((vector)
       (let ((etype-spec (if (cdr type) (cadr type) '*))
sds's avatar
sds committed
1555 1556
             (size-spec (if (cddr type) (caddr type) '*)))
         (make-random-vector etype-spec size-spec)))
1557 1558
      ((simple-vector)
       (let ((size-spec (if (cdr type) (cadr type) '*)))
sds's avatar
sds committed
1559
         (make-random-vector t size-spec :simple t)))
1560 1561
      ((array simple-array)
       (let ((etype-spec (if (cdr type) (cadr type) '*))
sds's avatar
sds committed
1562 1563
             (size-spec (if (cddr type) (caddr type) '*)))
         (make-random-array etype-spec size-spec :simple (eql (car type) 'simple-array))))
1564 1565
      ((string simple-string)
       (let ((size-spec (if (cdr type) (cadr type) '*)))
sds's avatar
sds committed
1566
         (make-random-string size-spec :simple (eql (car type) 'simple-string))))
1567 1568
      ((base-string simple-base-string)
       (let ((size-spec (if (cdr type) (cadr type) '*)))
sds's avatar
sds committed
1569
         (make-random-vector 'base-char size-spec :simple (eql (car type) 'simple-base-string))))
1570 1571
      ((bit-vector simple-bit-vector)
       (let ((size-spec (if (cdr type) (cadr type) '*)))
sds's avatar
sds committed
1572
         (make-random-vector 'bit size-spec :simple (eql (car type) 'simple-bit-vector))))
1573
      ((cons)
1574
       (cons (make-random-element-of-type (if (cdr type) (cadr type) t))
sds's avatar
sds committed
1575
             (make-random-element-of-type (if (cddr type) (caddr type) t))))
1576 1577
      ((complex)
       (cond
sds's avatar
sds committed
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
        ((null (cdr type))
         (make-random-element-of-type 'complex))
        (t
         (assert (null (cddr type)))
         (let ((etype (cadr type)))
           (loop for v1 = (make-random-element-of-type etype)
                 for v2 = (make-random-element-of-type etype)
                 for c = (complex v1 v2)
                 when (typep c type)
                 return c)))))
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
      )))
|#

(defmethod make-random-element-of-type ((type class))
  (make-random-element-of-type (class-name type)))

(defmethod make-random-element-of-type ((type (eql 'bit))) (random 2))
(defmethod make-random-element-of-type ((type (eql 'boolean)))
  (random-from-seq #(nil t)))
(defmethod make-random-element-of-type ((type (eql 'symbol)))
  (random-from-seq #(nil t a b c :a :b :c |z| foo |foo| car)))
(defmethod make-random-element-of-type ((type (eql 'keyword)))
  (random-from-seq #(:a :b :c :d :e :f :g :h :i :j)))
(defmethod make-random-element-of-type ((type (eql 'unsigned-byte)))
  (random-from-interval (1+ (ash 1 (random *maximum-random-int-bits*))) 0))
(defmethod make-random-element-of-type ((type (eql 'signed-byte)))
  (random-from-interval
   (1+ (ash 1 (random *maximum-random-int-bits*)))
   (- (ash 1 (random *maximum-random-int-bits*)))))
(defmethod make-random-element-of-type ((type (eql 'rational)))
  (make-random-rational))
(defmethod make-random-element-of-type ((type (eql 'ratio)))
  (let ((r 0))
    (loop do (setq r (make-random-element-of-type 'rational))
sds's avatar
sds committed
1612
          while (integerp r))
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
    r))
(defmethod make-random-element-of-type ((type (eql 'integer)))
  (let ((x (ash 1 (random *maximum-random-int-bits*))))
    (random-from-interval (1+ x) (- x))))
(defmethod make-random-element-of-type ((type (eql 'float)))
  (make-random-element-of-type
   (random-from-seq #(short-float single-float double-float long-float))))
(defmethod make-random-element-of-type ((type (eql 'real)))
  (make-random-element-of-type (random-from-seq #(integer rational float))))
(defmethod make-random-element-of-type ((type (eql 'number)))
  (make-random-element-of-type (random-from-seq #(integer rational float #-ecl complex))))
(defmethod make-random-element-of-type ((type (eql 'bit-vector)))
  (make-random-vector 'bit '*))
(defmethod make-random-element-of-type ((type (eql 'simple-bit-vector)))
  (make-random-vector 'bit '* :simple t))
(defmethod make-random-element-of-type ((type (eql 'vector)))
  (make-random-vector '* '*))
(defmethod make-random-element-of-type ((type (eql 'simple-vector)))
  (make-random-vector 't '* :simple t))
(defmethod make-random-element-of-type ((type (eql 'array)))
  (make-random-array '* '*))
(defmethod make-random-element-of-type ((type (eql 'simple-array)))
  (make-random-array '* '* :simple t))
(defmethod make-random-element-of-type ((type (eql 'string)))
  (make-random-string '*))
(defmethod make-random-element-of-type ((type (eql 'simple-string)))
  (make-random-string '* :simple t))
(defmethod make-random-element-of-type ((type (eql 'base-string)))
  (make-random-vector 'base-char '*))
(defmethod make-random-element-of-type ((type (eql 'simple-base-string)))
  (make-random-vector 'base-char '* :simple t))
(defmethod make-random-element-of-type ((type (eql 'character)))
  (make-random-character))
(defmethod make-random-element-of-type ((type (eql 'extended-char)))
  (loop for x = (make-random-character)
sds's avatar
sds committed
1648
        when (typep x 'extended-char) return x))
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
(defmethod make-random-element-of-type ((type (eql 'null))) nil)
(defmethod make-random-element-of-type ((type (eql 'fixnum)))
  (random-from-interval (1+ most-positive-fixnum) most-negative-fixnum))
(defmethod make-random-element-of-type ((type (eql 'complex)))
  (make-random-element-of-type '(complex real)))
(defmethod make-random-element-of-type ((type (eql 'cons)))
  (make-random-element-of-type '(cons t t)))
(defmethod make-random-element-of-type ((type (eql 'list)))
  ;; Should modify this to allow non-proper lists?
  (let ((len (min (random 10) (random 10))))
    (loop repeat len collect (make-random-element-of-type t))))
(defmethod make-random-element-of-type ((type (eql 'sequence)))
  (make-random-element-of-type '(or list vector)))
(defmethod make-random-element-of-type ((type (eql 'function)))
  (rcase
   (5 (symbol-function (random-from-seq *cl-function-symbols*)))
   (5 (symbol-function (random-from-seq *cl-accessor-symbols*)))
   (1 #'(lambda (x) (cons x x)))
   (1 (eval '#'(lambda (x) (cons x x))))))

(defmethod make-random-element-of-type ((type symbol))
  (case type
   ((single-float short-float double-float long-float)
    (make-random-element-of-type (list type)))
   ((base-char standard-char)
    (random-from-seq +standard-chars+))
   ;; Default
   ((atom t *) (make-random-element-of-type
sds's avatar
sds committed
1677 1678 1679
                (random-from-seq #(real symbol boolean integer unsigned-byte
                                        #-ecl complex character
                                        (string 1) (bit-vector 1)))))
1680 1681
   (t (call-next-method type))
   ))
1682

1683 1684 1685
(defun make-random-character ()
  (loop
   when (rcase
pfdietz's avatar
pfdietz committed
1686 1687 1688 1689 1690
         (3 (random-from-seq +standard-chars+))
         (3 (code-char (random (min 256 char-code-limit))))
         (1 (code-char (random (min (ash 1 16) char-code-limit))))
         (1 (code-char (random (min (ash 1 24) char-code-limit))))
         (1 (code-char (random char-code-limit))))
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
   return it))

(defun make-random-array-element-type ()
  ;; Create random types for array elements
  (let ((bits 40))
    (rcase
     (2 t)
     (1 'symbol)
     (1 `(unsigned-byte ,(1+ (random bits))))
     (1 `(signed-byte ,(1+ (random bits))))
     (1 'character)
     (1 'base-char)
     (1 'bit)
     (1 (random-from-seq #(short-float single-float double-float long-float))))))

(defun make-random-vector (etype-spec size-spec &key simple)
  (let* ((etype (if (eql etype-spec '*)
pfdietz's avatar
pfdietz committed
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
                    (make-random-array-element-type)
                  etype-spec))
         (size (if (eql size-spec '*)
                   (random (ash 1 (+ 2 (random 8))))
                 size-spec))
         (displaced? (and (not simple) (coin 4)))
         (displaced-size (+ size (random (max 6 size))))
         (displacement (random (1+ (- displaced-size size))))
         (adjustable (and (not simple) (coin 3)))
         (fill-pointer (and (not simple)
                            (rcase (3 nil) (1 t) (1 (random (1+ size)))))))
1719 1720
    (assert (<= size 1000000))
    (if displaced?
pfdietz's avatar
pfdietz committed
1721 1722 1723 1724 1725 1726 1727
        (let ((displaced-vector (make-array displaced-size :element-type etype
                                            :initial-contents (loop repeat displaced-size
                                                                    collect (make-random-element-of-type etype)))))
          (make-array size :element-type etype :adjustable adjustable
                      :fill-pointer fill-pointer
                      :displaced-to displaced-vector
                      :displaced-index-offset displacement))
1728
      (make-array size
pfdietz's avatar
pfdietz committed
1729 1730 1731 1732 1733 1734
                  :element-type etype
                  :initial-contents (loop repeat size
                                          collect (make-random-element-of-type etype))
                  :adjustable adjustable
                  :fill-pointer fill-pointer
                  ))))
1735 1736 1737 1738 1739 1740 1741

(defun make-random-array (etype-spec dim-specs &key simple)
  (when (eql dim-specs '*)
    (setq dim-specs (random 10)))
  (when (numberp dim-specs)
    (setq dim-specs (make-list dim-specs :initial-element '*)))
  (let* ((etype (if (eql etype-spec '*) t etype-spec))
pfdietz's avatar
pfdietz committed
1742 1743 1744 1745 1746
         (rank (length dim-specs))
         (dims (loop for dim in dim-specs
                     collect (if (eql dim '*)
                                 (1+ (random (ash 1 (floor 9 rank))))
                               dim))))
1747 1748 1749
    (assert (<= (reduce '* dims :initial-value 1) 1000000))
    (assert (<= (reduce 'max dims :initial-value 1) 1000000))
    (make-array dims
pfdietz's avatar
pfdietz committed
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
                :element-type etype
                :initial-contents
                (labels ((%init (dims)
                                (if (null dims)
                                    (make-random-element-of-type etype)
                                  (loop repeat (car dims)
                                        collect (%init (cdr dims))))))
                  (%init dims))
                :adjustable (and (not simple) (coin))
                ;; Do displacements later
                )))
1761 1762 1763 1764 1765 1766 1767 1768

(defun most-negative-float (float-type-symbol)
  (ecase float-type-symbol
    (short-float most-negative-short-float)
    (single-float most-negative-single-float)
    (double-float most-negative-double-float)
    (long-float most-negative-long-float)
    (float (min most-negative-short-float most-negative-single-float
pfdietz's avatar
pfdietz committed
1769
                most-negative-double-float most-negative-long-float))))
1770 1771 1772 1773 1774 1775 1776 1777

(defun most-positive-float (float-type-symbol)
  (ecase float-type-symbol
    (short-float most-positive-short-float)
    (single-float most-positive-single-float)
    (double-float most-positive-double-float)
    (long-float most-positive-long-float)
    (float (max most-positive-short-float most-positive-single-float
pfdietz's avatar
pfdietz committed
1778
                most-positive-double-float most-positive-long-float))))
1779

1780
(defun make-optimized-lambda-form (form vars var-types opt-decls)
1781
  `(lambda ,vars
1782
     ,@(mapcar #'(lambda (tp var) `(declare (type ,tp ,var)))
pfdietz's avatar
pfdietz committed
1783
               var-types vars)
1784 1785
     (declare (ignorable ,@vars))
     #+cmu (declare (optimize (extensions:inhibit-warnings 3)))
1786
     (declare (optimize ,@opt-decls))
1787 1788
     ,form))

1789
(defun make-unoptimized-lambda-form (form vars var-types opt-decls)
1790 1791
  (declare (ignore var-types))
  `(lambda ,vars
1792 1793
     (declare (notinline ,@(fn-symbols-in-form form)))
     #+cmu (declare (optimize (extensions:inhibit-warnings 3)))
1794
     (declare (optimize ,@opt-decls))
1795 1796
     ,form))

1797 1798 1799
(defvar *compile-using-defun*
  #-(or allegro lispworks) nil
  #+(or allegro lispworks) t)
pfdietz's avatar
pfdietz committed
1800 1801 1802 1803 1804

(defvar *compile-using-defgeneric* nil
  "If true and *COMPILE-USING-DEFUN* is false, then build a defgeneric form
   for the function and compile that.")

1805 1806 1807
(defvar *name-to-use-in-optimized-defun* 'dummy-fn-name1)
(defvar *name-to-use-in-unoptimized-defun* 'dummy-fn-name2)

1808
(defun test-int-form (form vars var-types vals-list opt-decls-1 opt-decls-2)
1809 1810 1811 1812
  ;; Try to compile FORM with associated VARS, and if it compiles
  ;; check for equality of the two compiled forms.
  ;; Return a non-nil list of details if a problem is found,
  ;; NIL otherwise.
1813
  (let ((optimized-fn-src (make-optimized-lambda-form form vars var-types opt-decls-1))
pfdietz's avatar
pfdietz committed
1814
        (unoptimized-fn-src (make-unoptimized-lambda-form form vars var-types opt-decls-2)))
1815
    (setq *int-form-vals* nil
pfdietz's avatar
pfdietz committed
1816 1817
          *optimized-fn-src* optimized-fn-src
          *unoptimized-fn-src* unoptimized-fn-src)
1818
    (flet ((%compile
pfdietz's avatar
pfdietz committed
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
            (lambda-form opt-defun-name)
            (cl:handler-bind
             (#+sbcl (sb-ext::compiler-note #'muffle-warning)
                     (warning #'muffle-warning)
                     ((or error serious-condition)
                      #'(lambda (c)
                                (format t "Compilation failure~%~A~%"
                                        (format nil "~S" form))
                                (finish-output *standard-output*)
                                (return-from test-int-form
                                  (list (list :vars vars
                                              :form form
                                              :var-types var-types
                                              :vals (first vals-list)
                                              :lambda-form lambda-form
                                              :decls1 opt-decls-1
                                              :decls2 opt-decls-2
                                              :compiler-condition
                                              (with-output-to-string
                                                (s)
                                                (prin1 c s))))))))
             (let ((start-time (get-universal-time))
                   (clf (cdr lambda-form)))
               (prog1
                   (cond
                    (*compile-using-defun*
                     (fmakunbound opt-defun-name)
                     (eval `(defun ,opt-defun-name ,@clf))
                     (compile opt-defun-name)
                     (symbol-function opt-defun-name))
                    (*compile-using-defgeneric*
                     (fmakunbound opt-defun-name)
                     (eval `(defgeneric ,opt-defun-name ,(car clf)))
                     (eval `(defmethod ,opt-defun-name,(mapcar #'(lambda (name) `(,name integer)) (car clf))
                              ,@(cdr clf)))
                     (compile opt-defun-name)
                     (symbol-function opt-defun-name))
                    (t (compile nil lambda-form)))
                 (let* ((stop-time (get-universal-time))
                        (total-time (- stop-time start-time)))
                   (when (> total-time *max-compile-time*)
                     (setf *max-compile-time* total-time)
                     (setf *max-compile-term* lambda-form)))
                 ;; #+:ecl (si:gc t)
                 )))))
1864
      (let ((optimized-compiled-fn (%compile optimized-fn-src
pfdietz's avatar
pfdietz committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
                                             *name-to-use-in-optimized-defun*))
            (unoptimized-compiled-fn
             (if *compile-unoptimized-form*
                 (%compile unoptimized-fn-src *name-to-use-in-unoptimized-defun*)
               (eval `(function ,unoptimized-fn-src)))))
        (declare (type function optimized-compiled-fn unoptimized-compiled-fn))
        (dolist (vals vals-list)
          (setq *int-form-vals* vals)
          (flet ((%eval-error
                  (kind)
                  (let ((*print-circle* t))
                    (format t "~A~%" (format nil "~S" form)))
                  (finish-output *standard-output*)
                  (return
                   (list (list :vars vars
                               :vals vals
                               :form form
                               :var-types var-types
                               :decls1 opt-decls-1
                               :decls2 opt-decls-2
                               :optimized-lambda-form optimized-fn-src
                               :unoptimized-lambda-form unoptimized-fn-src
                               :kind kind)))))
sds's avatar
sds committed
1888

pfdietz's avatar
pfdietz committed
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
            (let ((unopt-result
                   (cl-handler-case
                    (cl-handler-bind
                     (#+sbcl (sb-ext::compiler-note #'muffle-warning)
                             (warning #'muffle-warning))
                     (identity ;; multiple-value-list
                      (apply unoptimized-compiled-fn vals)))
                    ((or error serious-condition)
                     (c)
                     (%eval-error (list :unoptimized-form-error
                                        (with-output-to-string
                                          (s) (prin1 c s)))))))
                  (opt-result
                   (cl-handler-case
                    (cl-handler-bind
                     (#+sbcl (sb-ext::compiler-note #'muffle-warning)
                             (warning #'muffle-warning))
                     (identity ;; multiple-value-list
                      (apply optimized-compiled-fn vals)))
                    ((or error serious-condition)
                     (c)
                     (%eval-error (list :optimized-form-error
                                        (with-output-to-string
                                          (s) (prin1 c s))))))))
              (if (equal opt-result unopt-result)
                  nil
                (progn
                  (format t "Different results: ~A, ~A~%"
                          opt-result unopt-result)
                  (setq *opt-result* opt-result
                        *unopt-result* unopt-result)